From bf0ca67f2dc97d3f8a5830a958f07343cf9a03ce Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 15 Nov 2024 16:45:12 +0800 Subject: [PATCH 01/29] =?UTF-8?q?=E6=8F=90=E9=86=92=E4=BB=A3=E7=90=86?= =?UTF-8?q?=E8=A7=A3=E8=80=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: fengyang --- bundle.json | 4 +- frameworks/ans/BUILD.gn | 5 - frameworks/cj/ffi/BUILD.gn | 5 +- .../core/include/ans_manager_interface.h | 112 +- frameworks/core/include/ans_manager_proxy.h | 112 +- frameworks/core/include/ans_manager_stub.h | 126 +- frameworks/core/include/ans_notification.h | 59 +- frameworks/core/src/ans_notification.cpp | 100 - .../manager/ans_manager_proxy_reminder.cpp | 494 +- .../core/src/manager/ans_manager_stub.cpp | 392 +- .../src/manager/ans_manager_stub_invalid.cpp | 82 +- frameworks/js/napi/BUILD.gn | 5 +- frameworks/js/napi/src/manager/BUILD.gn | 5 +- frameworks/js/napi/src/reminder/BUILD.gn | 10 +- frameworks/js/napi/src/reminder/publish.cpp | 49 +- frameworks/js/napi/src/subscribe/BUILD.gn | 5 +- frameworks/reminder/BUILD.gn | 112 + frameworks/reminder/IReminderManager.idl | 25 + frameworks/reminder/idl-gen:Zone.Identifier | 0 .../{ans => reminder}/src/reminder_helper.cpp | 30 +- .../src/reminder_request.cpp | 2 +- .../src/reminder_request_alarm.cpp | 0 .../src/reminder_request_calendar.cpp | 10 +- .../reminder/src/reminder_request_client.cpp | 210 + .../reminder/src/reminder_request_client.h | 129 + .../src/reminder_request_timer.cpp | 0 interfaces/inner_api/reminder_helper.h | 8 +- .../inner_api/reminder_request_calendar.h | 6 +- interfaces/ndk/BUILD.gn | 5 +- notification.gni | 2 + services/ans/BUILD.gn | 1 + .../include/advanced_notification_service.h | 112 +- .../advanced_notification_service_ability.h | 2 +- .../include/reminder_config_change_observer.h | 70 +- services/ans/include/reminder_data_manager.h | 1526 +++--- services/ans/include/reminder_event_manager.h | 176 +- services/ans/include/reminder_store.h | 190 +- .../ans/include/reminder_store_strategy.h | 386 +- services/ans/include/reminder_table.h | 544 +-- services/ans/include/reminder_table_old.h | 478 +- services/ans/include/reminder_timer_info.h | 146 +- ...advanced_notification_reminder_service.cpp | 373 +- .../ans/src/advanced_notification_service.cpp | 2 +- .../advanced_notification_service_ability.cpp | 4 +- .../src/reminder_config_change_observer.cpp | 72 +- services/ans/src/reminder_data_manager.cpp | 4146 ++++++++--------- .../ans/src/reminder_data_manager_inner.cpp | 312 +- services/ans/src/reminder_event_manager.cpp | 722 +-- services/ans/src/reminder_store.cpp | 1630 +++---- services/ans/src/reminder_table.cpp | 326 +- services/ans/src/reminder_table_old.cpp | 294 +- services/ans/src/reminder_timer_info.cpp | 88 +- services/reminder/BUILD.gn | 295 ++ .../include/reminder_access_token_helper.h | 34 + .../include/reminder_bundle_manager_helper.h | 85 + .../include/reminder_config_change_observer.h | 42 + .../reminder/include/reminder_data_manager.h | 752 +++ .../reminder/include/reminder_event_manager.h | 102 + .../reminder_os_account_manager_helper.h | 55 + services/reminder/include/reminder_service.h | 150 + .../include/reminder_service_ability.h | 61 + services/reminder/include/reminder_store.h | 109 + .../include/reminder_store_strategy.h | 193 + services/reminder/include/reminder_table.h | 272 ++ .../reminder/include/reminder_table_old.h | 239 + .../reminder/include/reminder_timer_info.h | 88 + .../reminder/include/remote_death_recipient.h | 61 + .../src/reminder_access_token_helper.cpp | 46 + .../src/reminder_bundle_manager_helper.cpp | 151 + .../src/reminder_config_change_observer.cpp | 41 + .../reminder/src/reminder_data_manager.cpp | 2035 ++++++++ .../src/reminder_data_manager_inner.cpp | 166 + .../reminder/src/reminder_event_manager.cpp | 352 ++ .../src/reminder_notification_inline.cpp | 72 + .../reminder_os_account_manager_helper.cpp | 49 + services/reminder/src/reminder_service.cpp | 325 ++ .../reminder/src/reminder_service_ability.cpp | 136 + services/reminder/src/reminder_store.cpp | 809 ++++ .../reminder/src/reminder_store_strategy.cpp | 649 +++ services/reminder/src/reminder_table.cpp | 178 + services/reminder/src/reminder_table_old.cpp | 157 + services/reminder/src/reminder_timer_info.cpp | 51 + tools/dump/BUILD.gn | 5 +- 83 files changed, 14776 insertions(+), 6688 deletions(-) create mode 100644 frameworks/reminder/BUILD.gn create mode 100644 frameworks/reminder/IReminderManager.idl create mode 100644 frameworks/reminder/idl-gen:Zone.Identifier rename frameworks/{ans => reminder}/src/reminder_helper.cpp (58%) rename frameworks/{ans => reminder}/src/reminder_request.cpp (99%) rename frameworks/{ans => reminder}/src/reminder_request_alarm.cpp (100%) rename frameworks/{ans => reminder}/src/reminder_request_calendar.cpp (98%) create mode 100644 frameworks/reminder/src/reminder_request_client.cpp create mode 100644 frameworks/reminder/src/reminder_request_client.h rename frameworks/{ans => reminder}/src/reminder_request_timer.cpp (100%) create mode 100644 services/reminder/BUILD.gn create mode 100644 services/reminder/include/reminder_access_token_helper.h create mode 100644 services/reminder/include/reminder_bundle_manager_helper.h create mode 100644 services/reminder/include/reminder_config_change_observer.h create mode 100644 services/reminder/include/reminder_data_manager.h create mode 100644 services/reminder/include/reminder_event_manager.h create mode 100644 services/reminder/include/reminder_os_account_manager_helper.h create mode 100644 services/reminder/include/reminder_service.h create mode 100644 services/reminder/include/reminder_service_ability.h create mode 100644 services/reminder/include/reminder_store.h create mode 100644 services/reminder/include/reminder_store_strategy.h create mode 100644 services/reminder/include/reminder_table.h create mode 100644 services/reminder/include/reminder_table_old.h create mode 100644 services/reminder/include/reminder_timer_info.h create mode 100644 services/reminder/include/remote_death_recipient.h create mode 100644 services/reminder/src/reminder_access_token_helper.cpp create mode 100644 services/reminder/src/reminder_bundle_manager_helper.cpp create mode 100644 services/reminder/src/reminder_config_change_observer.cpp create mode 100644 services/reminder/src/reminder_data_manager.cpp create mode 100644 services/reminder/src/reminder_data_manager_inner.cpp create mode 100644 services/reminder/src/reminder_event_manager.cpp create mode 100644 services/reminder/src/reminder_notification_inline.cpp create mode 100644 services/reminder/src/reminder_os_account_manager_helper.cpp create mode 100644 services/reminder/src/reminder_service.cpp create mode 100644 services/reminder/src/reminder_service_ability.cpp create mode 100644 services/reminder/src/reminder_store.cpp create mode 100644 services/reminder/src/reminder_store_strategy.cpp create mode 100644 services/reminder/src/reminder_table.cpp create mode 100644 services/reminder/src/reminder_table_old.cpp create mode 100644 services/reminder/src/reminder_timer_info.cpp diff --git a/bundle.json b/bundle.json index f87567a63..b896cc607 100644 --- a/bundle.json +++ b/bundle.json @@ -106,11 +106,13 @@ "//base/notification/distributed_notification_service/frameworks/ans:ans_client", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_notification", "//base/notification/distributed_notification_service/frameworks/js/napi:napi_reminder", - "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification" + "//base/notification/distributed_notification_service/interfaces/ndk:ohnotification", + "//base/notification/distributed_notification_service/frameworks/reminder:reminder_client" ], "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", "//base/notification/distributed_notification_service/services:ans_service", + "//base/notification/distributed_notification_service/services/reminder:reminder_service", "//base/notification/distributed_notification_service/tools:tools_shell" ] }, diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 837a2878d..2cd10c2ae 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -112,11 +112,6 @@ ohos_shared_library("ans_innerkits") { "${frameworks_module_ans_path}/src/notification_user_input.cpp", "${frameworks_module_ans_path}/src/push_callback_stub.cpp", "${frameworks_module_ans_path}/src/push_promise_callback.cpp", - "${frameworks_module_ans_path}/src/reminder_helper.cpp", - "${frameworks_module_ans_path}/src/reminder_request.cpp", - "${frameworks_module_ans_path}/src/reminder_request_alarm.cpp", - "${frameworks_module_ans_path}/src/reminder_request_calendar.cpp", - "${frameworks_module_ans_path}/src/reminder_request_timer.cpp", ] public_configs = [ ":ans_innerkits_public_config" ] diff --git a/frameworks/cj/ffi/BUILD.gn b/frameworks/cj/ffi/BUILD.gn index ee353be72..9447c9c9c 100644 --- a/frameworks/cj/ffi/BUILD.gn +++ b/frameworks/cj/ffi/BUILD.gn @@ -38,7 +38,10 @@ ohos_shared_library("cj_notification_manager_ffi") { use_exceptions = true if (product_name != "ohos-sdk") { - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", "ability_base:zuri", diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index 2a1ae2880..e503d8d65 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -652,62 +652,62 @@ public: */ virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) = 0; - /** - * @brief Publishes a reminder notification. - * - * @param reminder Identifies the reminder notification request that needs to be published. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode PublishReminder(sptr &reminder) = 0; - - /** - * @brief Cancel a reminder notifications. - * - * @param reminderId Identifies the reminders id that needs to be canceled. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode CancelReminder(const int32_t reminderId) = 0; - - /** - * @brief Get all valid reminder notifications. - * - * @param reminders Identifies the list of all valid notifications. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode GetValidReminders(std::vector> &reminders) = 0; - - /** - * @brief Cancel all reminder notifications. - * - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode CancelAllReminders() = 0; - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) = 0; - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode DelExcludeDates(const int32_t reminderId) = 0; - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) = 0; + // /** + // * @brief Publishes a reminder notification. + // * + // * @param reminder Identifies the reminder notification request that needs to be published. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode PublishReminder(sptr &reminder) = 0; + + // /** + // * @brief Cancel a reminder notifications. + // * + // * @param reminderId Identifies the reminders id that needs to be canceled. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode CancelReminder(const int32_t reminderId) = 0; + + // /** + // * @brief Get all valid reminder notifications. + // * + // * @param reminders Identifies the list of all valid notifications. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode GetValidReminders(std::vector> &reminders) = 0; + + // /** + // * @brief Cancel all reminder notifications. + // * + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode CancelAllReminders() = 0; + + // /** + // * @brief Add exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param date exclude date + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) = 0; + + // /** + // * @brief Clear exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode DelExcludeDates(const int32_t reminderId) = 0; + + // /** + // * @brief Get exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param dates exclude dates + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) = 0; /** * @brief Checks whether this device is support template. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 2c6afcea9..db8df7d94 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -649,62 +649,62 @@ public: */ ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; - /** - * @brief Publishes a reminder notification. - * - * @param reminder Identifies the reminder notification request that needs to be published. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode PublishReminder(sptr &reminder) override; - - /** - * @brief Cancel a reminder notifications. - * - * @param reminderId Identifies the reminders id that needs to be canceled. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode CancelReminder(const int32_t reminderId) override; - - /** - * @brief Get all valid reminder notifications. - * - * @param reminders Identifies the list of all valid notifications. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetValidReminders(std::vector> &reminders) override; - - /** - * @brief Cancel all reminder notifications. - * - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode CancelAllReminders() override; - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode DelExcludeDates(const int32_t reminderId) override; - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; + // /** + // * @brief Publishes a reminder notification. + // * + // * @param reminder Identifies the reminder notification request that needs to be published. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode PublishReminder(sptr &reminder) override; + + // /** + // * @brief Cancel a reminder notifications. + // * + // * @param reminderId Identifies the reminders id that needs to be canceled. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode CancelReminder(const int32_t reminderId) override; + + // /** + // * @brief Get all valid reminder notifications. + // * + // * @param reminders Identifies the list of all valid notifications. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode GetValidReminders(std::vector> &reminders) override; + + // /** + // * @brief Cancel all reminder notifications. + // * + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode CancelAllReminders() override; + + // /** + // * @brief Add exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param date exclude date + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; + + // /** + // * @brief Clear exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode DelExcludeDates(const int32_t reminderId) override; + + // /** + // * @brief Get exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param dates exclude dates + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; /** * @brief Checks Whether the specified users is allowed to publish notifications. diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index bdd0e5bbd..51650a776 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -642,62 +642,62 @@ public: */ virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; - /** - * @brief Publishes a reminder notification. - * - * @param reminder Identifies the reminder notification request that needs to be published. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode PublishReminder(sptr &reminder) override; - - /** - * @brief Cancel a reminder notifications. - * - * @param reminderId Identifies the reminders id that needs to be canceled. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode CancelReminder(const int32_t reminderId) override; - - /** - * @brief Get all valid reminder notifications. - * - * @param reminders Identifies the list of all valid notifications. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode GetValidReminders(std::vector> &reminders) override; - - /** - * @brief Cancel all reminder notifications. - * - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode CancelAllReminders() override; - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode DelExcludeDates(const int32_t reminderId) override; - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; + // /** + // * @brief Publishes a reminder notification. + // * + // * @param reminder Identifies the reminder notification request that needs to be published. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode PublishReminder(sptr &reminder) override; + + // /** + // * @brief Cancel a reminder notifications. + // * + // * @param reminderId Identifies the reminders id that needs to be canceled. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode CancelReminder(const int32_t reminderId) override; + + // /** + // * @brief Get all valid reminder notifications. + // * + // * @param reminders Identifies the list of all valid notifications. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode GetValidReminders(std::vector> &reminders) override; + + // /** + // * @brief Cancel all reminder notifications. + // * + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode CancelAllReminders() override; + + // /** + // * @brief Add exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param date exclude date + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; + + // /** + // * @brief Clear exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode DelExcludeDates(const int32_t reminderId) override; + + // /** + // * @brief Get exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param dates exclude dates + // * @return Returns ERR_OK on success, others on failure. + // */ + // virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; /** * @brief Checks whether this device is support template. @@ -1012,13 +1012,13 @@ private: ErrCode HandleGetDeviceRemindType(MessageParcel &data, MessageParcel &reply); ErrCode HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); - ErrCode HandlePublishReminder(MessageParcel &data, MessageParcel &reply); - ErrCode HandleCancelReminder(MessageParcel &data, MessageParcel &reply); - ErrCode HandleGetValidReminders(MessageParcel &data, MessageParcel &reply); - ErrCode HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply); - ErrCode HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply); - ErrCode HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply); - ErrCode HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply); + // ErrCode HandlePublishReminder(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleCancelReminder(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleGetValidReminders(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply); + // ErrCode HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialUserAllowedNotifyByUser(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetNotificationsEnabledByUser(MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index 20287108d..cb70a6da4 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -876,64 +876,7 @@ public: * @brief try to reconnect ans SA when SA manager OnAddSystemAbility called. */ void Reconnect(); - - /** - * @brief Publishes a scheduled reminder. - * - * @param reminder Indicates a reminder. - * @return Returns publish result. - */ - ErrCode PublishReminder(ReminderRequest &reminder); - - /** - * @brief Cancels a specified reminder. - * - * @param reminderId Indicates reminder Id. - * @return Returns cancel result. - */ - ErrCode CancelReminder(const int32_t reminderId); - - /** - * @brief Cancels all reminders of current third part application. - * - * @return Returns cancel result. - */ - ErrCode CancelAllReminders(); - - /** - * @brief Obtains all valid reminder notifications set by the current application. - * - * @param[out] validReminders Indicates the vector to store the result. - * @return Returns get valid reminders result. - */ - ErrCode GetValidReminders(std::vector> &validReminders); - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date); - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode DelExcludeDates(const int32_t reminderId); - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates); - + /** * @brief Checks whether this application has permission to publish notifications under the user. * diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 00fb37e7e..5a141e431 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -24,9 +24,6 @@ #include "iservice_registry.h" #include "notification_button_option.h" #include "notification_local_live_view_subscriber.h" -#include "reminder_request_alarm.h" -#include "reminder_request_calendar.h" -#include "reminder_request_timer.h" #include "system_ability_definition.h" #include "unique_fd.h" @@ -1340,103 +1337,6 @@ void AnsNotification::Reconnect() } } -ErrCode AnsNotification::PublishReminder(ReminderRequest &reminder) -{ - sptr tarReminder = nullptr; - switch (reminder.GetReminderType()) { - case (ReminderRequest::ReminderType::TIMER): { - ANSR_LOGI("Publish timer"); - ReminderRequestTimer &timer = (ReminderRequestTimer &)reminder; - tarReminder = new (std::nothrow) ReminderRequestTimer(timer); - break; - } - case (ReminderRequest::ReminderType::ALARM): { - ANSR_LOGI("Publish alarm"); - ReminderRequestAlarm &alarm = (ReminderRequestAlarm &)reminder; - tarReminder = new (std::nothrow) ReminderRequestAlarm(alarm); - break; - } - case (ReminderRequest::ReminderType::CALENDAR): { - ANSR_LOGI("Publish calendar"); - ReminderRequestCalendar &calendar = (ReminderRequestCalendar &)reminder; - tarReminder = new (std::nothrow) ReminderRequestCalendar(calendar); - break; - } - default: { - ANSR_LOGW("PublishReminder fail."); - return ERR_ANS_INVALID_PARAM; - } - } - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - ErrCode code = proxy->PublishReminder(tarReminder); - reminder.SetReminderId(tarReminder->GetReminderId()); - return code; -} - -ErrCode AnsNotification::CancelReminder(const int32_t reminderId) -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->CancelReminder(reminderId); -} - -ErrCode AnsNotification::CancelAllReminders() -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->CancelAllReminders(); -} - -ErrCode AnsNotification::GetValidReminders(std::vector> &validReminders) -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->GetValidReminders(validReminders); -} - -ErrCode AnsNotification::AddExcludeDate(const int32_t reminderId, const uint64_t date) -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->AddExcludeDate(reminderId, date); -} - -ErrCode AnsNotification::DelExcludeDates(const int32_t reminderId) -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->DelExcludeDates(reminderId); -} - -ErrCode AnsNotification::GetExcludeDates(const int32_t reminderId, std::vector& dates) -{ - sptr proxy = GetAnsManagerProxy(); - if (!proxy) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return proxy->GetExcludeDates(reminderId, dates); -} - sptr AnsNotification::GetAnsManagerProxy() { sptr systemAbilityManager = diff --git a/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp b/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp index f5256f486..e5b32313d 100644 --- a/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp +++ b/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp @@ -30,266 +30,266 @@ namespace OHOS { namespace Notification { -ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) -{ - ANSR_LOGI("PublishReminder"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[PublishReminder] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - if (reminder == nullptr) { - ANSR_LOGW("[PublishReminder] fail: reminder is null ptr."); - return ERR_ANS_INVALID_PARAM; - } - if (!data.WriteUint8(static_cast(reminder->GetReminderType()))) { - ANSR_LOGE("[PublishReminder] fail: write reminder type failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteParcelable(reminder)) { - ANSR_LOGE("[Publish] fail: write reminder parcelable failed"); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) +// { +// ANSR_LOGI("PublishReminder"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[PublishReminder] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (reminder == nullptr) { +// ANSR_LOGW("[PublishReminder] fail: reminder is null ptr."); +// return ERR_ANS_INVALID_PARAM; +// } +// if (!data.WriteUint8(static_cast(reminder->GetReminderType()))) { +// ANSR_LOGE("[PublishReminder] fail: write reminder type failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteParcelable(reminder)) { +// ANSR_LOGE("[Publish] fail: write reminder parcelable failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::PUBLISH_REMINDER, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - int32_t reminderId = -1; - if (!reply.ReadInt32(reminderId)) { - ANSR_LOGE("[PublishReminder] fail: read reminder id failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - reminder->SetReminderId(reminderId); - ANSR_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[PublishReminder] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::PUBLISH_REMINDER, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// int32_t reminderId = -1; +// if (!reply.ReadInt32(reminderId)) { +// ANSR_LOGE("[PublishReminder] fail: read reminder id failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// reminder->SetReminderId(reminderId); +// ANSR_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[PublishReminder] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) -{ - ANSR_LOGI("[CancelReminder]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[CancelReminder] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteInt32(reminderId)) { - ANSR_LOGE("[CancelReminder] fail: write reminder id failed"); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) +// { +// ANSR_LOGI("[CancelReminder]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[CancelReminder] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteInt32(reminderId)) { +// ANSR_LOGE("[CancelReminder] fail: write reminder id failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_REMINDER, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[CancelReminder] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_REMINDER, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[CancelReminder] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::CancelAllReminders() -{ - ANSR_LOGI("[CancelAllReminders]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[CancelAllReminders] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::CancelAllReminders() +// { +// ANSR_LOGI("[CancelAllReminders]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[CancelAllReminders] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_ALL_REMINDERS, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[CancelAllReminders] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_ALL_REMINDERS, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[CancelAllReminders] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::GetValidReminders(std::vector> &reminders) -{ - ANSR_LOGI("[GetValidReminders]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[GetValidReminders] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::GetValidReminders(std::vector> &reminders) +// { +// ANSR_LOGI("[GetValidReminders]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[GetValidReminders] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - uint8_t count = 0; - if (!reply.ReadUint8(count)) { - ANSR_LOGE("[GetValidReminders] fail: read reminder count failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - ANSR_LOGD("[GetValidReminders] count=%{public}hhu", count); - reminders.clear(); - result = ReadReminders(count, reply, reminders); - if (result != ERR_OK) { - ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); - return result; - } else { - ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[GetValidReminders] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// uint8_t count = 0; +// if (!reply.ReadUint8(count)) { +// ANSR_LOGE("[GetValidReminders] fail: read reminder count failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// ANSR_LOGD("[GetValidReminders] count=%{public}hhu", count); +// reminders.clear(); +// result = ReadReminders(count, reply, reminders); +// if (result != ERR_OK) { +// ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); +// return result; +// } else { +// ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[GetValidReminders] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::AddExcludeDate(const int32_t reminderId, const uint64_t date) -{ - ANSR_LOGI("[AddExcludeDate]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[AddExcludeDate] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteInt32(reminderId)) { - ANSR_LOGE("[AddExcludeDate] fail: write reminder id failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteUint64(date)) { - ANSR_LOGE("[AddExcludeDate] fail: write exclude date failed"); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::AddExcludeDate(const int32_t reminderId, const uint64_t date) +// { +// ANSR_LOGI("[AddExcludeDate]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[AddExcludeDate] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteInt32(reminderId)) { +// ANSR_LOGE("[AddExcludeDate] fail: write reminder id failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteUint64(date)) { +// ANSR_LOGE("[AddExcludeDate] fail: write exclude date failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[AddExcludeDate] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[AddExcludeDate] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[AddExcludeDate] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[AddExcludeDate] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::DelExcludeDates(const int32_t reminderId) -{ - ANSR_LOGI("[DelExcludeDates]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[DelExcludeDates] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteInt32(reminderId)) { - ANSR_LOGE("[DelExcludeDates] fail: write reminder id failed"); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::DelExcludeDates(const int32_t reminderId) +// { +// ANSR_LOGI("[DelExcludeDates]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[DelExcludeDates] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteInt32(reminderId)) { +// ANSR_LOGE("[DelExcludeDates] fail: write reminder id failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[DelExcludeDates] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[DelExcludeDates] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[DelExcludeDates] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[DelExcludeDates] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::GetExcludeDates(const int32_t reminderId, std::vector& dates) -{ - ANSR_LOGI("[GetExcludeDates]"); - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANSR_LOGE("[GetExcludeDates] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!data.WriteInt32(reminderId)) { - ANSR_LOGE("[GetExcludeDates] fail: write reminder id failed"); - return ERR_ANS_PARCELABLE_FAILED; - } +// ErrCode AnsManagerProxy::GetExcludeDates(const int32_t reminderId, std::vector& dates) +// { +// ANSR_LOGI("[GetExcludeDates]"); +// MessageParcel data; +// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { +// ANSR_LOGE("[GetExcludeDates] fail: write interface token failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!data.WriteInt32(reminderId)) { +// ANSR_LOGE("[GetExcludeDates] fail: write reminder id failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER, option, data, reply); - if (result != ERR_OK) { - ANSR_LOGE("[GetExcludeDates] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - uint8_t count = 0; - if (!reply.ReadUint8(count)) { - ANSR_LOGE("[GetExcludeDates] fail: read exclude date count failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - ANSR_LOGD("[GetExcludeDates] count=%{public}hhu", count); - dates.clear(); - for (uint8_t i = 0; i < count; i++) { - uint64_t date = 0; - if (!reply.ReadUint64(date)) { - ANSR_LOGE("[GetExcludeDates] fail: read exclude date"); - return ERR_ANS_PARCELABLE_FAILED; - } - dates.push_back(date); - } - if (!reply.ReadInt32(result)) { - ANSR_LOGE("[GetExcludeDates] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// MessageParcel reply; +// MessageOption option = {MessageOption::TF_SYNC}; +// ErrCode result = InnerTransact(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER, option, data, reply); +// if (result != ERR_OK) { +// ANSR_LOGE("[GetExcludeDates] fail: transact ErrCode=%{public}d", result); +// return ERR_ANS_TRANSACT_FAILED; +// } +// uint8_t count = 0; +// if (!reply.ReadUint8(count)) { +// ANSR_LOGE("[GetExcludeDates] fail: read exclude date count failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// ANSR_LOGD("[GetExcludeDates] count=%{public}hhu", count); +// dates.clear(); +// for (uint8_t i = 0; i < count; i++) { +// uint64_t date = 0; +// if (!reply.ReadUint64(date)) { +// ANSR_LOGE("[GetExcludeDates] fail: read exclude date"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// dates.push_back(date); +// } +// if (!reply.ReadInt32(result)) { +// ANSR_LOGE("[GetExcludeDates] fail: read result failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } -ErrCode AnsManagerProxy::ReadReminders( - uint8_t &count, MessageParcel &reply, std::vector> &reminders) -{ - for (uint8_t i = 0; i < count; i++) { - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); - if (!reply.ReadUint8(typeInfo)) { - ANSR_LOGE("Failed to read reminder type"); - return ERR_ANS_PARCELABLE_FAILED; - } - auto reminderType = static_cast(typeInfo); - sptr reminder; - if (ReminderRequest::ReminderType::ALARM == reminderType) { - ANSR_LOGD("[GetValidReminders] alarm"); - reminder = reply.ReadParcelable(); - } else if (ReminderRequest::ReminderType::TIMER == reminderType) { - ANSR_LOGD("[GetValidReminders] timer"); - reminder = reply.ReadParcelable(); - } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { - ANSR_LOGD("[GetValidReminders] calendar"); - reminder = reply.ReadParcelable(); - } else { - ANSR_LOGW("[GetValidReminders] type=%{public}hhu", typeInfo); - return ERR_ANS_INVALID_PARAM; - } - if (!reminder) { - ANSR_LOGE("[GetValidReminders] fail: Reminder ReadParcelable failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - reminders.push_back(reminder); - } - return ERR_OK; -} +// ErrCode AnsManagerProxy::ReadReminders( +// uint8_t &count, MessageParcel &reply, std::vector> &reminders) +// { +// for (uint8_t i = 0; i < count; i++) { +// uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); +// if (!reply.ReadUint8(typeInfo)) { +// ANSR_LOGE("Failed to read reminder type"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// auto reminderType = static_cast(typeInfo); +// sptr reminder; +// if (ReminderRequest::ReminderType::ALARM == reminderType) { +// ANSR_LOGD("[GetValidReminders] alarm"); +// reminder = reply.ReadParcelable(); +// } else if (ReminderRequest::ReminderType::TIMER == reminderType) { +// ANSR_LOGD("[GetValidReminders] timer"); +// reminder = reply.ReadParcelable(); +// } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { +// ANSR_LOGD("[GetValidReminders] calendar"); +// reminder = reply.ReadParcelable(); +// } else { +// ANSR_LOGW("[GetValidReminders] type=%{public}hhu", typeInfo); +// return ERR_ANS_INVALID_PARAM; +// } +// if (!reminder) { +// ANSR_LOGE("[GetValidReminders] fail: Reminder ReadParcelable failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// reminders.push_back(reminder); +// } +// return ERR_OK; +// } } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/manager/ans_manager_stub.cpp b/frameworks/core/src/manager/ans_manager_stub.cpp index 92edc77a2..58bca12ed 100644 --- a/frameworks/core/src/manager/ans_manager_stub.cpp +++ b/frameworks/core/src/manager/ans_manager_stub.cpp @@ -287,22 +287,22 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCancelContinuousTaskNotification(data, reply); break; } - case static_cast(NotificationInterfaceCode::PUBLISH_REMINDER): { - result = HandlePublishReminder(data, reply); - break; - } - case static_cast(NotificationInterfaceCode::CANCEL_REMINDER): { - result = HandleCancelReminder(data, reply); - break; - } - case static_cast(NotificationInterfaceCode::CANCEL_ALL_REMINDERS): { - result = HandleCancelAllReminders(data, reply); - break; - } - case static_cast(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS): { - result = HandleGetValidReminders(data, reply); - break; - } + // case static_cast(NotificationInterfaceCode::PUBLISH_REMINDER): { + // result = HandlePublishReminder(data, reply); + // break; + // } + // case static_cast(NotificationInterfaceCode::CANCEL_REMINDER): { + // result = HandleCancelReminder(data, reply); + // break; + // } + // case static_cast(NotificationInterfaceCode::CANCEL_ALL_REMINDERS): { + // result = HandleCancelAllReminders(data, reply); + // break; + // } + // case static_cast(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS): { + // result = HandleGetValidReminders(data, reply); + // break; + // } case static_cast(NotificationInterfaceCode::IS_SUPPORT_TEMPLATE): { result = HandleIsSupportTemplate(data, reply); break; @@ -433,18 +433,18 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess break; } #endif - case static_cast(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER): { - result = HandleAddExcludeDate(data, reply); - break; - } - case static_cast(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER): { - result = HandleDelExcludeDates(data, reply); - break; - } - case static_cast(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER): { - result = HandleGetExcludeDates(data, reply); - break; - } + // case static_cast(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER): { + // result = HandleAddExcludeDate(data, reply); + // break; + // } + // case static_cast(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER): { + // result = HandleDelExcludeDates(data, reply); + // break; + // } + // case static_cast(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER): { + // result = HandleGetExcludeDates(data, reply); + // break; + // } case static_cast(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE): { result = HandleGetDoNotDisturbProfile(data, reply); break; @@ -1861,174 +1861,174 @@ ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &repl return ERR_OK; } -ErrCode AnsManagerStub::HandlePublishReminder(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandlePublishReminder"); - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); - if (!data.ReadUint8(typeInfo)) { - ANSR_LOGE("Failed to read reminder type"); - return ERR_ANS_PARCELABLE_FAILED; - } - ReminderRequest::ReminderType reminderType = static_cast(typeInfo); - sptr reminder; - if (ReminderRequest::ReminderType::ALARM == reminderType) { - ANSR_LOGD("Publish alarm"); - reminder = data.ReadParcelable(); - } else if (ReminderRequest::ReminderType::TIMER == reminderType) { - ANSR_LOGD("Publish timer"); - reminder = data.ReadParcelable(); - } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { - ANSR_LOGD("Publish calendar"); - reminder = data.ReadParcelable(); - } else { - ANSR_LOGE("Reminder type invalid"); - return ERR_ANS_INVALID_PARAM; - } - if (!reminder) { - ANSR_LOGE("Reminder ReadParcelable failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - ErrCode result = PublishReminder(reminder); - - if (!reply.WriteInt32(reminder->GetReminderId())) { - ANSR_LOGE("Write back reminderId failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleCancelReminder(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandleCancelReminder"); - int32_t reminderId = -1; - if (!data.ReadInt32(reminderId)) { - ANSR_LOGE("Read reminder id failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - ErrCode result = CancelReminder(reminderId); - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply) -{ - ErrCode result = CancelAllReminders(); - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandleGetValidReminders"); - std::vector> validReminders; - ErrCode result = GetValidReminders(validReminders); - - ANSR_LOGD("Write back size=%{public}zu", validReminders.size()); - if (!reply.WriteUint8(static_cast(validReminders.size()))) { - ANSR_LOGE("Write back reminder count failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - for (auto it = validReminders.begin(); it != validReminders.end(); ++it) { - sptr reminder = (*it); - uint8_t reminderType = static_cast(reminder->GetReminderType()); - ANSR_LOGD("ReminderType=%{public}d", reminderType); - if (!reply.WriteUint8(reminderType)) { - ANSR_LOGW("Write reminder type failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - if (!reply.WriteParcelable(reminder)) { - ANSR_LOGW("Write reminder parcelable failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - } - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandleAddExcludeDate"); - int32_t reminderId = -1; - if (!data.ReadInt32(reminderId)) { - ANSR_LOGE("Read reminder id failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - uint64_t date = 0; - if (!data.ReadUint64(date)) { - ANSR_LOGE("Read exclude date failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - ErrCode result = AddExcludeDate(reminderId, date); - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandleDelExcludeDates"); - int32_t reminderId = -1; - if (!data.ReadInt32(reminderId)) { - ANSR_LOGE("Read reminder id failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - ErrCode result = DelExcludeDates(reminderId); - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} - -ErrCode AnsManagerStub::HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply) -{ - ANSR_LOGI("HandleGetExcludeDates"); - int32_t reminderId = -1; - if (!data.ReadInt32(reminderId)) { - ANSR_LOGE("Read reminder id failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - std::vector dates; - ErrCode result = GetExcludeDates(reminderId, dates); - ANSR_LOGD("Write back size=%{public}zu", dates.size()); - if (!reply.WriteUint8(static_cast(dates.size()))) { - ANSR_LOGE("Write back exclude date count failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - for (const auto date : dates) { - if (!reply.WriteUint64(date)) { - ANSR_LOGW("Write exclude date failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - } - if (!reply.WriteInt32(result)) { - ANSR_LOGE("Write back result failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - return result; -} +// ErrCode AnsManagerStub::HandlePublishReminder(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandlePublishReminder"); +// uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); +// if (!data.ReadUint8(typeInfo)) { +// ANSR_LOGE("Failed to read reminder type"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// ReminderRequest::ReminderType reminderType = static_cast(typeInfo); +// sptr reminder; +// if (ReminderRequest::ReminderType::ALARM == reminderType) { +// ANSR_LOGD("Publish alarm"); +// reminder = data.ReadParcelable(); +// } else if (ReminderRequest::ReminderType::TIMER == reminderType) { +// ANSR_LOGD("Publish timer"); +// reminder = data.ReadParcelable(); +// } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { +// ANSR_LOGD("Publish calendar"); +// reminder = data.ReadParcelable(); +// } else { +// ANSR_LOGE("Reminder type invalid"); +// return ERR_ANS_INVALID_PARAM; +// } +// if (!reminder) { +// ANSR_LOGE("Reminder ReadParcelable failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// ErrCode result = PublishReminder(reminder); + +// if (!reply.WriteInt32(reminder->GetReminderId())) { +// ANSR_LOGE("Write back reminderId failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleCancelReminder(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandleCancelReminder"); +// int32_t reminderId = -1; +// if (!data.ReadInt32(reminderId)) { +// ANSR_LOGE("Read reminder id failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// ErrCode result = CancelReminder(reminderId); +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply) +// { +// ErrCode result = CancelAllReminders(); +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandleGetValidReminders"); +// std::vector> validReminders; +// ErrCode result = GetValidReminders(validReminders); + +// ANSR_LOGD("Write back size=%{public}zu", validReminders.size()); +// if (!reply.WriteUint8(static_cast(validReminders.size()))) { +// ANSR_LOGE("Write back reminder count failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// for (auto it = validReminders.begin(); it != validReminders.end(); ++it) { +// sptr reminder = (*it); +// uint8_t reminderType = static_cast(reminder->GetReminderType()); +// ANSR_LOGD("ReminderType=%{public}d", reminderType); +// if (!reply.WriteUint8(reminderType)) { +// ANSR_LOGW("Write reminder type failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// if (!reply.WriteParcelable(reminder)) { +// ANSR_LOGW("Write reminder parcelable failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// } +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandleAddExcludeDate"); +// int32_t reminderId = -1; +// if (!data.ReadInt32(reminderId)) { +// ANSR_LOGE("Read reminder id failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// uint64_t date = 0; +// if (!data.ReadUint64(date)) { +// ANSR_LOGE("Read exclude date failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// ErrCode result = AddExcludeDate(reminderId, date); +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandleDelExcludeDates"); +// int32_t reminderId = -1; +// if (!data.ReadInt32(reminderId)) { +// ANSR_LOGE("Read reminder id failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// ErrCode result = DelExcludeDates(reminderId); +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } + +// ErrCode AnsManagerStub::HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply) +// { +// ANSR_LOGI("HandleGetExcludeDates"); +// int32_t reminderId = -1; +// if (!data.ReadInt32(reminderId)) { +// ANSR_LOGE("Read reminder id failed."); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// std::vector dates; +// ErrCode result = GetExcludeDates(reminderId, dates); +// ANSR_LOGD("Write back size=%{public}zu", dates.size()); +// if (!reply.WriteUint8(static_cast(dates.size()))) { +// ANSR_LOGE("Write back exclude date count failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } + +// for (const auto date : dates) { +// if (!reply.WriteUint64(date)) { +// ANSR_LOGW("Write exclude date failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// } +// if (!reply.WriteInt32(result)) { +// ANSR_LOGE("Write back result failed"); +// return ERR_ANS_PARCELABLE_FAILED; +// } +// return result; +// } ErrCode AnsManagerStub::HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply) { diff --git a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp index e447bad8a..62d5cea3d 100644 --- a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp @@ -454,47 +454,47 @@ ErrCode AnsManagerStub::CancelContinuousTaskNotification(const std::string &labe return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::PublishReminder(sptr &reminder) -{ - ANS_LOGE("AnsManagerStub::PublishReminder called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::CancelReminder(const int32_t reminderId) -{ - ANS_LOGE("AnsManagerStub::CancelReminder called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::GetValidReminders(std::vector> &reminders) -{ - ANS_LOGE("AnsManagerStub::getValidReminders called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::CancelAllReminders() -{ - ANS_LOGE("AnsManagerStub::cancelAllReminders called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::AddExcludeDate(const int32_t reminderId, const uint64_t date) -{ - ANS_LOGE("AnsManagerStub::AddExcludeDate called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::DelExcludeDates(const int32_t reminderId) -{ - ANS_LOGE("AnsManagerStub::DelExcludeDates called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::GetExcludeDates(const int32_t reminderId, std::vector& dates) -{ - ANS_LOGE("AnsManagerStub::GetExcludeDates called!"); - return ERR_INVALID_OPERATION; -} +// ErrCode AnsManagerStub::PublishReminder(sptr &reminder) +// { +// ANS_LOGE("AnsManagerStub::PublishReminder called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::CancelReminder(const int32_t reminderId) +// { +// ANS_LOGE("AnsManagerStub::CancelReminder called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::GetValidReminders(std::vector> &reminders) +// { +// ANS_LOGE("AnsManagerStub::getValidReminders called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::CancelAllReminders() +// { +// ANS_LOGE("AnsManagerStub::cancelAllReminders called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::AddExcludeDate(const int32_t reminderId, const uint64_t date) +// { +// ANS_LOGE("AnsManagerStub::AddExcludeDate called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::DelExcludeDates(const int32_t reminderId) +// { +// ANS_LOGE("AnsManagerStub::DelExcludeDates called!"); +// return ERR_INVALID_OPERATION; +// } + +// ErrCode AnsManagerStub::GetExcludeDates(const int32_t reminderId, std::vector& dates) +// { +// ANS_LOGE("AnsManagerStub::GetExcludeDates called!"); +// return ERR_INVALID_OPERATION; +// } ErrCode AnsManagerStub::IsSupportTemplate(const std::string &templateName, bool &support) { diff --git a/frameworks/js/napi/BUILD.gn b/frameworks/js/napi/BUILD.gn index 7e11b4929..a410ebc6e 100644 --- a/frameworks/js/napi/BUILD.gn +++ b/frameworks/js/napi/BUILD.gn @@ -96,7 +96,10 @@ ohos_shared_library("notification") { "src/unsubscribe.cpp", ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", diff --git a/frameworks/js/napi/src/manager/BUILD.gn b/frameworks/js/napi/src/manager/BUILD.gn index 3cfda893b..0081f8b8b 100644 --- a/frameworks/js/napi/src/manager/BUILD.gn +++ b/frameworks/js/napi/src/manager/BUILD.gn @@ -94,7 +94,10 @@ ohos_shared_library("notificationmanager") { "napi_template.cpp", ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", diff --git a/frameworks/js/napi/src/reminder/BUILD.gn b/frameworks/js/napi/src/reminder/BUILD.gn index 3bdbdddb1..365b4d2d0 100644 --- a/frameworks/js/napi/src/reminder/BUILD.gn +++ b/frameworks/js/napi/src/reminder/BUILD.gn @@ -58,7 +58,10 @@ ohos_shared_library("reminderagent") { "reminder_common.cpp", ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", @@ -112,7 +115,10 @@ ohos_shared_library("reminderagentmanager") { "reminder_common.cpp", ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", diff --git a/frameworks/js/napi/src/reminder/publish.cpp b/frameworks/js/napi/src/reminder/publish.cpp index f45edf5d2..a1e7aa60e 100644 --- a/frameworks/js/napi/src/reminder/publish.cpp +++ b/frameworks/js/napi/src/reminder/publish.cpp @@ -53,19 +53,19 @@ struct AsyncCallbackInfo { napi_ref callback = nullptr; napi_value result = nullptr; int32_t reminderId = -1; - uint64_t excludeDate = 0; + int64_t excludeDate = 0; bool isThrow = false; NotificationNapi::NotificationConstant::SlotType inType = NotificationNapi::NotificationConstant::SlotType::CONTENT_INFORMATION; std::shared_ptr reminder = nullptr; - std::vector> validReminders; - std::vector excludeDates; + std::vector validReminders; + std::vector excludeDates; CallbackPromiseInfo info; }; struct Parameters { int32_t reminderId = -1; - uint64_t excludeDate = 0; + int64_t excludeDate = 0; int32_t errCode = ERR_OK; NotificationNapi::NotificationConstant::SlotType inType = NotificationNapi::NotificationConstant::SlotType::CONTENT_INFORMATION; @@ -632,7 +632,7 @@ void ParseButtonDataShareUpdate(const napi_env &env, ParseValueBucket(env, valuesBucketVector, buttonDataShareUpdate, BUTTON_DATA_SHARE_UPDATE_VALUE); } -void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_value &result) +void ParseActionButtons(const napi_env &env, const ReminderRequest &reminder, napi_value &result) { auto actionButtonsMap = reminder.GetActionButtons(); @@ -679,7 +679,7 @@ void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_val } } -void ParseWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value &result) +void ParseWantAgent(const napi_env &env, const ReminderRequest &reminder, napi_value &result) { // create obj napi_value wantAgentInfo = nullptr; @@ -699,7 +699,7 @@ void ParseWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value & napi_set_named_property(env, wantAgentInfo, WANT_AGENT_PARAMETERS, params); } -void ParseMaxScreenWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value &result) +void ParseMaxScreenWantAgent(const napi_env &env, const ReminderRequest &reminder, napi_value &result) { // create obj napi_value maxScreenWantAgentInfo = nullptr; @@ -713,7 +713,7 @@ void ParseMaxScreenWantAgent(const napi_env &env, ReminderRequest &reminder, nap napi_set_named_property(env, maxScreenWantAgentInfo, MAX_SCREEN_WANT_AGENT_ABILITY, info); } -napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi_value &result) +napi_value SetValidReminder(const napi_env &env,const ReminderRequest &reminder, napi_value &result) { ANSR_LOGI("enter"); napi_value value = nullptr; @@ -805,18 +805,14 @@ napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi return NotificationNapi::Common::NapiGetBoolean(env, true); } -void GetValidRemindersInner(napi_env env, const std::vector>& validReminders, napi_value& arr) +void GetValidRemindersInner(napi_env env, const std::vector& validReminders, napi_value& arr) { int32_t count = 0; napi_create_array(env, &arr); - for (auto reminder : validReminders) { - if (reminder == nullptr) { - ANSR_LOGW("reminder is null"); - continue; - } + for (auto& reminder : validReminders) { napi_value result = nullptr; napi_create_object(env, &result); - if (!SetValidReminder(env, *reminder, result)) { + if (!SetValidReminder(env, reminder, result)) { ANSR_LOGW("Set reminder object failed"); continue; } @@ -826,26 +822,23 @@ void GetValidRemindersInner(napi_env env, const std::vector>& validReminders, napi_value& arr) +void GetAllValidRemindersInner(napi_env env, const std::vector& validReminders, napi_value& arr) { int32_t count = 0; napi_create_array(env, &arr); - for (auto reminder : validReminders) { - if (reminder == nullptr) { - ANSR_LOGW("reminder is null"); - continue; - } + for (auto& reminder : validReminders) { + napi_value result = nullptr; napi_create_object(env, &result); napi_value reminderReq = nullptr; napi_create_object(env, &reminderReq); napi_set_named_property(env, result, REMINDER_INFO_REMINDER_REQ, reminderReq); - if (!SetValidReminder(env, *reminder, reminderReq)) { + if (!SetValidReminder(env, reminder, reminderReq)) { ANSR_LOGW("Set reminder object failed"); continue; } napi_value reminderId = nullptr; - napi_create_int32(env, reminder->GetReminderId(), &reminderId); + napi_create_int32(env, reminder.GetReminderId(), &reminderId); napi_set_named_property(env, result, REMINDER_INFO_REMINDER_ID, reminderId); napi_set_element(env, arr, count, result); count++; @@ -1033,8 +1026,8 @@ napi_value PublishReminderInner(napi_env env, napi_callback_info info, bool isTh ANSR_LOGI("Publish napi_create_async_work start"); AsyncCallbackInfo *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { - asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); - ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder), asynccallbackinfo->reminderId); + ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminderId); } }, [](napi_env env, napi_status status, void *data) { @@ -1045,7 +1038,7 @@ napi_value PublishReminderInner(napi_env env, napi_callback_info info, bool isTh // reminderId if (asynccallbackinfo) { if (asynccallbackinfo->info.errorCode == ERR_OK) { - napi_create_int32(env, asynccallbackinfo->reminder->GetReminderId(), &(asynccallbackinfo->result)); + napi_create_int32(env, asynccallbackinfo->reminderId, &(asynccallbackinfo->result)); } else { napi_create_int32(env, -1, &(asynccallbackinfo->result)); } @@ -1187,7 +1180,7 @@ napi_value ParseAddExcludeDateParameter(const napi_env &env, const napi_callback ReminderCommon::HandleErrCode(env, ERR_REMINDER_INVALID_PARAM); return nullptr; } - params.excludeDate = static_cast(date); + params.excludeDate = static_cast(date); return NotificationNapi::Common::NapiGetNull(env); } @@ -1335,7 +1328,7 @@ napi_value DelExcludeDates(napi_env env, napi_callback_info info) return isCallback ? NotificationNapi::Common::NapiGetNull(env) : promise; } -void GetExcludeDatesInner(napi_env env, const std::vector& dates, napi_value& arr) +void GetExcludeDatesInner(napi_env env, const std::vector& dates, napi_value& arr) { int32_t count = 0; napi_create_array(env, &arr); diff --git a/frameworks/js/napi/src/subscribe/BUILD.gn b/frameworks/js/napi/src/subscribe/BUILD.gn index 8b3e32f8c..300bffd59 100644 --- a/frameworks/js/napi/src/subscribe/BUILD.gn +++ b/frameworks/js/napi/src/subscribe/BUILD.gn @@ -73,7 +73,10 @@ ohos_shared_library("notificationsubscribe") { "napi_subscribe.cpp", ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:want", diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn new file mode 100644 index 000000000..05f61ec66 --- /dev/null +++ b/frameworks/reminder/BUILD.gn @@ -0,0 +1,112 @@ +# Copyright (c) 2024 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("//build/ohos.gni") +import("//base/notification/distributed_notification_service/notification.gni") +import("//foundation/ability/idl_tool/idl_config.gni") + +group("reminder_client") { + deps = [ ":reminder_innerkits" ] +} + +idl_interface_sources = [ + "${target_gen_dir}/reminder_manager_proxy.cpp", + "${target_gen_dir}/reminder_manager_stub.cpp", +] + +idl_gen_interface("reminder_manager_interface") { + src_idl = rebase_path("IReminderManager.idl") + dst_file = string_join(",", idl_interface_sources) + hitrace = "HITRACE_TAG_ABILITY_MANAGER" + log_domainid = "0xD003900" + log_tag = "ReminderManagerService" +} + +config("reminder_innerkits_public_config") { + visibility = [ "./../../*" ] + + include_dirs = [ + "${inner_api_path}", + "${core_path}/common/include", + "${core_path}/include", + "${target_gen_dir}", + "//third_party/json/single_include", + ] +} + +ohos_shared_library("reminder_innerkits") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + include_dirs = [ "${inner_api_path}" ] + public_configs = [ ":reminder_innerkits_public_config" ] + output_values = get_target_outputs(":reminder_manager_interface") + sources = [ + "${frameworks_module_reminder_path}/src/reminder_request_client.cpp", + "${frameworks_module_reminder_path}/src/reminder_helper.cpp", + "${frameworks_module_reminder_path}/src/reminder_request.cpp", + "${frameworks_module_reminder_path}/src/reminder_request_alarm.cpp", + "${frameworks_module_reminder_path}/src/reminder_request_calendar.cpp", + "${frameworks_module_reminder_path}/src/reminder_request_timer.cpp", + ] + sources += filter_include(output_values, [ "*.cpp" ]) + defines = [] + deps = [ + ":reminder_manager_interface", + "${frameworks_path}/ans:ans_client", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:appkit_native", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "eventhandler:libeventhandler", + "hicollie:libhicollie", + "hilog:libhilog", + "i18n:intl_util", + "ipc:ipc_core", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + public_external_deps = [ + "ability_runtime:wantagent_innerkits", + "image_framework:image_native", + ] + + if (is_double_framework) { + cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + if (ans_hitrace_usage) { + external_deps += [ "hitrace:hitrace_meter" ] + defines += [ "HITRACE_METER_ENABLE" ] + } + + if (notification_smart_reminder_supported) { + defines += [ "NOTIFICATION_SMART_REMINDER_SUPPORTED" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} diff --git a/frameworks/reminder/IReminderManager.idl b/frameworks/reminder/IReminderManager.idl new file mode 100644 index 000000000..b050e6ec9 --- /dev/null +++ b/frameworks/reminder/IReminderManager.idl @@ -0,0 +1,25 @@ +/* + * Copyright (c) 2024 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. + */ + +sequenceable OHOS.Notification.ReminderRequest; +interface OHOS.Notification.IReminderManager { + void PublishReminder([in] ReminderRequest reminder, [out] int reminderId); + void CancelReminder([in] int reminderId); + void CancelAllReminders(); + void GetValidReminders([out] ReminderRequest[] reminders); + void AddExcludeDate([in] int reminderId, [in] long date); + void DelExcludeDates([in] int reminderId); + void GetExcludeDates([in] int reminderId, [out] long[] dates); +} \ No newline at end of file diff --git a/frameworks/reminder/idl-gen:Zone.Identifier b/frameworks/reminder/idl-gen:Zone.Identifier new file mode 100644 index 000000000..e69de29bb diff --git a/frameworks/ans/src/reminder_helper.cpp b/frameworks/reminder/src/reminder_helper.cpp similarity index 58% rename from frameworks/ans/src/reminder_helper.cpp rename to frameworks/reminder/src/reminder_helper.cpp index 49298a072..a38f7a4fa 100644 --- a/frameworks/ans/src/reminder_helper.cpp +++ b/frameworks/reminder/src/reminder_helper.cpp @@ -16,65 +16,63 @@ #include "reminder_helper.h" #include "ans_log_wrapper.h" -#include "ans_notification.h" -#include "notification_helper.h" +#include "reminder_request_client.h" #include "singleton.h" namespace OHOS { namespace Notification { -ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) +ErrCode ReminderHelper::PublishReminder(const ReminderRequest& reminder, int32_t& reminderId) { ANSR_LOGI("PublishReminder start"); - NotificationHelper::AddSlotByType(reminder.GetSlotType()); - return DelayedSingleton::GetInstance()->PublishReminder(reminder); + return DelayedSingleton::GetInstance()->PublishReminder(reminder, reminderId); } ErrCode ReminderHelper::CancelReminder(const int32_t reminderId) { ANSR_LOGI("CancelReminder start"); - return DelayedSingleton::GetInstance()->CancelReminder(reminderId); + return DelayedSingleton::GetInstance()->CancelReminder(reminderId); } ErrCode ReminderHelper::CancelAllReminders() { ANSR_LOGI("CancelAllReminders start"); - return DelayedSingleton::GetInstance()->CancelAllReminders(); + return DelayedSingleton::GetInstance()->CancelAllReminders(); } -ErrCode ReminderHelper::GetValidReminders(std::vector> &validReminders) +ErrCode ReminderHelper::GetValidReminders(std::vector &validReminders) { ANSR_LOGI("GetValidReminders start"); - return DelayedSingleton::GetInstance()->GetValidReminders(validReminders); + return DelayedSingleton::GetInstance()->GetValidReminders(validReminders); } ErrCode ReminderHelper::AddNotificationSlot(const NotificationSlot &slot) { ANSR_LOGI("AddNotificationSlot start"); - return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); + return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); } ErrCode ReminderHelper::RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) { ANSR_LOGI("RemoveNotificationSlot start"); - return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); + return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); } -ErrCode ReminderHelper::AddExcludeDate(const int32_t reminderId, const uint64_t date) +ErrCode ReminderHelper::AddExcludeDate(const int32_t reminderId, const int64_t date) { ANSR_LOGI("AddExcludeDate start"); - return DelayedSingleton::GetInstance()->AddExcludeDate(reminderId, date); + return DelayedSingleton::GetInstance()->AddExcludeDate(reminderId, date); } ErrCode ReminderHelper::DelExcludeDates(const int32_t reminderId) { ANSR_LOGI("DelExcludeDates start"); - return DelayedSingleton::GetInstance()->DelExcludeDates(reminderId); + return DelayedSingleton::GetInstance()->DelExcludeDates(reminderId); } -ErrCode ReminderHelper::GetExcludeDates(const int32_t reminderId, std::vector& dates) +ErrCode ReminderHelper::GetExcludeDates(const int32_t reminderId, std::vector& dates) { ANSR_LOGI("GetExcludeDates start"); - return DelayedSingleton::GetInstance()->GetExcludeDates(reminderId, dates); + return DelayedSingleton::GetInstance()->GetExcludeDates(reminderId, dates); } } } \ No newline at end of file diff --git a/frameworks/ans/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp similarity index 99% rename from frameworks/ans/src/reminder_request.cpp rename to frameworks/reminder/src/reminder_request.cpp index 2420f77b2..859cbc092 100644 --- a/frameworks/ans/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -1317,7 +1317,7 @@ uint64_t ReminderRequest::GetDurationSinceEpochInMilli(const time_t target) ANSR_LOGW("tarDuration is less than 0."); return INVALID_LONG_LONG_VALUE; } - return static_cast(tarDate); + return tarDate; } std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const diff --git a/frameworks/ans/src/reminder_request_alarm.cpp b/frameworks/reminder/src/reminder_request_alarm.cpp similarity index 100% rename from frameworks/ans/src/reminder_request_alarm.cpp rename to frameworks/reminder/src/reminder_request_alarm.cpp diff --git a/frameworks/ans/src/reminder_request_calendar.cpp b/frameworks/reminder/src/reminder_request_calendar.cpp similarity index 98% rename from frameworks/ans/src/reminder_request_calendar.cpp rename to frameworks/reminder/src/reminder_request_calendar.cpp index df26f548c..23ed023c7 100644 --- a/frameworks/ans/src/reminder_request_calendar.cpp +++ b/frameworks/reminder/src/reminder_request_calendar.cpp @@ -69,7 +69,7 @@ void ReminderRequestCalendar::SetRRuleWantAgentInfo(const std::shared_ptr(date / MILLI_SECONDS); struct tm dateTime; @@ -90,9 +90,9 @@ void ReminderRequestCalendar::DelExcludeDates() excludeDates_.clear(); } -std::vector ReminderRequestCalendar::GetExcludeDates() const +std::vector ReminderRequestCalendar::GetExcludeDates() const { - std::vector excludeDates; + std::vector excludeDates; for (auto date : excludeDates_) { excludeDates.push_back(date); } @@ -112,7 +112,7 @@ bool ReminderRequestCalendar::IsInExcludeDate() const ANSR_LOGW("error start date time"); return false; } - uint64_t notificationTime = ReminderRequest::GetDurationSinceEpochInMilli(target); + int64_t notificationTime = ReminderRequest::GetDurationSinceEpochInMilli(target); if (excludeDates_.find(notificationTime) != excludeDates_.end()) { ANSR_LOGI("Reminder[%{public}d] trigger time is in exclude date", GetReminderId()); return true; @@ -862,7 +862,7 @@ void ReminderRequestCalendar::DeserializationExcludeDates(const std::string& str excludeDates_.clear(); for (auto date : root["excludeDates"]) { if (date.is_number()) { - excludeDates_.insert(date.get()); + excludeDates_.insert(date.get()); } } } diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp new file mode 100644 index 000000000..9fbf265ae --- /dev/null +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -0,0 +1,210 @@ +/* + * Copyright (c) 2021-2024 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 "reminder_request_client.h" +#include "ans_manager_proxy.h" +#include "reminder_manager_proxy.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" + +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" +#include "system_ability_definition.h" +#include "unique_fd.h" + +#include +#include + +namespace OHOS { +namespace Notification { +ErrCode ReminderRequestClient::AddSlotByType(const NotificationConstant::SlotType &slotType) +{ + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->AddSlotByType(slotType); +} + +ErrCode ReminderRequestClient::AddNotificationSlot(const NotificationSlot &slot) +{ + std::vector slots; + slots.push_back(slot); + return AddNotificationSlots(slots); +} + +ErrCode ReminderRequestClient::AddNotificationSlots(const std::vector &slots) +{ + if (slots.size() == 0) { + ANS_LOGE("Failed to add notification slots because input slots size is 0."); + return ERR_ANS_INVALID_PARAM; + } + + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + std::vector> slotsSptr; + for (auto it = slots.begin(); it != slots.end(); ++it) { + sptr slot = new (std::nothrow) NotificationSlot(*it); + if (slot == nullptr) { + ANS_LOGE("Failed to create NotificationSlot ptr."); + return ERR_ANS_NO_MEMORY; + } + slotsSptr.emplace_back(slot); + } + + return proxy->AddSlots(slotsSptr); +} + +ErrCode ReminderRequestClient::RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) +{ + ANS_LOGI("enter RemoveNotificationSlot,slotType:%{public}d", slotType); + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->RemoveSlotByType(slotType); +} + +ErrCode ReminderRequestClient::PublishReminder(const ReminderRequest& reminder, int32_t& reminderId) +{ + AddSlotByType(reminder.GetSlotType()); + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetReminderManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->PublishReminder(reminder, reminderId); +} + +ErrCode ReminderRequestClient::CancelReminder(const int32_t reminderId) +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->CancelReminder(reminderId); +} + +ErrCode ReminderRequestClient::CancelAllReminders() +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->CancelAllReminders(); +} + +ErrCode ReminderRequestClient::GetValidReminders(std::vector &validReminders) +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->GetValidReminders(validReminders); +} + +ErrCode ReminderRequestClient::AddExcludeDate(const int32_t reminderId, const uint64_t date) +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->AddExcludeDate(reminderId, date); +} + +ErrCode ReminderRequestClient::DelExcludeDates(const int32_t reminderId) +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->DelExcludeDates(reminderId); +} + +ErrCode ReminderRequestClient::GetExcludeDates(const int32_t reminderId, std::vector& dates) +{ + sptr proxy = GetReminderManagerProxy(); + if (!proxy) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return proxy->GetExcludeDates(reminderId, dates); +} + +sptr ReminderRequestClient::GetAnsManagerProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + ANS_LOGE("Failed to get system ability mgr."); + return nullptr; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (!remoteObject) { + ANS_LOGE("Failed to get notification Manager."); + return nullptr; + } + + sptr proxy = iface_cast(remoteObject); + if ((!proxy) || (!proxy->AsObject())) { + ANS_LOGE("Failed to get notification Manager's proxy"); + return nullptr; + } + return proxy; +} + +sptr ReminderRequestClient::GetReminderManagerProxy() +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!systemAbilityManager) { + ANS_LOGE("Failed to get system ability mgr."); + return nullptr; + } + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + if (!remoteObject) { + ANS_LOGE("Failed to get notification Manager."); + return nullptr; + } + + sptr proxy = iface_cast(remoteObject); + if ((!proxy) || (!proxy->AsObject())) { + ANS_LOGE("Failed to get notification Manager's proxy"); + return nullptr; + } + return proxy; +} + +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/reminder/src/reminder_request_client.h b/frameworks/reminder/src/reminder_request_client.h new file mode 100644 index 000000000..2ed9d113f --- /dev/null +++ b/frameworks/reminder/src/reminder_request_client.h @@ -0,0 +1,129 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "reminder_request.h" +#include "notification_slot.h" +#include "notification_constant.h" +#include "ans_manager_interface.h" +#include "ireminder_manager.h" + +namespace OHOS { +namespace Notification { +class ReminderRequestClient { +public: + /** + * @brief Publishes a scheduled reminder. + * + * @param reminder Indicates a reminder. + * @return Returns publish result. + */ + ErrCode PublishReminder(const ReminderRequest& reminder, int32_t& reminderId); + + /** + * @brief Cancels a specified reminder. + * + * @param reminderId Indicates reminder Id. + * @return Returns cancel result. + */ + ErrCode CancelReminder(const int32_t reminderId); + + /** + * @brief Cancels all reminders of current third part application. + * + * @return Returns cancel result. + */ + ErrCode CancelAllReminders(); + + /** + * @brief Obtains all valid reminder notifications set by the current application. + * + * @param[out] validReminders Indicates the vector to store the result. + * @return Returns get valid reminders result. + */ + ErrCode GetValidReminders(std::vector &validReminders); + + /** + * @brief Add exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param date exclude date + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date); + + /** + * @brief Clear exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DelExcludeDates(const int32_t reminderId); + + /** + * @brief Get exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param dates exclude dates + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates); + + /** + * @brief Creates a notification slot. + * @note You can call the NotificationRequest::SetSlotType(NotificationConstant::SlotType) method to bind the slot + * for publishing. A NotificationSlot instance cannot be used directly after being initialized. Instead, you have to + * call this method to create a notification slot and bind the slot ID to a NotificationRequest object so that the + * notification published can have all the characteristics set in the NotificationSlot. After a notification slot is + * created by using this method, only the name and description of the notification slot can be changed. Changes to + * the other attributes, such as the vibration status and notification tone, will no longer take effect. + * + * @param slot Indicates the notification slot to be created, which is set by NotificationSlot. + * This parameter must be specified. + * @return Returns add notification slot result. + */ + ErrCode AddNotificationSlot(const NotificationSlot &slot); + + /** + * @brief Deletes a created notification slot based on the slot ID. + * + * @param slotType Indicates the ID of the slot, which is created by AddNotificationSlot + * This parameter must be specified. + * @return Returns remove notification slot result. + */ + ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + +private: + + /** + * @brief Adds a notification slot by type. + * + * @param slotType Indicates the notification slot type to be added. + * @return Returns add notification slot result. + */ + ErrCode AddSlotByType(const NotificationConstant::SlotType &slotType); + + ErrCode AddNotificationSlots(const std::vector &slots); + + sptr GetAnsManagerProxy(); + + sptr GetReminderManagerProxy(); + +}; +} // namespace Notification +} // namespace OHOS + diff --git a/frameworks/ans/src/reminder_request_timer.cpp b/frameworks/reminder/src/reminder_request_timer.cpp similarity index 100% rename from frameworks/ans/src/reminder_request_timer.cpp rename to frameworks/reminder/src/reminder_request_timer.cpp diff --git a/interfaces/inner_api/reminder_helper.h b/interfaces/inner_api/reminder_helper.h index 553dea0c9..77f79f4b3 100644 --- a/interfaces/inner_api/reminder_helper.h +++ b/interfaces/inner_api/reminder_helper.h @@ -48,7 +48,7 @@ public: * Reminder id will be set with a number >= 0 if publishing the reminder successfully, Otherwise * reminder id is -1. You can call reminder.GetReminderId() to get the reminder id. */ - static ErrCode PublishReminder(ReminderRequest &reminder); + static ErrCode PublishReminder(const ReminderRequest &reminder, int32_t& reminderId); /** * Cancels a specified reminder. @@ -72,7 +72,7 @@ public: * @param[out] validReminders Indicates an initial vector to receive the result. * @return Returns an array list containing all valid reminder notifications set by the current application. */ - static ErrCode GetValidReminders(std::vector> &validReminders); + static ErrCode GetValidReminders(std::vector &validReminders); /** * Creates a NotificationSlot. @@ -104,7 +104,7 @@ public: * @param date exclude date * @return Returns ERR_OK on success, others on failure. */ - static ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date); + static ErrCode AddExcludeDate(const int32_t reminderId, const int64_t date); /** * @brief Clear exclude date for reminder @@ -121,7 +121,7 @@ public: * @param dates exclude dates * @return Returns ERR_OK on success, others on failure. */ - static ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates); + static ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates); private: static bool CheckPermission(); diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index 6e2ff9dbc..4aae0a889 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -68,9 +68,9 @@ public: std::shared_ptr GetRRuleWantAgentInfo(); - void AddExcludeDate(const uint64_t date); + void AddExcludeDate(const int64_t date); void DelExcludeDates(); - std::vector GetExcludeDates() const; + std::vector GetExcludeDates() const; bool IsInExcludeDate() const; inline uint16_t GetYear() const @@ -378,7 +378,7 @@ private: uint64_t durationTime_{0}; uint64_t lastStartDateTime_{0}; - std::set excludeDates_; + std::set excludeDates_; // repeat calendar std::shared_ptr rruleWantAgentInfo_ = nullptr; diff --git a/interfaces/ndk/BUILD.gn b/interfaces/ndk/BUILD.gn index 08121f875..ef401769f 100644 --- a/interfaces/ndk/BUILD.gn +++ b/interfaces/ndk/BUILD.gn @@ -52,7 +52,10 @@ ohos_shared_library("ohnotification") { sources = [ "src/notification.cpp" ] - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] external_deps = [ "ability_base:base", diff --git a/notification.gni b/notification.gni index 77e6889af..776b78f68 100644 --- a/notification.gni +++ b/notification.gni @@ -23,8 +23,10 @@ component_path = "//base/notification/distributed_notification_service" multimedia_path = "//foundation/multimedia/image_framework" commonlibrary_utils_path = "//commonlibrary/c_utils" services_path = "${component_path}/services" +reminder_services_path = "${component_path}/services/reminder" frameworks_path = "${component_path}/frameworks" frameworks_module_ans_path = "${frameworks_path}/ans" +frameworks_module_reminder_path = "${frameworks_path}/reminder" interfaces_path = "${component_path}/interfaces" inner_api_path = "${interfaces_path}/inner_api" notification_ndk_path = "${interfaces_path}/ndk" diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index c44e54ab6..5e1cda269 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -22,6 +22,7 @@ config("public_ans_config") { include_dirs = [ "${services_path}/ans/include", "${core_path}/include", + "${frameworks_module_reminder_path}/include", ] } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 7ed7f0e99..41d1c0be5 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -702,62 +702,62 @@ public: */ bool CheckReminderPermission(); - /** - * @brief Publishes a reminder notification. - * - * @param reminder Identifies the reminder notification request that needs to be published. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode PublishReminder(sptr &reminder) override; - - /** - * @brief Cancel a reminder notifications. - * - * @param reminderId Identifies the reminders id that needs to be canceled. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode CancelReminder(const int32_t reminderId) override; - - /** - * @brief Get all valid reminder notifications. - * - * @param reminders Identifies the list of all valid notifications. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetValidReminders(std::vector> &reminders) override; - - /** - * @brief Cancel all reminder notifications. - * - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode CancelAllReminders() override; - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode DelExcludeDates(const int32_t reminderId) override; - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; + // /** + // * @brief Publishes a reminder notification. + // * + // * @param reminder Identifies the reminder notification request that needs to be published. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode PublishReminder(sptr &reminder) override; + + // /** + // * @brief Cancel a reminder notifications. + // * + // * @param reminderId Identifies the reminders id that needs to be canceled. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode CancelReminder(const int32_t reminderId) override; + + // /** + // * @brief Get all valid reminder notifications. + // * + // * @param reminders Identifies the list of all valid notifications. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode GetValidReminders(std::vector> &reminders) override; + + // /** + // * @brief Cancel all reminder notifications. + // * + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode CancelAllReminders() override; + + // /** + // * @brief Add exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param date exclude date + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; + + // /** + // * @brief Clear exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode DelExcludeDates(const int32_t reminderId) override; + + // /** + // * @brief Get exclude date for reminder + // * + // * @param reminderId Identifies the reminders id. + // * @param dates exclude dates + // * @return Returns ERR_OK on success, others on failure. + // */ + // ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; /** * @brief Checks whether this device is support template. diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 229e57197..5cbc4f61f 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -55,7 +55,7 @@ private: private: std::atomic isDatashaReready_ {false}; sptr service_; - std::shared_ptr reminderAgent_; + // std::shared_ptr reminderAgent_; std::shared_ptr subscriber_ = nullptr; }; } // namespace Notification diff --git a/services/ans/include/reminder_config_change_observer.h b/services/ans/include/reminder_config_change_observer.h index c7981b0b8..342eb9748 100644 --- a/services/ans/include/reminder_config_change_observer.h +++ b/services/ans/include/reminder_config_change_observer.h @@ -1,42 +1,42 @@ -/* - * Copyright (c) 2023 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. - */ +// /* +// * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H +// #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H -#include "configuration_observer_stub.h" +// #include "configuration_observer_stub.h" -namespace OHOS { -namespace Notification { +// namespace OHOS { +// namespace Notification { -/** - * @brief Listening system language change, when the system language changes, - * notify ReminderDataManager. -*/ -class ReminderConfigChangeObserver final : public AppExecFwk::ConfigurationObserverStub { -public: - ReminderConfigChangeObserver() = default; - ~ReminderConfigChangeObserver() = default; +// /** +// * @brief Listening system language change, when the system language changes, +// * notify ReminderDataManager. +// */ +// class ReminderConfigChangeObserver final : public AppExecFwk::ConfigurationObserverStub { +// public: +// ReminderConfigChangeObserver() = default; +// ~ReminderConfigChangeObserver() = default; -public: - void OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) override; +// public: +// void OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) override; -private: - std::string languageInfo_; -}; -} // namespace Notification -} // namespace OHOS +// private: +// std::string languageInfo_; +// }; +// } // namespace Notification +// } // namespace OHOS -#endif \ No newline at end of file +// #endif \ No newline at end of file diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 24551916b..2e0cbbc70 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -1,763 +1,763 @@ -/* - * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H - -#include -#include - -#include "advanced_notification_service.h" -#include "ans_inner_errors.h" -#ifdef PLAYER_FRAMEWORK_ENABLE -#include "player.h" -#endif -#include "ffrt.h" -#include "app_mgr_client.h" -#include "reminder_request.h" -#include "reminder_store.h" -#include "reminder_timer_info.h" -#include "reminder_config_change_observer.h" -#include "datashare_predicates.h" -#include "datashare_values_bucket.h" -#include "app_mgr_interface.h" -#include "time_service_client.h" - -namespace OHOS { -namespace Notification { -class ReminderDataManager final { -public: - ReminderDataManager() - { - Init(false); - }; - ~ReminderDataManager(); - - ReminderDataManager(ReminderDataManager &other) = delete; - ReminderDataManager& operator = (const ReminderDataManager &other) = delete; - - /** - * @brief Cancels all the reminders relative to the bundle option. - * - * @param packageName Indicates the package name. - * @param userId Indicates the user id which the bundle belong to. - * @param uid Indicates the uid which the bundle belong to. - * @return ERR_OK if success, else not. - */ - ErrCode CancelAllReminders(const std::string& packageName, const int32_t userId, - const int32_t uid); - - /** - * @brief Cancels the target reminder relative to the reminder id and bundle option. - * - * @param reminderId Indicates the reminder id. - * @param bundleOption Indicates the bundle option. - * @return ERR_OK if success, else not. - */ - ErrCode CancelReminder(const int32_t &reminderId, const sptr &bundleOption); - - sptr CheckExcludeDateParam(const int32_t reminderId, - const sptr &bundleOption); - - /** - * @brief Add exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param date exclude date - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date, - const sptr &bundleOption); - - /** - * @brief Clear exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode DelExcludeDates(const int32_t reminderId, const sptr &bundleOption); - - /** - * @brief Get exclude date for reminder - * - * @param reminderId Identifies the reminders id. - * @param dates exclude dates - * @return Returns ERR_OK on success, others on failure. - */ - ErrCode GetExcludeDates(const int32_t reminderId, const sptr &bundleOption, - std::vector& dates); - - /** - * @brief Close the target reminder which is showing on panel. - * This is manul operation by user: 1.Click close button of the reminder, 2.remove reminder notification. - * - * @param want Want information that transferred when the event trigger by user. - * @param cancelNotification Indicates whether need to cancel notification or not. - */ - void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification); - - /** - * Dump all the reminders information. - * - * @return reminders informations. - */ - std::string Dump() const; - - /** - * Obtains the single instance. - * - * @return Single instance of ReminderDataManager. - */ - static std::shared_ptr GetInstance(); - static std::shared_ptr InitInstance( - const sptr &advancedNotificationService); - - /** - * Obtains all the valid reminders (which are not expired) relative to the bundle option. - * - * @param bundleOption Indicates the bundle option. - * @param[out] reminders return the valid reminders. - */ - void GetValidReminders( - const sptr &bundleOption, std::vector> &reminders); - - /** - * @brief Inits and recovery data from database. - * - * @param isFromBootComplete Indicates the init is called when boot completed. - */ - void Init(bool isFromBootComplete); - - void InitUserId(); - - /** - * @brief Check all reminders, Whether an immediate reminder is needed; - * whether a pull up service extension is required. - * Use when powering on and changing the system time. - */ - void CheckReminderTime(std::vector>& immediatelyReminders, - std::vector>& extensionReminders); - - /** - * @brief Register configuration observer, the listening system language is changed. - */ - bool RegisterConfigurationObserver(); - - void OnUserRemove(const int32_t& userId); - - /** - * @brief Bundle manager service start. - */ - void OnBundleMgrServiceStart(); - - /** - * @brief Ability manager service start. - */ - void OnAbilityMgrServiceStart(); - - void OnUserSwitch(const int32_t& userId); - - /** - * @brief Triggered when third party application died. - * - * @param bundleOption Indicates the bundleOption of third party application. - */ - void OnProcessDiedLocked(const sptr &bundleOption); - - /** - * Publishs a scheduled reminder. - * - * @param reminder Indicates the reminder. - * @param bundleOption Indicates bundle option the reminder belongs to. - * @return ERR_OK if success, else not. - */ - ErrCode PublishReminder(const sptr &reminder, - const sptr &bundleOption); - - /** - * @brief Refresh all reminders when date/time or timeZone of device changed by user. - * - * @param type Indicates it is triggered by dateTime change or timeZone change. - */ - void RefreshRemindersDueToSysTimeChange(uint8_t type); - - /** - * @brief Indicates the single instance of ans that used to execute operations in service. - * - * @param Indicates the single instance of ans notification service. - */ - void SetService(sptr &advancedNotificationService); - - bool ShouldAlert(const sptr &reminder) const; - - /** - * @brief Show the reminder. - * - * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. - * @param want Which contains the given reminder. - */ - void ShowActiveReminder(const EventFwk::Want &want); - - /** - * @brief Snooze the reminder by manual. - * 1) Snooze the trigger time to the next. - * 2) Update the notification(Update notification lable/content...; Stop audio player and vibrator) - * 3) Show the notification dialog in the SystemUI - * 4) Start a new reminder, which is recent one now. - * - * @param want Which contains the given reminder. - */ - void SnoozeReminder(const OHOS::EventFwk::Want &want); - - /** - * Starts the recent reminder timing. - */ - void StartRecentReminder(); - - /** - * Handle custom button click event. - */ - void HandleCustomButtonClick(const OHOS::EventFwk::Want &want); - - /** - * Handle click notification, no button. - */ - void ClickReminder(const OHOS::EventFwk::Want &want); - - /** - * Handle auto delete time - */ - void HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, const int64_t autoDeletedTime); - - /** - * @brief Terminate the alerting reminder. - * - * 1. Stop sound and vibrate. - * 2. Stop the alerting timer. - * 3. Update the reminder state. - * 4. Update the display content of the notification. - * - * @param want Which contains the given reminder. - */ - void TerminateAlerting(const OHOS::EventFwk::Want &want); - - /** - * @brief Update reminders based on the system language. - * - * Update action button title. - */ - void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); - - /** - * @brief System language change - */ - void OnLanguageChanged(); - - /** - * @brief When OnRemoveSystemAbility occurs. - */ - void OnRemoveAppMgr(); - - /** - * @brief Whether the device is ready or not. - */ - bool IsSystemReady(); - - static constexpr uint8_t TIME_ZONE_CHANGE = 0; - static constexpr uint8_t DATE_TIME_CHANGE = 1; - -private: - enum class TimerType : uint8_t { - TRIGGER_TIMER, - ALERTING_TIMER - }; - - static std::shared_ptr serviceQueue_; - /** - * Add default slot to the reminder if no slot set by user. - * - * @param reminder Indicates the reminder. - */ - void AddDefaultSlotIfNeeded(sptr &reminder); - - /** - * Add reminder to showed reminder vector. - * - * @param reminder Indicates the showed reminder. - */ - void AddToShowedReminders(const sptr &reminder); - - void CancelAllReminders(const int32_t userId); - - /** - * @brief Check the update conditions. - * - * @param reminder Indicates the showed reminder. - * @param actionButtonType Button type of the button. - * @param actionButtonMap Button map. - * @return True if check successful. - */ - bool CheckUpdateConditions(const sptr &reminder, - const ReminderRequest::ActionButtonType &actionButtonType, - const std::map &actionButtonMap); - - /** - * @brief update app database. - * - * @param reminder Indicates the showed reminder. - * @param actionButtonType Button type of the button. - */ - void UpdateAppDatabase(const sptr &reminder, - const ReminderRequest::ActionButtonType &actionButtonType); - - /** - * @brief generate Predicates for dataShare. - * - * @param predicates find fields from database. - * @param equalToVector Split from dataShareUpdate->equaleTo. - */ - void GenPredicates(DataShare::DataSharePredicates &predicates, const std::vector &equalToVector); - - /** - * @brief generate ValuesBucket for dataShare. - * - * @param valuesBucket update fields at database. - * @param valuesBucketVector Split from dataShareUpdate->valuesBucket. - */ - void GenValuesBucket(DataShare::DataShareValuesBucket &valuesBucket, - const std::vector &valuesBucketVector); - - /** - * @brief get bundleName from uri. - * - * @param dstBundleName The package name required to update the database. - * @param uri Database address. - */ - void GenDstBundleName(std::string &dstBundleName, const std::string &uri) const; - - /** - * @brief get custom ring uri. - * - * @param reminder Indicates the reminder. - * @return Returns the uri of ring tone. - */ - std::string GetCustomRingUri(const sptr &reminder); - - /** - * @brief Cancels all the reminders of the target bundle or user. - * - * @param packageName Indicates the packageName need to cancel. - * @param userId Indicates the userId to cancel. - */ - void CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, const int32_t uid); - - /** - * @brief Close reminders with the same group id. - * - * @param oldReminderId Indicates the reminderId that are currently bing showed. - * @param packageName Indicates the packageName need to cancel. - * @param groupId Indicates the group id to cancel. - */ - void CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, - const std::string &groupId); - - /** - * Cancels the notification relative to the reminder. - * - * @param reminder Indicates the reminder. - */ - void CancelNotification(const sptr &reminder) const; - - /** - * Check whether the number limit of reminders if exceeded. - * - * @param bundleName Indicates the target bundle. - * @return true if number limit is exceeded. - */ - bool CheckReminderLimitExceededLocked(const sptr &bundleOption, - const sptr &reminder) const; - void CloseReminder(const sptr &reminder, bool cancelNotification); - - /** - * Create a information for timer, such as timer type, repeat policy, interval and want agent. - * - * @param type Indicates the timer type. - * @param reminderRequest Indicates the reminder request. - * @return pointer of ReminderTimerInfo. - */ - std::shared_ptr CreateTimerInfo(TimerType type, - const sptr &reminderRequest) const; - void InitTimerInfo(std::shared_ptr &timerInfo, - const sptr &reminderRequest, TimerType reminderType) const; - - void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; - - std::string GetSoundUri(const sptr &reminder); - - /** - * Find the reminder from reminderVector_ by reminder id. - * - * @param reminderId Indicates the reminder id. - * @return pointer of reminder request or nullptr. - */ - sptr FindReminderRequestLocked(const int32_t &reminderId); - - /** - * Find the reminder from {@link reminderVector_} and - * {@link notificationBundleOptionMap_} by reminder id and pkgName. - * - * @param reminderId Indicates the reminder id. - * @param pkgName Indicates the package name. - * @return pointer of reminder request or nullptr. - */ - sptr FindReminderRequestLocked(const int32_t &reminderId, const std::string &pkgName); - - /** - * Obtains the recent reminder which is not expired from reminder vector. - * - * The expired reminders will be removed from reminderVector_ and notificationBundleOptionMap_. - * - * @return pointer of reminder object. - */ - sptr GetRecentReminderLocked(); - - void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); - void HandleExtensionReminder(std::vector> &extensionReminders); - - /** - * @brief Refresh the reminder due to date/time or timeZone change by user. - * - * @param type Indicates it is date/time change or timeZone change. - * @param reminder Indicates the target reminder. - * @return sptr Returns the target reminder if it is need to show immediately, otherwise nullptr. - */ - sptr HandleRefreshReminder(const uint8_t &type, sptr &reminder); - - /** - * @brief Handles all the reminders that have the same notification id and belong to same application - * with the current reminder. Unset the state of "showing". - * - * @param reminder Indicates the current reminder. - */ - void HandleSameNotificationIdShowing(const sptr reminder); - - bool HandleSysTimeChange(const sptr reminder) const; - - /** - * @brief Judge the two reminders is belong to the same application or not. - * - * @param bundleOption Indicates the bundleOption of first reminder. - * @param other Indicates the bundleOption of second reminder. - * @return true if the two reminders belong to the same application. - */ - bool IsBelongToSameApp(const sptr &bundleOption, - const sptr &other) const; - bool CheckIsSameApp(const sptr &reminder, const sptr &other) const; - - /** - * @brief Judges whether the reminder is matched with the bundleOption or userId. - * - * @param reminder Indicates the target reminder. - * @param packageName Indicates the package name. - * @param userId Indicates the user id. - * @param uid Indicates the uid. - * @return true If the reminder is matched with the bundleOption or userId. - */ - bool IsMatched(const sptr &reminder, const std::string &packageName, - const int32_t userId, const int32_t uid) const; - - /** - * @brief Judges whether the reminder is matched with the packageName or groupId. - * - * @param reminder Indicates the target reminder. - * @param packageName Indicates the package name. - * @param groupId Indicates the group id. - * @return true If the reminder is matched with the packageName and groupId. - */ - bool IsMatchedForGroupIdAndPkgName(const sptr &reminder, const std::string &packageName, - const std::string &groupId) const; - - bool IsAllowedNotify(const sptr &reminder) const; - - bool IsReminderAgentReady() const; - - void LoadReminderFromDb(); - - void PlaySoundAndVibrationLocked(const sptr &reminder); - void PlaySoundAndVibration(const sptr &reminder); - void StopSoundAndVibrationLocked(const sptr &reminder); - void StopSoundAndVibration(const sptr &reminder); - - /** - * Remove from showed reminder vector. - * - * @param reminder Indicates the reminder need to remove. - */ - void RemoveFromShowedReminders(const sptr &reminder); - - /** - * @brief Refresh the all reminders due to date/time or timeZone change by user. - * - * @param type Indicates it is date/time change or timeZone change. - * @return reminders that need to show immediately. - */ - void RefreshRemindersLocked(uint8_t type, std::vector>& immediatelyReminders, - std::vector>& extensionReminders); - - /** - * Removes the reminder. - * 1. removes the reminder from reminderVector_ and notificationBundleOptionMap_. - * 2. cancels the notification. - * - * @param reminderId Indicates the reminder id. - */ - void RemoveReminderLocked(const int32_t &reminderId); - - /** - * Resets timer status. - * 1. Sets timerId_ or timerIdAlerting_ with 0. - * 2. Sets activeReminderId_ or alertingReminderId with -1. - * - * @param type Indicates the timer type. - */ - void ResetStates(TimerType type); - - void SetActiveReminder(const sptr &reminder); - void SetAlertingReminder(const sptr &reminder); - void ShowActiveReminderExtendLocked(sptr &reminder); - static bool StartExtensionAbility(const sptr &reminder); - static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); - void InitServiceHandler(); - /** - * @brief Show the reminder on SystemUI. - * - * @param reminder Indicates the reminder to show. - * @param isNeedToPlaySound Indicates whether need to play sound. - * @param isNeedToStartNext Indicates whether need to start next reminder. - * @param isSysTimeChanged Indicates whether it is triggerred as system time changed by user. - * @param needScheduleTimeout Indicates whether need to control the ring duration. - */ - void ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, - const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout); - - void SnoozeReminderImpl(sptr &reminder); - - /** - * Starts timing actually. - * - * @param reminderRequest Indicates the reminder. - * @param type Indicates the timer type. - */ - void StartTimerLocked(const sptr &reminderRequest, TimerType type); - void StartTimer(const sptr &reminderRequest, TimerType type); - - uint64_t HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, - const sptr &timer); - - uint64_t HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, - const sptr &timer, time_t now); - - /** - * @brief Stop the alerting timer and update reminder information. - * - * 1. Stop sound and vibrate. - * 2. Stop the alerting timer. - * - * @param reminder Indicates the target reminder. - */ - void StopAlertingReminder(const sptr &reminder); - - /** - * Stops timing. - * - * @param type Indicates the timer type. - */ - void StopTimer(TimerType type); - void StopTimerLocked(TimerType type); - - /** - * @brief Terminate the alerting reminder. - * - * 1. Stop sound and vibrate. - * 2. Stop the alerting timer. - * 3. Update the reminder state. - * 4. Update the display content of the notification. - * - * @param reminder Indicates the reminder. - * @param reason Indicates the description information. - */ - void TerminateAlerting(const sptr &reminder, const std::string &reason); - void TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder); - - /** - * @brief Assign unique reminder id and save reminder in memory. - * - * @param reminder Indicates a reminder. - * @param bundleOption Indicates bundle option relative to the reminder. - */ - void UpdateAndSaveReminderLocked( - const sptr &reminder, const sptr &bundleOption); - - void UpdateNotification(const sptr &reminder, bool isSnooze); - - static bool cmp(sptr &reminderRequest, sptr &other); - - /** - * @brief Connect App Manager to get the current foreground application. - */ - bool ConnectAppMgr(); - - /** - * @brief Check need to notify the application, if the current foreground application - * is the creator of the reminder, notify the application of the reminder status - * change; otherwise, do not noitfy. - * - * @param reminder Indicates a reminder. - * @param buttonType The type of button clicked by the user. - */ - void CheckNeedNotifyStatus(const sptr &reminder, - const ReminderRequest::ActionButtonType buttonType); - - std::string GetFullPath(const std::string& path); - - /** - * @brief Check action button data share permission - */ - bool IsActionButtonDataShareValid(const sptr& reminder, - const uint32_t callerTokenId); - - /** - * @brief Get resource manager by bundlename and uid. - */ - std::shared_ptr GetResourceMgr(const std::string& bundleName, - const int32_t uid); - - /** - * @brief Get custom ring file desc. - * lock by resourceMutex_ in function - */ - bool GetCustomRingFileDesc(const sptr& reminder, - Global::Resource::ResourceManager::RawFileDescriptor& desc); - - /** - * @brief Close custom ring file desc. - * lock by resourceMutex_ in function - */ - void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); - - /** - * @brief report event to dfx - */ - void ReportSysEvent(const sptr& reminder); - - /** - * Single instance. - */ - static std::shared_ptr REMINDER_DATA_MANAGER; - - /** - * Used for multi-thread synchronise. - */ - static std::mutex MUTEX; - static std::mutex SHOW_MUTEX; - static std::mutex ALERT_MUTEX; - static std::mutex TIMER_MUTEX; - static std::mutex ACTIVE_MUTEX; - - /** - * Max number of reminders limit for the whole system. - */ - static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYSTEM = 12000; - - /** - * Max number of reminders limit for one system application. - */ - static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYS_APP = 10000; - - /** - * Max number of reminders limit for one application. - */ - static constexpr int16_t MAX_NUM_REMINDER_LIMIT_APP = 30; - - bool isReminderAgentReady_ = false; - - /** - * Vector used to record all the reminders in system. - */ - std::vector> reminderVector_; - - /** - * Vector used to record all the reminders which has been shown on panel. - */ - std::vector> showedReminderVector_; - - /** - * This timer is used to control the triggerTime of next reminder. - */ - uint64_t timerId_ {0}; - - /** - * This timer is used to control the ringDuration of the alerting reminder. - */ - std::atomic timerIdAlerting_ {0}; - - /** - * Indicates the active reminder that timing is taking effect. - */ - std::atomic activeReminderId_ = -1; - sptr activeReminder_ = nullptr; - - /** - * Indicates the reminder which is playing sound or vibration. - */ - std::atomic alertingReminderId_ = -1; - sptr alertingReminder_ = nullptr; -#ifdef PLAYER_FRAMEWORK_ENABLE - std::shared_ptr soundPlayer_ = nullptr; - std::mutex resourceMutex_; // for soundResource_ - std::shared_ptr soundResource_ = nullptr; -#endif - /** - * Indicates the total count of reminders in system. - */ - int16_t totalCount_ {0}; - int currentUserId_ {0}; - sptr advancedNotificationService_ = nullptr; - std::shared_ptr store_ = nullptr; - - /** - * Indicates config change observer for language - */ - sptr configChangeObserver_ = nullptr; - - /** - * Indicates app mananger for get foreground application - */ - std::mutex appMgrMutex_; - sptr appMgrProxy_ = nullptr; - - /** - * async queue - */ - std::shared_ptr queue_ = nullptr; - - /** - * Sa ready flag - */ - std::atomic saReadyFlag_{ 0 }; -}; -} // namespace OHOS -} // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +// /* +// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H + +// #include +// #include + +// #include "advanced_notification_service.h" +// #include "ans_inner_errors.h" +// #ifdef PLAYER_FRAMEWORK_ENABLE +// #include "player.h" +// #endif +// #include "ffrt.h" +// #include "app_mgr_client.h" +// #include "reminder_request.h" +// #include "reminder_store.h" +// #include "reminder_timer_info.h" +// #include "reminder_config_change_observer.h" +// #include "datashare_predicates.h" +// #include "datashare_values_bucket.h" +// #include "app_mgr_interface.h" +// #include "time_service_client.h" + +// namespace OHOS { +// namespace Notification { +// class ReminderDataManager final { +// public: +// ReminderDataManager() +// { +// Init(false); +// }; +// ~ReminderDataManager(); + +// ReminderDataManager(ReminderDataManager &other) = delete; +// ReminderDataManager& operator = (const ReminderDataManager &other) = delete; + +// /** +// * @brief Cancels all the reminders relative to the bundle option. +// * +// * @param packageName Indicates the package name. +// * @param userId Indicates the user id which the bundle belong to. +// * @param uid Indicates the uid which the bundle belong to. +// * @return ERR_OK if success, else not. +// */ +// ErrCode CancelAllReminders(const std::string& packageName, const int32_t userId, +// const int32_t uid); + +// /** +// * @brief Cancels the target reminder relative to the reminder id and bundle option. +// * +// * @param reminderId Indicates the reminder id. +// * @param bundleOption Indicates the bundle option. +// * @return ERR_OK if success, else not. +// */ +// ErrCode CancelReminder(const int32_t &reminderId, const sptr &bundleOption); + +// sptr CheckExcludeDateParam(const int32_t reminderId, +// const sptr &bundleOption); + +// /** +// * @brief Add exclude date for reminder +// * +// * @param reminderId Identifies the reminders id. +// * @param date exclude date +// * @return Returns ERR_OK on success, others on failure. +// */ +// ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date, +// const sptr &bundleOption); + +// /** +// * @brief Clear exclude date for reminder +// * +// * @param reminderId Identifies the reminders id. +// * @return Returns ERR_OK on success, others on failure. +// */ +// ErrCode DelExcludeDates(const int32_t reminderId, const sptr &bundleOption); + +// /** +// * @brief Get exclude date for reminder +// * +// * @param reminderId Identifies the reminders id. +// * @param dates exclude dates +// * @return Returns ERR_OK on success, others on failure. +// */ +// ErrCode GetExcludeDates(const int32_t reminderId, const sptr &bundleOption, +// std::vector& dates); + +// /** +// * @brief Close the target reminder which is showing on panel. +// * This is manul operation by user: 1.Click close button of the reminder, 2.remove reminder notification. +// * +// * @param want Want information that transferred when the event trigger by user. +// * @param cancelNotification Indicates whether need to cancel notification or not. +// */ +// void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification); + +// /** +// * Dump all the reminders information. +// * +// * @return reminders informations. +// */ +// std::string Dump() const; + +// /** +// * Obtains the single instance. +// * +// * @return Single instance of ReminderDataManager. +// */ +// static std::shared_ptr GetInstance(); +// static std::shared_ptr InitInstance( +// const sptr &advancedNotificationService); + +// /** +// * Obtains all the valid reminders (which are not expired) relative to the bundle option. +// * +// * @param bundleOption Indicates the bundle option. +// * @param[out] reminders return the valid reminders. +// */ +// void GetValidReminders( +// const sptr &bundleOption, std::vector> &reminders); + +// /** +// * @brief Inits and recovery data from database. +// * +// * @param isFromBootComplete Indicates the init is called when boot completed. +// */ +// void Init(bool isFromBootComplete); + +// void InitUserId(); + +// /** +// * @brief Check all reminders, Whether an immediate reminder is needed; +// * whether a pull up service extension is required. +// * Use when powering on and changing the system time. +// */ +// void CheckReminderTime(std::vector>& immediatelyReminders, +// std::vector>& extensionReminders); + +// /** +// * @brief Register configuration observer, the listening system language is changed. +// */ +// bool RegisterConfigurationObserver(); + +// void OnUserRemove(const int32_t& userId); + +// /** +// * @brief Bundle manager service start. +// */ +// void OnBundleMgrServiceStart(); + +// /** +// * @brief Ability manager service start. +// */ +// void OnAbilityMgrServiceStart(); + +// void OnUserSwitch(const int32_t& userId); + +// /** +// * @brief Triggered when third party application died. +// * +// * @param bundleOption Indicates the bundleOption of third party application. +// */ +// void OnProcessDiedLocked(const sptr &bundleOption); + +// /** +// * Publishs a scheduled reminder. +// * +// * @param reminder Indicates the reminder. +// * @param bundleOption Indicates bundle option the reminder belongs to. +// * @return ERR_OK if success, else not. +// */ +// ErrCode PublishReminder(const sptr &reminder, +// const sptr &bundleOption); + +// /** +// * @brief Refresh all reminders when date/time or timeZone of device changed by user. +// * +// * @param type Indicates it is triggered by dateTime change or timeZone change. +// */ +// void RefreshRemindersDueToSysTimeChange(uint8_t type); + +// /** +// * @brief Indicates the single instance of ans that used to execute operations in service. +// * +// * @param Indicates the single instance of ans notification service. +// */ +// void SetService(sptr &advancedNotificationService); + +// bool ShouldAlert(const sptr &reminder) const; + +// /** +// * @brief Show the reminder. +// * +// * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. +// * @param want Which contains the given reminder. +// */ +// void ShowActiveReminder(const EventFwk::Want &want); + +// /** +// * @brief Snooze the reminder by manual. +// * 1) Snooze the trigger time to the next. +// * 2) Update the notification(Update notification lable/content...; Stop audio player and vibrator) +// * 3) Show the notification dialog in the SystemUI +// * 4) Start a new reminder, which is recent one now. +// * +// * @param want Which contains the given reminder. +// */ +// void SnoozeReminder(const OHOS::EventFwk::Want &want); + +// /** +// * Starts the recent reminder timing. +// */ +// void StartRecentReminder(); + +// /** +// * Handle custom button click event. +// */ +// void HandleCustomButtonClick(const OHOS::EventFwk::Want &want); + +// /** +// * Handle click notification, no button. +// */ +// void ClickReminder(const OHOS::EventFwk::Want &want); + +// /** +// * Handle auto delete time +// */ +// void HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, const int64_t autoDeletedTime); + +// /** +// * @brief Terminate the alerting reminder. +// * +// * 1. Stop sound and vibrate. +// * 2. Stop the alerting timer. +// * 3. Update the reminder state. +// * 4. Update the display content of the notification. +// * +// * @param want Which contains the given reminder. +// */ +// void TerminateAlerting(const OHOS::EventFwk::Want &want); + +// /** +// * @brief Update reminders based on the system language. +// * +// * Update action button title. +// */ +// void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); + +// /** +// * @brief System language change +// */ +// void OnLanguageChanged(); + +// /** +// * @brief When OnRemoveSystemAbility occurs. +// */ +// void OnRemoveAppMgr(); + +// /** +// * @brief Whether the device is ready or not. +// */ +// bool IsSystemReady(); + +// static constexpr uint8_t TIME_ZONE_CHANGE = 0; +// static constexpr uint8_t DATE_TIME_CHANGE = 1; + +// private: +// enum class TimerType : uint8_t { +// TRIGGER_TIMER, +// ALERTING_TIMER +// }; + +// static std::shared_ptr serviceQueue_; +// /** +// * Add default slot to the reminder if no slot set by user. +// * +// * @param reminder Indicates the reminder. +// */ +// void AddDefaultSlotIfNeeded(sptr &reminder); + +// /** +// * Add reminder to showed reminder vector. +// * +// * @param reminder Indicates the showed reminder. +// */ +// void AddToShowedReminders(const sptr &reminder); + +// void CancelAllReminders(const int32_t userId); + +// /** +// * @brief Check the update conditions. +// * +// * @param reminder Indicates the showed reminder. +// * @param actionButtonType Button type of the button. +// * @param actionButtonMap Button map. +// * @return True if check successful. +// */ +// bool CheckUpdateConditions(const sptr &reminder, +// const ReminderRequest::ActionButtonType &actionButtonType, +// const std::map &actionButtonMap); + +// /** +// * @brief update app database. +// * +// * @param reminder Indicates the showed reminder. +// * @param actionButtonType Button type of the button. +// */ +// void UpdateAppDatabase(const sptr &reminder, +// const ReminderRequest::ActionButtonType &actionButtonType); + +// /** +// * @brief generate Predicates for dataShare. +// * +// * @param predicates find fields from database. +// * @param equalToVector Split from dataShareUpdate->equaleTo. +// */ +// void GenPredicates(DataShare::DataSharePredicates &predicates, const std::vector &equalToVector); + +// /** +// * @brief generate ValuesBucket for dataShare. +// * +// * @param valuesBucket update fields at database. +// * @param valuesBucketVector Split from dataShareUpdate->valuesBucket. +// */ +// void GenValuesBucket(DataShare::DataShareValuesBucket &valuesBucket, +// const std::vector &valuesBucketVector); + +// /** +// * @brief get bundleName from uri. +// * +// * @param dstBundleName The package name required to update the database. +// * @param uri Database address. +// */ +// void GenDstBundleName(std::string &dstBundleName, const std::string &uri) const; + +// /** +// * @brief get custom ring uri. +// * +// * @param reminder Indicates the reminder. +// * @return Returns the uri of ring tone. +// */ +// std::string GetCustomRingUri(const sptr &reminder); + +// /** +// * @brief Cancels all the reminders of the target bundle or user. +// * +// * @param packageName Indicates the packageName need to cancel. +// * @param userId Indicates the userId to cancel. +// */ +// void CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, const int32_t uid); + +// /** +// * @brief Close reminders with the same group id. +// * +// * @param oldReminderId Indicates the reminderId that are currently bing showed. +// * @param packageName Indicates the packageName need to cancel. +// * @param groupId Indicates the group id to cancel. +// */ +// void CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, +// const std::string &groupId); + +// /** +// * Cancels the notification relative to the reminder. +// * +// * @param reminder Indicates the reminder. +// */ +// void CancelNotification(const sptr &reminder) const; + +// /** +// * Check whether the number limit of reminders if exceeded. +// * +// * @param bundleName Indicates the target bundle. +// * @return true if number limit is exceeded. +// */ +// bool CheckReminderLimitExceededLocked(const sptr &bundleOption, +// const sptr &reminder) const; +// void CloseReminder(const sptr &reminder, bool cancelNotification); + +// /** +// * Create a information for timer, such as timer type, repeat policy, interval and want agent. +// * +// * @param type Indicates the timer type. +// * @param reminderRequest Indicates the reminder request. +// * @return pointer of ReminderTimerInfo. +// */ +// std::shared_ptr CreateTimerInfo(TimerType type, +// const sptr &reminderRequest) const; +// void InitTimerInfo(std::shared_ptr &timerInfo, +// const sptr &reminderRequest, TimerType reminderType) const; + +// void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; + +// std::string GetSoundUri(const sptr &reminder); + +// /** +// * Find the reminder from reminderVector_ by reminder id. +// * +// * @param reminderId Indicates the reminder id. +// * @return pointer of reminder request or nullptr. +// */ +// sptr FindReminderRequestLocked(const int32_t &reminderId); + +// /** +// * Find the reminder from {@link reminderVector_} and +// * {@link notificationBundleOptionMap_} by reminder id and pkgName. +// * +// * @param reminderId Indicates the reminder id. +// * @param pkgName Indicates the package name. +// * @return pointer of reminder request or nullptr. +// */ +// sptr FindReminderRequestLocked(const int32_t &reminderId, const std::string &pkgName); + +// /** +// * Obtains the recent reminder which is not expired from reminder vector. +// * +// * The expired reminders will be removed from reminderVector_ and notificationBundleOptionMap_. +// * +// * @return pointer of reminder object. +// */ +// sptr GetRecentReminderLocked(); + +// void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); +// void HandleExtensionReminder(std::vector> &extensionReminders); + +// /** +// * @brief Refresh the reminder due to date/time or timeZone change by user. +// * +// * @param type Indicates it is date/time change or timeZone change. +// * @param reminder Indicates the target reminder. +// * @return sptr Returns the target reminder if it is need to show immediately, otherwise nullptr. +// */ +// sptr HandleRefreshReminder(const uint8_t &type, sptr &reminder); + +// /** +// * @brief Handles all the reminders that have the same notification id and belong to same application +// * with the current reminder. Unset the state of "showing". +// * +// * @param reminder Indicates the current reminder. +// */ +// void HandleSameNotificationIdShowing(const sptr reminder); + +// bool HandleSysTimeChange(const sptr reminder) const; + +// /** +// * @brief Judge the two reminders is belong to the same application or not. +// * +// * @param bundleOption Indicates the bundleOption of first reminder. +// * @param other Indicates the bundleOption of second reminder. +// * @return true if the two reminders belong to the same application. +// */ +// bool IsBelongToSameApp(const sptr &bundleOption, +// const sptr &other) const; +// bool CheckIsSameApp(const sptr &reminder, const sptr &other) const; + +// /** +// * @brief Judges whether the reminder is matched with the bundleOption or userId. +// * +// * @param reminder Indicates the target reminder. +// * @param packageName Indicates the package name. +// * @param userId Indicates the user id. +// * @param uid Indicates the uid. +// * @return true If the reminder is matched with the bundleOption or userId. +// */ +// bool IsMatched(const sptr &reminder, const std::string &packageName, +// const int32_t userId, const int32_t uid) const; + +// /** +// * @brief Judges whether the reminder is matched with the packageName or groupId. +// * +// * @param reminder Indicates the target reminder. +// * @param packageName Indicates the package name. +// * @param groupId Indicates the group id. +// * @return true If the reminder is matched with the packageName and groupId. +// */ +// bool IsMatchedForGroupIdAndPkgName(const sptr &reminder, const std::string &packageName, +// const std::string &groupId) const; + +// bool IsAllowedNotify(const sptr &reminder) const; + +// bool IsReminderAgentReady() const; + +// void LoadReminderFromDb(); + +// void PlaySoundAndVibrationLocked(const sptr &reminder); +// void PlaySoundAndVibration(const sptr &reminder); +// void StopSoundAndVibrationLocked(const sptr &reminder); +// void StopSoundAndVibration(const sptr &reminder); + +// /** +// * Remove from showed reminder vector. +// * +// * @param reminder Indicates the reminder need to remove. +// */ +// void RemoveFromShowedReminders(const sptr &reminder); + +// /** +// * @brief Refresh the all reminders due to date/time or timeZone change by user. +// * +// * @param type Indicates it is date/time change or timeZone change. +// * @return reminders that need to show immediately. +// */ +// void RefreshRemindersLocked(uint8_t type, std::vector>& immediatelyReminders, +// std::vector>& extensionReminders); + +// /** +// * Removes the reminder. +// * 1. removes the reminder from reminderVector_ and notificationBundleOptionMap_. +// * 2. cancels the notification. +// * +// * @param reminderId Indicates the reminder id. +// */ +// void RemoveReminderLocked(const int32_t &reminderId); + +// /** +// * Resets timer status. +// * 1. Sets timerId_ or timerIdAlerting_ with 0. +// * 2. Sets activeReminderId_ or alertingReminderId with -1. +// * +// * @param type Indicates the timer type. +// */ +// void ResetStates(TimerType type); + +// void SetActiveReminder(const sptr &reminder); +// void SetAlertingReminder(const sptr &reminder); +// void ShowActiveReminderExtendLocked(sptr &reminder); +// static bool StartExtensionAbility(const sptr &reminder); +// static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); +// void InitServiceHandler(); +// /** +// * @brief Show the reminder on SystemUI. +// * +// * @param reminder Indicates the reminder to show. +// * @param isNeedToPlaySound Indicates whether need to play sound. +// * @param isNeedToStartNext Indicates whether need to start next reminder. +// * @param isSysTimeChanged Indicates whether it is triggerred as system time changed by user. +// * @param needScheduleTimeout Indicates whether need to control the ring duration. +// */ +// void ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, +// const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout); + +// void SnoozeReminderImpl(sptr &reminder); + +// /** +// * Starts timing actually. +// * +// * @param reminderRequest Indicates the reminder. +// * @param type Indicates the timer type. +// */ +// void StartTimerLocked(const sptr &reminderRequest, TimerType type); +// void StartTimer(const sptr &reminderRequest, TimerType type); + +// uint64_t HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, +// const sptr &timer); + +// uint64_t HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, +// const sptr &timer, time_t now); + +// /** +// * @brief Stop the alerting timer and update reminder information. +// * +// * 1. Stop sound and vibrate. +// * 2. Stop the alerting timer. +// * +// * @param reminder Indicates the target reminder. +// */ +// void StopAlertingReminder(const sptr &reminder); + +// /** +// * Stops timing. +// * +// * @param type Indicates the timer type. +// */ +// void StopTimer(TimerType type); +// void StopTimerLocked(TimerType type); + +// /** +// * @brief Terminate the alerting reminder. +// * +// * 1. Stop sound and vibrate. +// * 2. Stop the alerting timer. +// * 3. Update the reminder state. +// * 4. Update the display content of the notification. +// * +// * @param reminder Indicates the reminder. +// * @param reason Indicates the description information. +// */ +// void TerminateAlerting(const sptr &reminder, const std::string &reason); +// void TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder); + +// /** +// * @brief Assign unique reminder id and save reminder in memory. +// * +// * @param reminder Indicates a reminder. +// * @param bundleOption Indicates bundle option relative to the reminder. +// */ +// void UpdateAndSaveReminderLocked( +// const sptr &reminder, const sptr &bundleOption); + +// void UpdateNotification(const sptr &reminder, bool isSnooze); + +// static bool cmp(sptr &reminderRequest, sptr &other); + +// /** +// * @brief Connect App Manager to get the current foreground application. +// */ +// bool ConnectAppMgr(); + +// /** +// * @brief Check need to notify the application, if the current foreground application +// * is the creator of the reminder, notify the application of the reminder status +// * change; otherwise, do not noitfy. +// * +// * @param reminder Indicates a reminder. +// * @param buttonType The type of button clicked by the user. +// */ +// void CheckNeedNotifyStatus(const sptr &reminder, +// const ReminderRequest::ActionButtonType buttonType); + +// std::string GetFullPath(const std::string& path); + +// /** +// * @brief Check action button data share permission +// */ +// bool IsActionButtonDataShareValid(const sptr& reminder, +// const uint32_t callerTokenId); + +// /** +// * @brief Get resource manager by bundlename and uid. +// */ +// std::shared_ptr GetResourceMgr(const std::string& bundleName, +// const int32_t uid); + +// /** +// * @brief Get custom ring file desc. +// * lock by resourceMutex_ in function +// */ +// bool GetCustomRingFileDesc(const sptr& reminder, +// Global::Resource::ResourceManager::RawFileDescriptor& desc); + +// /** +// * @brief Close custom ring file desc. +// * lock by resourceMutex_ in function +// */ +// void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); + +// /** +// * @brief report event to dfx +// */ +// void ReportSysEvent(const sptr& reminder); + +// /** +// * Single instance. +// */ +// static std::shared_ptr REMINDER_DATA_MANAGER; + +// /** +// * Used for multi-thread synchronise. +// */ +// static std::mutex MUTEX; +// static std::mutex SHOW_MUTEX; +// static std::mutex ALERT_MUTEX; +// static std::mutex TIMER_MUTEX; +// static std::mutex ACTIVE_MUTEX; + +// /** +// * Max number of reminders limit for the whole system. +// */ +// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYSTEM = 12000; + +// /** +// * Max number of reminders limit for one system application. +// */ +// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYS_APP = 10000; + +// /** +// * Max number of reminders limit for one application. +// */ +// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_APP = 30; + +// bool isReminderAgentReady_ = false; + +// /** +// * Vector used to record all the reminders in system. +// */ +// std::vector> reminderVector_; + +// /** +// * Vector used to record all the reminders which has been shown on panel. +// */ +// std::vector> showedReminderVector_; + +// /** +// * This timer is used to control the triggerTime of next reminder. +// */ +// uint64_t timerId_ {0}; + +// /** +// * This timer is used to control the ringDuration of the alerting reminder. +// */ +// std::atomic timerIdAlerting_ {0}; + +// /** +// * Indicates the active reminder that timing is taking effect. +// */ +// std::atomic activeReminderId_ = -1; +// sptr activeReminder_ = nullptr; + +// /** +// * Indicates the reminder which is playing sound or vibration. +// */ +// std::atomic alertingReminderId_ = -1; +// sptr alertingReminder_ = nullptr; +// #ifdef PLAYER_FRAMEWORK_ENABLE +// std::shared_ptr soundPlayer_ = nullptr; +// std::mutex resourceMutex_; // for soundResource_ +// std::shared_ptr soundResource_ = nullptr; +// #endif +// /** +// * Indicates the total count of reminders in system. +// */ +// int16_t totalCount_ {0}; +// int currentUserId_ {0}; +// sptr advancedNotificationService_ = nullptr; +// std::shared_ptr store_ = nullptr; + +// /** +// * Indicates config change observer for language +// */ +// sptr configChangeObserver_ = nullptr; + +// /** +// * Indicates app mananger for get foreground application +// */ +// std::mutex appMgrMutex_; +// sptr appMgrProxy_ = nullptr; + +// /** +// * async queue +// */ +// std::shared_ptr queue_ = nullptr; + +// /** +// * Sa ready flag +// */ +// std::atomic saReadyFlag_{ 0 }; +// }; +// } // namespace OHOS +// } // namespace Notification +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h index 415d0a5c0..ab3e4856a 100644 --- a/services/ans/include/reminder_event_manager.h +++ b/services/ans/include/reminder_event_manager.h @@ -1,100 +1,100 @@ -/* - * Copyright (c) 2021-2022 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. - */ +// /* +// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +// #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H -#include "common_event_subscriber.h" -#include "reminder_data_manager.h" -#include "system_ability_status_change_stub.h" -#include "notification_subscriber.h" +// #include "common_event_subscriber.h" +// #include "reminder_data_manager.h" +// #include "system_ability_status_change_stub.h" +// #include "notification_subscriber.h" -#include +// #include -namespace OHOS { -namespace Notification { -class ReminderEventManager { -public: - explicit ReminderEventManager(std::shared_ptr &reminderDataManager); - virtual ~ReminderEventManager() {}; - ReminderEventManager(ReminderEventManager &other) = delete; - ReminderEventManager& operator = (const ReminderEventManager &other) = delete; +// namespace OHOS { +// namespace Notification { +// class ReminderEventManager { +// public: +// explicit ReminderEventManager(std::shared_ptr &reminderDataManager); +// virtual ~ReminderEventManager() {}; +// ReminderEventManager(ReminderEventManager &other) = delete; +// ReminderEventManager& operator = (const ReminderEventManager &other) = delete; -private: - void init(std::shared_ptr &reminderDataManager) const; - void SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const; +// private: +// void init(std::shared_ptr &reminderDataManager) const; +// void SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const; -class ReminderEventSubscriber : public EventFwk::CommonEventSubscriber { -public: - ReminderEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, - std::shared_ptr &reminderDataManager); - virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +// class ReminderEventSubscriber : public EventFwk::CommonEventSubscriber { +// public: +// ReminderEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, +// std::shared_ptr &reminderDataManager); +// virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); -private: - sptr GetBundleOption(const OHOS::EventFwk::Want &want) const; - void HandlePackageRemove(const EventFwk::Want &want) const; - void HandleProcessDied(const EventFwk::Want &want) const; - std::shared_ptr reminderDataManager_ = nullptr; -}; +// private: +// sptr GetBundleOption(const OHOS::EventFwk::Want &want) const; +// void HandlePackageRemove(const EventFwk::Want &want) const; +// void HandleProcessDied(const EventFwk::Want &want) const; +// std::shared_ptr reminderDataManager_ = nullptr; +// }; -class ReminderEventCustomSubscriber : public EventFwk::CommonEventSubscriber { -public: - ReminderEventCustomSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, - std::shared_ptr &reminderDataManager); - virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); +// class ReminderEventCustomSubscriber : public EventFwk::CommonEventSubscriber { +// public: +// ReminderEventCustomSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, +// std::shared_ptr &reminderDataManager); +// virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); -private: - std::shared_ptr reminderDataManager_ = nullptr; -}; +// private: +// std::shared_ptr reminderDataManager_ = nullptr; +// }; -class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { -public: - explicit SystemAbilityStatusChangeListener(std::shared_ptr &reminderDataManager); - ~SystemAbilityStatusChangeListener() {}; - virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; - virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; -private: - std::shared_ptr reminderDataManager_ = nullptr; -}; +// class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { +// public: +// explicit SystemAbilityStatusChangeListener(std::shared_ptr &reminderDataManager); +// ~SystemAbilityStatusChangeListener() {}; +// virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +// virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +// private: +// std::shared_ptr reminderDataManager_ = nullptr; +// }; -class ReminderNotificationSubscriber : public NotificationSubscriber { -public: - explicit ReminderNotificationSubscriber(std::shared_ptr &reminderDataManager); - ~ReminderNotificationSubscriber() override; - void OnConnected() override; - void OnDisconnected() override; - void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int deleteReason) override; - void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override; - void OnUpdate(const std::shared_ptr &sortingMap) override; - void OnDied() override; - void OnDoNotDisturbDateChange( - const std::shared_ptr &date) override; - void OnEnabledNotificationChanged( - const std::shared_ptr &callbackData) override; - void OnBadgeChanged(const std::shared_ptr &badgeData) override; - void OnBadgeEnabledChanged(const sptr &callbackData) override; - void OnBatchCanceled(const std::vector> &requestList, - const std::shared_ptr &sortingMap, int32_t deleteReason) override; -private: - std::shared_ptr reminderDataManager_ = nullptr; -}; +// class ReminderNotificationSubscriber : public NotificationSubscriber { +// public: +// explicit ReminderNotificationSubscriber(std::shared_ptr &reminderDataManager); +// ~ReminderNotificationSubscriber() override; +// void OnConnected() override; +// void OnDisconnected() override; +// void OnCanceled(const std::shared_ptr &request, +// const std::shared_ptr &sortingMap, int deleteReason) override; +// void OnConsumed(const std::shared_ptr &request, +// const std::shared_ptr &sortingMap) override; +// void OnUpdate(const std::shared_ptr &sortingMap) override; +// void OnDied() override; +// void OnDoNotDisturbDateChange( +// const std::shared_ptr &date) override; +// void OnEnabledNotificationChanged( +// const std::shared_ptr &callbackData) override; +// void OnBadgeChanged(const std::shared_ptr &badgeData) override; +// void OnBadgeEnabledChanged(const sptr &callbackData) override; +// void OnBatchCanceled(const std::vector> &requestList, +// const std::shared_ptr &sortingMap, int32_t deleteReason) override; +// private: +// std::shared_ptr reminderDataManager_ = nullptr; +// }; - static std::shared_ptr subscriber_; -}; -} // namespace OHOS -} // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +// static std::shared_ptr subscriber_; +// }; +// } // namespace OHOS +// } // namespace Notification +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H diff --git a/services/ans/include/reminder_store.h b/services/ans/include/reminder_store.h index ac81e8e25..22bcf9487 100644 --- a/services/ans/include/reminder_store.h +++ b/services/ans/include/reminder_store.h @@ -1,109 +1,109 @@ -/* - * Copyright (c) 2022 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. - */ +// /* +// * Copyright (c) 2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H +// #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H -#include +// #include -#include "notification_bundle_option.h" -#include "reminder_request.h" -#include "rdb_errno.h" -#include "rdb_helper.h" -#include "rdb_open_callback.h" -#include "rdb_store_config.h" +// #include "notification_bundle_option.h" +// #include "reminder_request.h" +// #include "rdb_errno.h" +// #include "rdb_helper.h" +// #include "rdb_open_callback.h" +// #include "rdb_store_config.h" -namespace OHOS { -namespace Notification { -class ReminderStore { -public: - ReminderStore() {}; - virtual ~ReminderStore() {}; +// namespace OHOS { +// namespace Notification { +// class ReminderStore { +// public: +// ReminderStore() {}; +// virtual ~ReminderStore() {}; -public: - int32_t Init(); - int32_t Delete(const int32_t reminderId); - int32_t Delete(const std::string& pkg, const int32_t userId, const int32_t uid); - int32_t DeleteUser(const int32_t userId); - int32_t UpdateOrInsert(const sptr& reminder, const sptr& bundleOption); - int32_t GetMaxId(); - std::vector> GetAllValidReminders(); +// public: +// int32_t Init(); +// int32_t Delete(const int32_t reminderId); +// int32_t Delete(const std::string& pkg, const int32_t userId, const int32_t uid); +// int32_t DeleteUser(const int32_t userId); +// int32_t UpdateOrInsert(const sptr& reminder, const sptr& bundleOption); +// int32_t GetMaxId(); +// std::vector> GetAllValidReminders(); -public: - static void GetUInt8Val(const std::shared_ptr& resultSet, - const std::string& name, uint8_t& value); - static void GetUInt16Val(const std::shared_ptr& resultSet, - const std::string& name, uint16_t& value); - static void GetInt32Val(const std::shared_ptr& resultSet, - const std::string& name, int32_t& value); - static void GetInt64Val(const std::shared_ptr& resultSet, - const std::string& name, int64_t& value); - static void GetUInt64Val(const std::shared_ptr& resultSet, - const std::string& name, uint64_t& value); - static void GetStringVal(const std::shared_ptr& resultSet, - const std::string& name, std::string& value); +// public: +// static void GetUInt8Val(const std::shared_ptr& resultSet, +// const std::string& name, uint8_t& value); +// static void GetUInt16Val(const std::shared_ptr& resultSet, +// const std::string& name, uint16_t& value); +// static void GetInt32Val(const std::shared_ptr& resultSet, +// const std::string& name, int32_t& value); +// static void GetInt64Val(const std::shared_ptr& resultSet, +// const std::string& name, int64_t& value); +// static void GetUInt64Val(const std::shared_ptr& resultSet, +// const std::string& name, uint64_t& value); +// static void GetStringVal(const std::shared_ptr& resultSet, +// const std::string& name, std::string& value); - static const int32_t STATE_OK; - static const int32_t STATE_FAIL; +// static const int32_t STATE_OK; +// static const int32_t STATE_FAIL; - static const std::string REMINDER_DB_DIR; - static const std::string REMINDER_DB_NAME; - static const std::string REMINDER_DB_TABLE; +// static const std::string REMINDER_DB_DIR; +// static const std::string REMINDER_DB_NAME; +// static const std::string REMINDER_DB_TABLE; -private: - /** - * @brief Inits the data in database when system boot on or proxy process reboot on. - * - * 1. Deletes all the reminders which IS_EXPIRED is true. - * 2. Sets all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE - * - * @return int32_t result code. - */ - int32_t InitData(); - int32_t DeleteBase(const std::string& deleteCondition); - int32_t Delete(const std::string& baseCondition, const std::string& assoConditon); - int32_t Insert(const sptr& reminder, const sptr& bundleOption); - int32_t Update(const sptr& reminder, const sptr& bundleOption); +// private: +// /** +// * @brief Inits the data in database when system boot on or proxy process reboot on. +// * +// * 1. Deletes all the reminders which IS_EXPIRED is true. +// * 2. Sets all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE +// * +// * @return int32_t result code. +// */ +// int32_t InitData(); +// int32_t DeleteBase(const std::string& deleteCondition); +// int32_t Delete(const std::string& baseCondition, const std::string& assoConditon); +// int32_t Insert(const sptr& reminder, const sptr& bundleOption); +// int32_t Update(const sptr& reminder, const sptr& bundleOption); - bool IsReminderExist(const sptr& reminder); - std::vector> GetReminders(const std::string& queryCondition); - sptr BuildReminder(const std::shared_ptr& resultBase); +// bool IsReminderExist(const sptr& reminder); +// std::vector> GetReminders(const std::string& queryCondition); +// sptr BuildReminder(const std::shared_ptr& resultBase); - std::shared_ptr Query(const std::string& tableName, const std::string& colums, - const int32_t reminderId); - std::shared_ptr Query(const std::string& queryCondition) const; +// std::shared_ptr Query(const std::string& tableName, const std::string& colums, +// const int32_t reminderId); +// std::shared_ptr Query(const std::string& queryCondition) const; -private: - std::shared_ptr rdbStore_ = nullptr; +// private: +// std::shared_ptr rdbStore_ = nullptr; -private: -class ReminderStoreDataCallBack : public NativeRdb::RdbOpenCallback { -public: - int32_t OnCreate(NativeRdb::RdbStore& store) override; - int32_t OnUpgrade(NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) override; - int32_t OnDowngrade(NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) override; +// private: +// class ReminderStoreDataCallBack : public NativeRdb::RdbOpenCallback { +// public: +// int32_t OnCreate(NativeRdb::RdbStore& store) override; +// int32_t OnUpgrade(NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) override; +// int32_t OnDowngrade(NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) override; -private: - int32_t CreateTable(NativeRdb::RdbStore& store); - int32_t CopyData(NativeRdb::RdbStore& store); - std::vector> GetOldReminders(NativeRdb::RdbStore& store); - void InsertNewReminders(NativeRdb::RdbStore& store, const std::vector>& reminders); - void AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, - const std::string& columnName, const std::string& columnType, const std::string& defValue); -}; -}; -} // namespace Notification -} // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H \ No newline at end of file +// private: +// int32_t CreateTable(NativeRdb::RdbStore& store); +// int32_t CopyData(NativeRdb::RdbStore& store); +// std::vector> GetOldReminders(NativeRdb::RdbStore& store); +// void InsertNewReminders(NativeRdb::RdbStore& store, const std::vector>& reminders); +// void AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, +// const std::string& columnName, const std::string& columnType, const std::string& defValue); +// }; +// }; +// } // namespace Notification +// } // namespace OHOS +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H \ No newline at end of file diff --git a/services/ans/include/reminder_store_strategy.h b/services/ans/include/reminder_store_strategy.h index 0d0ccefb6..57555341d 100644 --- a/services/ans/include/reminder_store_strategy.h +++ b/services/ans/include/reminder_store_strategy.h @@ -1,193 +1,193 @@ -/* - * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H - -#include -#include - -#include "reminder_request.h" -#include "rdb_store.h" - -namespace OHOS { -namespace Notification { -class ReminderStrategy { -public: - /** - * @brief Gets the value from rdb result. - * - * @param resultSet the rdb result. - * @param name the column name in rdb. - * @param value the column value in rdb. - */ - template - static void GetRdbValue(const std::shared_ptr& resultSet, - const std::string& name, T& value); - -public: - /** - * @brief Persist the reminder to the database. - */ - static void AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket &values, const bool oldVersion = false); - - /** - * @brief Restore the reminder from the database(old version rdb). - */ - static void RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - - /** - * @brief Restore the reminder from the database. - */ - static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); - -private: - /** - * @brief Recovery time related fields from the database(old version rdb). - */ - static void RecoverTimeFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - /** - * @brief Recovery id related fields from the database(old version rdb). - */ - static void RecoverIdFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - /** - * @brief Recovery context related from the database(old version rdb). - */ - static void RecoverContextFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - - /** - * @brief Recovery time related fields from the database. - */ - static void RecoverTimeFromDb(sptr& reminder, - const std::shared_ptr& resultSet); - /** - * @brief Recovery id related fields from the database. - */ - static void RecoverIdFromDb(sptr& reminder, - const std::shared_ptr& resultSet); - /** - * @brief Recovery context related from the database. - */ - static void RecoverContextFromDb(sptr& reminder, - const std::shared_ptr& resultSet); -}; - -class ReminderTimerStrategy { -public: - /** - * @brief Persist the reminder to the database. - */ - static void AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values); - - /** - * @brief Restore the reminder from the database(old version rdb). - */ - static void RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - - /** - * @brief Restore the reminder from the database. - */ - static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, - const std::shared_ptr& resultSet); -}; - -class ReminderAlarmStrategy { -public: - /** - * @brief Persist the reminder to the database. - */ - static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); - - /** - * @brief Restore the reminder from the database(old version rdb). - */ - static void RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - - /** - * @brief Restore the reminder from the database. - */ - static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, - const std::shared_ptr& resultSet); -}; - -class ReminderCalendarStrategy { -public: - /** - * @brief Persist the reminder to the database. - */ - static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); - - /** - * @brief Restore the reminder from the database(old version rdb). - */ - static void RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet); - - /** - * @brief Restore the reminder from the database. - */ - static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, - const std::shared_ptr& resultSet); - -private: - static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); -}; - -template -void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, - const std::string& name, T& value) -{ - value = T(); - int32_t columnIndex = -1; - resultSet->GetColumnIndex(name, columnIndex); - if (columnIndex == -1) { - ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); - return; - } - - if constexpr (std::is_same_v) { - resultSet->GetString(columnIndex, value); - } else if constexpr (std::is_same_v) { - resultSet->GetLong(columnIndex, value); - } else if constexpr (std::is_same_v) { - int64_t t = 0; - resultSet->GetLong(columnIndex, t); - value = static_cast(t); - } else if constexpr (std::is_same_v) { - resultSet->GetInt(columnIndex, value); - } else if constexpr (std::is_same_v) { - int32_t t = 0; - resultSet->GetInt(columnIndex, t); - value = static_cast(t); - } else if constexpr (std::is_same_v) { - int32_t t = 0; - resultSet->GetInt(columnIndex, t); - value = static_cast(t); - } else if constexpr (std::is_same_v) { - int32_t t = 0; - resultSet->GetInt(columnIndex, t); - value = static_cast(t); - } -} -} // namespace Notification -} // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file +// /* +// * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H + +// #include +// #include + +// #include "reminder_request.h" +// #include "rdb_store.h" + +// namespace OHOS { +// namespace Notification { +// class ReminderStrategy { +// public: +// /** +// * @brief Gets the value from rdb result. +// * +// * @param resultSet the rdb result. +// * @param name the column name in rdb. +// * @param value the column value in rdb. +// */ +// template +// static void GetRdbValue(const std::shared_ptr& resultSet, +// const std::string& name, T& value); + +// public: +// /** +// * @brief Persist the reminder to the database. +// */ +// static void AppendValuesBucket(const sptr& reminder, +// NativeRdb::ValuesBucket &values, const bool oldVersion = false); + +// /** +// * @brief Restore the reminder from the database(old version rdb). +// */ +// static void RecoverFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); + +// /** +// * @brief Restore the reminder from the database. +// */ +// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); + +// private: +// /** +// * @brief Recovery time related fields from the database(old version rdb). +// */ +// static void RecoverTimeFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); +// /** +// * @brief Recovery id related fields from the database(old version rdb). +// */ +// static void RecoverIdFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); +// /** +// * @brief Recovery context related from the database(old version rdb). +// */ +// static void RecoverContextFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); + +// /** +// * @brief Recovery time related fields from the database. +// */ +// static void RecoverTimeFromDb(sptr& reminder, +// const std::shared_ptr& resultSet); +// /** +// * @brief Recovery id related fields from the database. +// */ +// static void RecoverIdFromDb(sptr& reminder, +// const std::shared_ptr& resultSet); +// /** +// * @brief Recovery context related from the database. +// */ +// static void RecoverContextFromDb(sptr& reminder, +// const std::shared_ptr& resultSet); +// }; + +// class ReminderTimerStrategy { +// public: +// /** +// * @brief Persist the reminder to the database. +// */ +// static void AppendValuesBucket(const sptr& reminder, +// NativeRdb::ValuesBucket& values); + +// /** +// * @brief Restore the reminder from the database(old version rdb). +// */ +// static void RecoverFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); + +// /** +// * @brief Restore the reminder from the database. +// */ +// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, +// const std::shared_ptr& resultSet); +// }; + +// class ReminderAlarmStrategy { +// public: +// /** +// * @brief Persist the reminder to the database. +// */ +// static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + +// /** +// * @brief Restore the reminder from the database(old version rdb). +// */ +// static void RecoverFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); + +// /** +// * @brief Restore the reminder from the database. +// */ +// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, +// const std::shared_ptr& resultSet); +// }; + +// class ReminderCalendarStrategy { +// public: +// /** +// * @brief Persist the reminder to the database. +// */ +// static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + +// /** +// * @brief Restore the reminder from the database(old version rdb). +// */ +// static void RecoverFromOldVersion(sptr& reminder, +// const std::shared_ptr& resultSet); + +// /** +// * @brief Restore the reminder from the database. +// */ +// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, +// const std::shared_ptr& resultSet); + +// private: +// static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); +// }; + +// template +// void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, +// const std::string& name, T& value) +// { +// value = T(); +// int32_t columnIndex = -1; +// resultSet->GetColumnIndex(name, columnIndex); +// if (columnIndex == -1) { +// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); +// return; +// } + +// if constexpr (std::is_same_v) { +// resultSet->GetString(columnIndex, value); +// } else if constexpr (std::is_same_v) { +// resultSet->GetLong(columnIndex, value); +// } else if constexpr (std::is_same_v) { +// int64_t t = 0; +// resultSet->GetLong(columnIndex, t); +// value = static_cast(t); +// } else if constexpr (std::is_same_v) { +// resultSet->GetInt(columnIndex, value); +// } else if constexpr (std::is_same_v) { +// int32_t t = 0; +// resultSet->GetInt(columnIndex, t); +// value = static_cast(t); +// } else if constexpr (std::is_same_v) { +// int32_t t = 0; +// resultSet->GetInt(columnIndex, t); +// value = static_cast(t); +// } else if constexpr (std::is_same_v) { +// int32_t t = 0; +// resultSet->GetInt(columnIndex, t); +// value = static_cast(t); +// } +// } +// } // namespace Notification +// } // namespace OHOS +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/services/ans/include/reminder_table.h b/services/ans/include/reminder_table.h index 4542000cd..364adde4f 100644 --- a/services/ans/include/reminder_table.h +++ b/services/ans/include/reminder_table.h @@ -1,272 +1,272 @@ -/* - * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H - -#include -#include - -namespace OHOS { -namespace Notification { -class ReminderBaseTable { -public: - /* - * reminder base table name - */ - static const std::string TABLE_NAME; - - /* - * reminder id - */ - static const std::string REMINDER_ID; - - /* - * package name - */ - static const std::string PACKAGE_NAME; - - /* - * user id - */ - static const std::string USER_ID; - - /* - * uid - */ - static const std::string UID; - - /* - * systerm app flag - */ - static const std::string SYSTEM_APP; - - /* - * reminder type: Timer/Calendar/Alarm - */ - static const std::string REMINDER_TYPE; - - /* - * reminder time - */ - static const std::string REMINDER_TIME; - - /* - * trigger time - */ - static const std::string TRIGGER_TIME; - - /* - * time interval - */ - static const std::string TIME_INTERVAL; - - /* - * snooze times - */ - static const std::string SNOOZE_TIMES; - - /* - * dynamic snooze times - */ - static const std::string DYNAMIC_SNOOZE_TIMES; - - /* - * ring duration - */ - static const std::string RING_DURATION; - - /* - * expired flag - */ - static const std::string IS_EXPIRED; - - /* - * reminder state - */ - static const std::string STATE; - - /* - * action button information - */ - static const std::string ACTION_BUTTON_INFO; - - /* - * custom button uri - */ - static const std::string CUSTOM_BUTTON_URI; - - /* - * slot type - */ - static const std::string SLOT_ID; - - /* - * snoozeslot type - */ - static const std::string SNOOZE_SLOT_ID; - - /* - * notification id - */ - static const std::string NOTIFICATION_ID; - - /* - * notification title - */ - static const std::string TITLE; - - /* - * notification content - */ - static const std::string CONTENT; - - /* - * notification snooze content - */ - static const std::string SNOOZE_CONTENT; - - /* - * notification expired content - */ - static const std::string EXPIRED_CONTENT; - - /* - * want agent information - */ - static const std::string WANT_AGENT; - - /* - * max screen want agent information - */ - static const std::string MAX_SCREEN_WANT_AGENT; - - /* - * tap dismissed flag - */ - static const std::string TAP_DISMISSED; - - /* - * auto deleted time - */ - static const std::string AUTO_DELETED_TIME; - - /* - * group id - */ - static const std::string GROUP_ID; - - /* - * custom ring uri - */ - static const std::string CUSTOM_RING_URI; - - /* - * creator bundle name - */ - static const std::string CREATOR_BUNDLE_NAME; - - /* - * creator uid - */ - static const std::string CREATOR_UID; - -public: - static void InitDbColumns(); - -public: - static std::string ADD_COLUMNS; - static std::string SELECT_COLUMNS; -}; - -class ReminderAlarmTable { -public: - /* - * reminder alarm table name - */ - static const std::string TABLE_NAME; - - /* - * reminder timer table field - */ - static const std::string REMINDER_ID; - static const std::string ALARM_HOUR; - static const std::string ALARM_MINUTE; - static const std::string REPEAT_DAYS_OF_WEEK; - -public: - static void InitDbColumns(); - -public: - static std::string ADD_COLUMNS; - static std::string SELECT_COLUMNS; -}; - -class ReminderCalendarTable { -public: - /* - * reminder calendar table name - */ - static const std::string TABLE_NAME; - - /* - * reminder calendar table field - */ - static const std::string REMINDER_ID; - static const std::string FIRST_DESIGNATE_YEAR; - static const std::string FIRST_DESIGNATE_MONTH; - static const std::string FIRST_DESIGNATE_DAY; - static const std::string CALENDAR_DATE_TIME; - static const std::string CALENDAR_END_DATE_TIME; - static const std::string REPEAT_DAYS; - static const std::string REPEAT_MONTHS; - static const std::string REPEAT_DAYS_OF_WEEK; - static const std::string RRULE_WANT_AGENT; - static const std::string EXCLUDE_DATES; - static const std::string CALENDAR_LAST_DATE_TIME; - -public: - static void InitDbColumns(); - -public: - static std::string ADD_COLUMNS; - static std::string SELECT_COLUMNS; -}; - -class ReminderTimerTable { -public: - /* - * reminder timer table name - */ - static const std::string TABLE_NAME; - - /* - * reminder timer table field - */ - static const std::string REMINDER_ID; - static const std::string TRIGGER_SECOND; - static const std::string START_DATE_TIME; - static const std::string END_DATE_TIME; - -public: - static void InitDbColumns(); - -public: - static std::string ADD_COLUMNS; - static std::string SELECT_COLUMNS; -}; -} // namespace Notification -} // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H +// /* +// * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H + +// #include +// #include + +// namespace OHOS { +// namespace Notification { +// class ReminderBaseTable { +// public: +// /* +// * reminder base table name +// */ +// static const std::string TABLE_NAME; + +// /* +// * reminder id +// */ +// static const std::string REMINDER_ID; + +// /* +// * package name +// */ +// static const std::string PACKAGE_NAME; + +// /* +// * user id +// */ +// static const std::string USER_ID; + +// /* +// * uid +// */ +// static const std::string UID; + +// /* +// * systerm app flag +// */ +// static const std::string SYSTEM_APP; + +// /* +// * reminder type: Timer/Calendar/Alarm +// */ +// static const std::string REMINDER_TYPE; + +// /* +// * reminder time +// */ +// static const std::string REMINDER_TIME; + +// /* +// * trigger time +// */ +// static const std::string TRIGGER_TIME; + +// /* +// * time interval +// */ +// static const std::string TIME_INTERVAL; + +// /* +// * snooze times +// */ +// static const std::string SNOOZE_TIMES; + +// /* +// * dynamic snooze times +// */ +// static const std::string DYNAMIC_SNOOZE_TIMES; + +// /* +// * ring duration +// */ +// static const std::string RING_DURATION; + +// /* +// * expired flag +// */ +// static const std::string IS_EXPIRED; + +// /* +// * reminder state +// */ +// static const std::string STATE; + +// /* +// * action button information +// */ +// static const std::string ACTION_BUTTON_INFO; + +// /* +// * custom button uri +// */ +// static const std::string CUSTOM_BUTTON_URI; + +// /* +// * slot type +// */ +// static const std::string SLOT_ID; + +// /* +// * snoozeslot type +// */ +// static const std::string SNOOZE_SLOT_ID; + +// /* +// * notification id +// */ +// static const std::string NOTIFICATION_ID; + +// /* +// * notification title +// */ +// static const std::string TITLE; + +// /* +// * notification content +// */ +// static const std::string CONTENT; + +// /* +// * notification snooze content +// */ +// static const std::string SNOOZE_CONTENT; + +// /* +// * notification expired content +// */ +// static const std::string EXPIRED_CONTENT; + +// /* +// * want agent information +// */ +// static const std::string WANT_AGENT; + +// /* +// * max screen want agent information +// */ +// static const std::string MAX_SCREEN_WANT_AGENT; + +// /* +// * tap dismissed flag +// */ +// static const std::string TAP_DISMISSED; + +// /* +// * auto deleted time +// */ +// static const std::string AUTO_DELETED_TIME; + +// /* +// * group id +// */ +// static const std::string GROUP_ID; + +// /* +// * custom ring uri +// */ +// static const std::string CUSTOM_RING_URI; + +// /* +// * creator bundle name +// */ +// static const std::string CREATOR_BUNDLE_NAME; + +// /* +// * creator uid +// */ +// static const std::string CREATOR_UID; + +// public: +// static void InitDbColumns(); + +// public: +// static std::string ADD_COLUMNS; +// static std::string SELECT_COLUMNS; +// }; + +// class ReminderAlarmTable { +// public: +// /* +// * reminder alarm table name +// */ +// static const std::string TABLE_NAME; + +// /* +// * reminder timer table field +// */ +// static const std::string REMINDER_ID; +// static const std::string ALARM_HOUR; +// static const std::string ALARM_MINUTE; +// static const std::string REPEAT_DAYS_OF_WEEK; + +// public: +// static void InitDbColumns(); + +// public: +// static std::string ADD_COLUMNS; +// static std::string SELECT_COLUMNS; +// }; + +// class ReminderCalendarTable { +// public: +// /* +// * reminder calendar table name +// */ +// static const std::string TABLE_NAME; + +// /* +// * reminder calendar table field +// */ +// static const std::string REMINDER_ID; +// static const std::string FIRST_DESIGNATE_YEAR; +// static const std::string FIRST_DESIGNATE_MONTH; +// static const std::string FIRST_DESIGNATE_DAY; +// static const std::string CALENDAR_DATE_TIME; +// static const std::string CALENDAR_END_DATE_TIME; +// static const std::string REPEAT_DAYS; +// static const std::string REPEAT_MONTHS; +// static const std::string REPEAT_DAYS_OF_WEEK; +// static const std::string RRULE_WANT_AGENT; +// static const std::string EXCLUDE_DATES; +// static const std::string CALENDAR_LAST_DATE_TIME; + +// public: +// static void InitDbColumns(); + +// public: +// static std::string ADD_COLUMNS; +// static std::string SELECT_COLUMNS; +// }; + +// class ReminderTimerTable { +// public: +// /* +// * reminder timer table name +// */ +// static const std::string TABLE_NAME; + +// /* +// * reminder timer table field +// */ +// static const std::string REMINDER_ID; +// static const std::string TRIGGER_SECOND; +// static const std::string START_DATE_TIME; +// static const std::string END_DATE_TIME; + +// public: +// static void InitDbColumns(); + +// public: +// static std::string ADD_COLUMNS; +// static std::string SELECT_COLUMNS; +// }; +// } // namespace Notification +// } // namespace OHOS +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H diff --git a/services/ans/include/reminder_table_old.h b/services/ans/include/reminder_table_old.h index 172541b49..3ab69aea2 100644 --- a/services/ans/include/reminder_table_old.h +++ b/services/ans/include/reminder_table_old.h @@ -1,239 +1,239 @@ -/* - * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H - -#include -#include - -namespace OHOS { -namespace Notification { -class ReminderTable { -public: - static void InitDbColumns(); - - static const std::string TABLE_NAME; - - // Reminder Table Basic Columns. - - /* - * reminder id - */ - static const std::string REMINDER_ID; - - /* - * package name - */ - static const std::string PKG_NAME; - - /* - * user id - */ - static const std::string USER_ID; - - /* - * uid - */ - static const std::string UID; - - /* - * systerm app flag - */ - static const std::string SYS_APP; - - /* - * app label - */ - static const std::string APP_LABEL; - - /* - * reminder type: Timer/Calendar/Alarm - */ - static const std::string REMINDER_TYPE; - - /* - * reminder time - */ - static const std::string REMINDER_TIME; - - /* - * trigger time - */ - static const std::string TRIGGER_TIME; - - /* - * RTC trigger time - */ - static const std::string RTC_TRIGGER_TIME; - - /* - * time interval - */ - static const std::string TIME_INTERVAL; - - /* - * snooze times - */ - static const std::string SNOOZE_TIMES; - - /* - * dynamic snooze times - */ - static const std::string DYNAMIC_SNOOZE_TIMES; - - /* - * ring duration - */ - static const std::string RING_DURATION; - - /* - * expired flag - */ - static const std::string IS_EXPIRED; - - /* - * active flag - */ - static const std::string IS_ACTIVE; - - /* - * reminder state - */ - static const std::string STATE; - - /* - * zone id - */ - static const std::string ZONE_ID; - - /* - * scheduled timeout flag - */ - static const std::string HAS_SCHEDULED_TIMEOUT; - - /* - * action button information - */ - static const std::string ACTION_BUTTON_INFO; - - /* - * custom button uri - */ - static const std::string CUSTOM_BUTTON_URI; - - /* - * slot type - */ - static const std::string SLOT_ID; - - /* - * snoozeslot type - */ - static const std::string SNOOZE_SLOT_ID; - - /* - * notification id - */ - static const std::string NOTIFICATION_ID; - - /* - * notification title - */ - static const std::string TITLE; - - /* - * notification content - */ - static const std::string CONTENT; - - /* - * notification snooze content - */ - static const std::string SNOOZE_CONTENT; - - /* - * notification expired content - */ - static const std::string EXPIRED_CONTENT; - - /* - * agent information - */ - static const std::string AGENT; - - /* - * max screen agent information - */ - static const std::string MAX_SCREEN_AGENT; - - /* - * tap dismissed flag - */ - static const std::string TAP_DISMISSED; - - /* - * auto deleted time - */ - static const std::string AUTO_DELETED_TIME; - - /* - * repeat days of week - */ - static const std::string REPEAT_DAYS_OF_WEEK; - - /* - * reminder group id - */ - static const std::string GROUP_ID; - - /* - * reminder ring uri - */ - static const std::string CUSTOM_RING_URI; - - /* - * reminder creator bundle name - */ - static const std::string CREATOR_BUNDLE_NAME; - - // Reminder Table Calendar Columns. - static const std::string REPEAT_DAYS; - static const std::string REPEAT_MONTHS; - static const std::string FIRST_DESIGNATE_YEAR; - static const std::string FIRST_DESIGNATE_MONTH; - static const std::string FIRST_DESIGNATE_DAY; - static const std::string CALENDAR_YEAR; - static const std::string CALENDAR_MONTH; - static const std::string CALENDAR_DAY; - static const std::string CALENDAR_HOUR; - static const std::string CALENDAR_MINUTE; - - // Reminder Table Alarm Columns. - static const std::string ALARM_HOUR; - static const std::string ALARM_MINUTE; - - static std::string ADD_COLUMNS; - static std::string SELECT_COLUMNS; - -private: - static void InitBasicColumns(); - static void InitCalendarColumns(); - static void InitAlarmColumns(); - static void AddColumn(const std::string& name, const std::string& type, bool isEnd = false); -}; -} // namespace Notification -} // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H +// /* +// * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H + +// #include +// #include + +// namespace OHOS { +// namespace Notification { +// class ReminderTable { +// public: +// static void InitDbColumns(); + +// static const std::string TABLE_NAME; + +// // Reminder Table Basic Columns. + +// /* +// * reminder id +// */ +// static const std::string REMINDER_ID; + +// /* +// * package name +// */ +// static const std::string PKG_NAME; + +// /* +// * user id +// */ +// static const std::string USER_ID; + +// /* +// * uid +// */ +// static const std::string UID; + +// /* +// * systerm app flag +// */ +// static const std::string SYS_APP; + +// /* +// * app label +// */ +// static const std::string APP_LABEL; + +// /* +// * reminder type: Timer/Calendar/Alarm +// */ +// static const std::string REMINDER_TYPE; + +// /* +// * reminder time +// */ +// static const std::string REMINDER_TIME; + +// /* +// * trigger time +// */ +// static const std::string TRIGGER_TIME; + +// /* +// * RTC trigger time +// */ +// static const std::string RTC_TRIGGER_TIME; + +// /* +// * time interval +// */ +// static const std::string TIME_INTERVAL; + +// /* +// * snooze times +// */ +// static const std::string SNOOZE_TIMES; + +// /* +// * dynamic snooze times +// */ +// static const std::string DYNAMIC_SNOOZE_TIMES; + +// /* +// * ring duration +// */ +// static const std::string RING_DURATION; + +// /* +// * expired flag +// */ +// static const std::string IS_EXPIRED; + +// /* +// * active flag +// */ +// static const std::string IS_ACTIVE; + +// /* +// * reminder state +// */ +// static const std::string STATE; + +// /* +// * zone id +// */ +// static const std::string ZONE_ID; + +// /* +// * scheduled timeout flag +// */ +// static const std::string HAS_SCHEDULED_TIMEOUT; + +// /* +// * action button information +// */ +// static const std::string ACTION_BUTTON_INFO; + +// /* +// * custom button uri +// */ +// static const std::string CUSTOM_BUTTON_URI; + +// /* +// * slot type +// */ +// static const std::string SLOT_ID; + +// /* +// * snoozeslot type +// */ +// static const std::string SNOOZE_SLOT_ID; + +// /* +// * notification id +// */ +// static const std::string NOTIFICATION_ID; + +// /* +// * notification title +// */ +// static const std::string TITLE; + +// /* +// * notification content +// */ +// static const std::string CONTENT; + +// /* +// * notification snooze content +// */ +// static const std::string SNOOZE_CONTENT; + +// /* +// * notification expired content +// */ +// static const std::string EXPIRED_CONTENT; + +// /* +// * agent information +// */ +// static const std::string AGENT; + +// /* +// * max screen agent information +// */ +// static const std::string MAX_SCREEN_AGENT; + +// /* +// * tap dismissed flag +// */ +// static const std::string TAP_DISMISSED; + +// /* +// * auto deleted time +// */ +// static const std::string AUTO_DELETED_TIME; + +// /* +// * repeat days of week +// */ +// static const std::string REPEAT_DAYS_OF_WEEK; + +// /* +// * reminder group id +// */ +// static const std::string GROUP_ID; + +// /* +// * reminder ring uri +// */ +// static const std::string CUSTOM_RING_URI; + +// /* +// * reminder creator bundle name +// */ +// static const std::string CREATOR_BUNDLE_NAME; + +// // Reminder Table Calendar Columns. +// static const std::string REPEAT_DAYS; +// static const std::string REPEAT_MONTHS; +// static const std::string FIRST_DESIGNATE_YEAR; +// static const std::string FIRST_DESIGNATE_MONTH; +// static const std::string FIRST_DESIGNATE_DAY; +// static const std::string CALENDAR_YEAR; +// static const std::string CALENDAR_MONTH; +// static const std::string CALENDAR_DAY; +// static const std::string CALENDAR_HOUR; +// static const std::string CALENDAR_MINUTE; + +// // Reminder Table Alarm Columns. +// static const std::string ALARM_HOUR; +// static const std::string ALARM_MINUTE; + +// static std::string ADD_COLUMNS; +// static std::string SELECT_COLUMNS; + +// private: +// static void InitBasicColumns(); +// static void InitCalendarColumns(); +// static void InitAlarmColumns(); +// static void AddColumn(const std::string& name, const std::string& type, bool isEnd = false); +// }; +// } // namespace Notification +// } // namespace OHOS +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h index 5ffc5b34a..1a63c8126 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -1,88 +1,88 @@ -/* - * Copyright (c) 2021-2022 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. - */ +// /* +// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +// #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H -#include "advanced_notification_service.h" -#include "itimer_info.h" -#include "notification_request.h" -#include "reminder_request.h" +// #include "advanced_notification_service.h" +// #include "itimer_info.h" +// #include "notification_request.h" +// #include "reminder_request.h" -namespace OHOS { -namespace Notification { -class ReminderTimerInfo : public MiscServices::ITimerInfo { -public: - ReminderTimerInfo() {}; - virtual ~ReminderTimerInfo() {}; +// namespace OHOS { +// namespace Notification { +// class ReminderTimerInfo : public MiscServices::ITimerInfo { +// public: +// ReminderTimerInfo() {}; +// virtual ~ReminderTimerInfo() {}; - ReminderTimerInfo(ReminderTimerInfo &other) = delete; - ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; +// ReminderTimerInfo(ReminderTimerInfo &other) = delete; +// ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; - inline void SetAction(const std::string &action) - { - action_ = action; - } +// inline void SetAction(const std::string &action) +// { +// action_ = action; +// } - inline void SetPid(const int32_t pid) - { - pid_ = pid; - } +// inline void SetPid(const int32_t pid) +// { +// pid_ = pid; +// } - inline void SetUid(const int32_t uid) - { - uid_ = uid; - } +// inline void SetUid(const int32_t uid) +// { +// uid_ = uid; +// } - inline void SetBundleName(const std::string &bundleName) - { - bundleName_ = bundleName; - } +// inline void SetBundleName(const std::string &bundleName) +// { +// bundleName_ = bundleName; +// } - /** - * When timing is up, this function will execute as call back. - */ - void OnTrigger() override; +// /** +// * When timing is up, this function will execute as call back. +// */ +// void OnTrigger() override; - /** - * Indicates the timing type. - */ - void SetType(const int32_t &type) override; +// /** +// * Indicates the timing type. +// */ +// void SetType(const int32_t &type) override; - /** - * Indicates the repeat policy. - */ - void SetRepeat(bool repeat) override; +// /** +// * Indicates the repeat policy. +// */ +// void SetRepeat(bool repeat) override; - /** - * Indicates the interval time for repeat timing. - */ - void SetInterval(const uint64_t &interval) override; +// /** +// * Indicates the interval time for repeat timing. +// */ +// void SetInterval(const uint64_t &interval) override; - /** - * Indicates the want agent information. - */ - void SetWantAgent(std::shared_ptr wantAgent) override; +// /** +// * Indicates the want agent information. +// */ +// void SetWantAgent(std::shared_ptr wantAgent) override; -private: - std::string action_; - int32_t pid_ {-1}; - int32_t uid_ {-1}; - std::string bundleName_; -}; -} // namespace OHOS -} // namespace Notification +// private: +// std::string action_; +// int32_t pid_ {-1}; +// int32_t uid_ {-1}; +// std::string bundleName_; +// }; +// } // namespace OHOS +// } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/ans/src/advanced_notification_reminder_service.cpp b/services/ans/src/advanced_notification_reminder_service.cpp index c6ff8843a..02a63b7a1 100644 --- a/services/ans/src/advanced_notification_reminder_service.cpp +++ b/services/ans/src/advanced_notification_reminder_service.cpp @@ -30,7 +30,6 @@ #include "notification_request.h" #include "os_account_manager.h" #include "hitrace_meter_adapter.h" -#include "reminder_data_manager.h" #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED #include "distributed_notification_manager.h" #include "distributed_preferences.h" @@ -41,207 +40,207 @@ namespace OHOS { namespace Notification { -inline bool AdvancedNotificationService::CheckReminderPermission() -{ - Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); - ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken( - callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER"); - return result == Security::AccessToken::PermissionState::PERMISSION_GRANTED; -} +// inline bool AdvancedNotificationService::CheckReminderPermission() +// { +// Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); +// ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken( +// callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER"); +// return result == Security::AccessToken::PermissionState::PERMISSION_GRANTED; +// } -ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Publish reminder"); - if (!reminder) { - ANSR_LOGE("ReminderRequest object is nullptr"); - return ERR_ANS_INVALID_PARAM; - } +// ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Publish reminder"); +// if (!reminder) { +// ANSR_LOGE("ReminderRequest object is nullptr"); +// return ERR_ANS_INVALID_PARAM; +// } - std::string bundle = GetClientBundleName(); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } - if (!AllowUseReminder(bundle)) { - ANSR_LOGW("The number of reminders exceeds the limit[0]."); - return ERR_REMINDER_NUMBER_OVERLOAD; - } - ANSR_LOGD("is system app: %{public}d", AccessTokenHelper::IsSystemApp()); - reminder->SetSystemApp(AccessTokenHelper::IsSystemApp()); - sptr notificationRequest = reminder->GetNotificationRequest(); - reminder->InitCreatorBundleName(bundle); - reminder->InitCreatorUid(IPCSkeleton::GetCallingUid()); - if (reminder->GetWantAgentInfo() == nullptr || reminder->GetMaxScreenWantAgentInfo() == nullptr) { - ANSR_LOGE("wantagent info is nullptr"); - return ERR_ANS_INVALID_PARAM; - } - std::string wantAgentName = reminder->GetWantAgentInfo()->pkgName; - std::string msWantAgentName = reminder->GetMaxScreenWantAgentInfo()->pkgName; - if (wantAgentName != msWantAgentName && wantAgentName != "" && msWantAgentName != "") { - ANSR_LOGE("wantAgentName is not same to msWantAgentName, wantAgentName:%{public}s, msWantAgentName:%{public}s", - wantAgentName.c_str(), msWantAgentName.c_str()); - return ERR_ANS_INVALID_PARAM; - } - if (wantAgentName != bundle && wantAgentName != "") { - ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(), - wantAgentName.c_str()); - SetAgentNotification(notificationRequest, wantAgentName); - } else if (msWantAgentName != bundle && msWantAgentName != "") { - ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(), - msWantAgentName.c_str()); - SetAgentNotification(notificationRequest, msWantAgentName); - } - sptr bundleOption = nullptr; - ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); - if (result != ERR_OK) { - ANSR_LOGW("PrepareNotificationInfo fail"); - return result; - } - bool allowedNotify = false; - result = IsAllowedNotifySelf(bundleOption, allowedNotify); - if (!reminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { - ANSR_LOGW("The application does not request enable notification"); - return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - return ERR_NO_INIT; - } - return rdm->PublishReminder(reminder, bundleOption); -} +// std::string bundle = GetClientBundleName(); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } +// if (!AllowUseReminder(bundle)) { +// ANSR_LOGW("The number of reminders exceeds the limit[0]."); +// return ERR_REMINDER_NUMBER_OVERLOAD; +// } +// ANSR_LOGD("is system app: %{public}d", AccessTokenHelper::IsSystemApp()); +// reminder->SetSystemApp(AccessTokenHelper::IsSystemApp()); +// sptr notificationRequest = reminder->GetNotificationRequest(); +// reminder->InitCreatorBundleName(bundle); +// reminder->InitCreatorUid(IPCSkeleton::GetCallingUid()); +// if (reminder->GetWantAgentInfo() == nullptr || reminder->GetMaxScreenWantAgentInfo() == nullptr) { +// ANSR_LOGE("wantagent info is nullptr"); +// return ERR_ANS_INVALID_PARAM; +// } +// std::string wantAgentName = reminder->GetWantAgentInfo()->pkgName; +// std::string msWantAgentName = reminder->GetMaxScreenWantAgentInfo()->pkgName; +// if (wantAgentName != msWantAgentName && wantAgentName != "" && msWantAgentName != "") { +// ANSR_LOGE("wantAgentName is not same to msWantAgentName, wantAgentName:%{public}s, msWantAgentName:%{public}s", +// wantAgentName.c_str(), msWantAgentName.c_str()); +// return ERR_ANS_INVALID_PARAM; +// } +// if (wantAgentName != bundle && wantAgentName != "") { +// ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(), +// wantAgentName.c_str()); +// SetAgentNotification(notificationRequest, wantAgentName); +// } else if (msWantAgentName != bundle && msWantAgentName != "") { +// ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(), +// msWantAgentName.c_str()); +// SetAgentNotification(notificationRequest, msWantAgentName); +// } +// sptr bundleOption = nullptr; +// ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); +// if (result != ERR_OK) { +// ANSR_LOGW("PrepareNotificationInfo fail"); +// return result; +// } +// bool allowedNotify = false; +// result = IsAllowedNotifySelf(bundleOption, allowedNotify); +// if (!reminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { +// ANSR_LOGW("The application does not request enable notification"); +// return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// return ERR_NO_INIT; +// } +// return rdm->PublishReminder(reminder, bundleOption); +// } -ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Cancel Reminder"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Cancel Reminder"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - return ERR_NO_INIT; - } - return rdm->CancelReminder(reminderId, bundleOption); -} +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// return ERR_ANS_INVALID_BUNDLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// return ERR_NO_INIT; +// } +// return rdm->CancelReminder(reminderId, bundleOption); +// } -ErrCode AdvancedNotificationService::CancelAllReminders() -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Cancel all reminders"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::CancelAllReminders() +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Cancel all reminders"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - int32_t userId = -1; - AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - return ERR_NO_INIT; - } - return rdm->CancelAllReminders(bundleOption->GetBundleName(), userId, bundleOption->GetUid()); -} +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// return ERR_ANS_INVALID_BUNDLE; +// } +// int32_t userId = -1; +// AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// return ERR_NO_INIT; +// } +// return rdm->CancelAllReminders(bundleOption->GetBundleName(), userId, bundleOption->GetUid()); +// } -ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("GetValidReminders"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("GetValidReminders"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - reminders.clear(); - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - return ERR_NO_INIT; - } - rdm->GetValidReminders(bundleOption, reminders); - ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); - return ERR_OK; -} +// reminders.clear(); +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// return ERR_ANS_INVALID_BUNDLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// return ERR_NO_INIT; +// } +// rdm->GetValidReminders(bundleOption, reminders); +// ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); +// return ERR_OK; +// } -ErrCode AdvancedNotificationService::AddExcludeDate(const int32_t reminderId, const uint64_t date) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Add Exclude Date"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::AddExcludeDate(const int32_t reminderId, const uint64_t date) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Add Exclude Date"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - ANSR_LOGW("Generate bundle option failed!"); - return ERR_ANS_INVALID_BUNDLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - ANSR_LOGW("Reminder data manager not init!"); - return ERR_NO_INIT; - } - return rdm->AddExcludeDate(reminderId, date, bundleOption); -} +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// ANSR_LOGW("Generate bundle option failed!"); +// return ERR_ANS_INVALID_BUNDLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// ANSR_LOGW("Reminder data manager not init!"); +// return ERR_NO_INIT; +// } +// return rdm->AddExcludeDate(reminderId, date, bundleOption); +// } -ErrCode AdvancedNotificationService::DelExcludeDates(const int32_t reminderId) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Del Exclude Dates"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::DelExcludeDates(const int32_t reminderId) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Del Exclude Dates"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - ANSR_LOGW("Generate bundle option failed!"); - return ERR_ANS_INVALID_BUNDLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - ANSR_LOGW("Reminder data manager not init!"); - return ERR_NO_INIT; - } - return rdm->DelExcludeDates(reminderId, bundleOption); -} +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// ANSR_LOGW("Generate bundle option failed!"); +// return ERR_ANS_INVALID_BUNDLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// ANSR_LOGW("Reminder data manager not init!"); +// return ERR_NO_INIT; +// } +// return rdm->DelExcludeDates(reminderId, bundleOption); +// } -ErrCode AdvancedNotificationService::GetExcludeDates(const int32_t reminderId, std::vector& dates) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("Get Exclude Dates"); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } +// ErrCode AdvancedNotificationService::GetExcludeDates(const int32_t reminderId, std::vector& dates) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("Get Exclude Dates"); +// if (!CheckReminderPermission()) { +// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); +// return ERR_REMINDER_PERMISSION_DENIED; +// } - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - ANSR_LOGW("Generate bundle option failed!"); - return ERR_ANS_INVALID_BUNDLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - ANSR_LOGW("Reminder data manager not init!"); - return ERR_NO_INIT; - } - return rdm->GetExcludeDates(reminderId, bundleOption, dates); -} +// sptr bundleOption = GenerateBundleOption(); +// if (bundleOption == nullptr) { +// ANSR_LOGW("Generate bundle option failed!"); +// return ERR_ANS_INVALID_BUNDLE; +// } +// auto rdm = ReminderDataManager::GetInstance(); +// if (rdm == nullptr) { +// ANSR_LOGW("Reminder data manager not init!"); +// return ERR_NO_INIT; +// } +// return rdm->GetExcludeDates(reminderId, bundleOption, dates); +// } #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED NotificationConstant::RemindType AdvancedNotificationService::GetRemindType() diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 093ce403e..aa303ddb3 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -590,7 +590,7 @@ ErrCode AdvancedNotificationService::FillNotificationRecord( ANS_LOGE("Failed to create notification."); return ERR_ANS_NO_MEMORY; } - SetNotificationRemindType(record->notification, true); + //fengyang SetNotificationRemindType(record->notification, true); record->bundleOption = requestdbObj.bundleOption; ErrCode ret = AssignValidNotificationSlot(record, record->bundleOption); diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 2b444241a..1953c6a0e 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -46,7 +46,7 @@ void AdvancedNotificationServiceAbility::OnStart() } service_->CreateDialogManager(); service_->InitPublishProcess(); - reminderAgent_ = ReminderDataManager::InitInstance(service_); + // reminderAgent_ = ReminderDataManager::InitInstance(service_); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->InitExtentionWrapper(); @@ -64,7 +64,7 @@ void AdvancedNotificationServiceAbility::OnStart() void AdvancedNotificationServiceAbility::OnStop() { service_ = nullptr; - reminderAgent_ = nullptr; + // reminderAgent_ = nullptr; } void AdvancedNotificationServiceAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) diff --git a/services/ans/src/reminder_config_change_observer.cpp b/services/ans/src/reminder_config_change_observer.cpp index e0efc126f..03ce6e250 100644 --- a/services/ans/src/reminder_config_change_observer.cpp +++ b/services/ans/src/reminder_config_change_observer.cpp @@ -1,41 +1,41 @@ -/* - * Copyright (c) 2023 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. - */ +// /* +// * Copyright (c) 2023 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 "reminder_config_change_observer.h" +// #include "reminder_config_change_observer.h" -#include "ans_log_wrapper.h" -#include "reminder_data_manager.h" +// #include "ans_log_wrapper.h" +// #include "reminder_data_manager.h" -namespace OHOS { -namespace Notification { +// namespace OHOS { +// namespace Notification { -void ReminderConfigChangeObserver::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) -{ - ANSR_LOGD("OnConfigurationUpdated."); - auto reminderDataMgr = ReminderDataManager::GetInstance(); - if (reminderDataMgr == nullptr) { - ANSR_LOGW("Reminder data manager is nullptr"); - return; - } - std::string newLanguageInfo = configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE); - if (!newLanguageInfo.empty() && newLanguageInfo != languageInfo_) { - ANSR_LOGD("language change: %{public}s -> %{public}s", languageInfo_.c_str(), newLanguageInfo.c_str()); - reminderDataMgr->OnLanguageChanged(); - languageInfo_ = newLanguageInfo; - } -} +// void ReminderConfigChangeObserver::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) +// { +// ANSR_LOGD("OnConfigurationUpdated."); +// auto reminderDataMgr = ReminderDataManager::GetInstance(); +// if (reminderDataMgr == nullptr) { +// ANSR_LOGW("Reminder data manager is nullptr"); +// return; +// } +// std::string newLanguageInfo = configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE); +// if (!newLanguageInfo.empty() && newLanguageInfo != languageInfo_) { +// ANSR_LOGD("language change: %{public}s -> %{public}s", languageInfo_.c_str(), newLanguageInfo.c_str()); +// reminderDataMgr->OnLanguageChanged(); +// languageInfo_ = newLanguageInfo; +// } +// } -} // namespace Notification -} // namespace OHOS +// } // namespace Notification +// } // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index f682fc1b7..185ab9c7c 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -1,2073 +1,2073 @@ -/* - * Copyright (c) 2021-2023 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 "reminder_data_manager.h" - -#include "ability_manager_client.h" -#include "access_token_helper.h" -#include "ans_log_wrapper.h" -#include "ans_const_define.h" -#include "common_event_support.h" -#include "common_event_manager.h" -#include "reminder_request_calendar.h" -#include "in_process_call_wrapper.h" -#ifdef DEVICE_STANDBY_ENABLE -#include "standby_service_client.h" -#include "allow_type.h" -#endif -#include "ipc_skeleton.h" -#include "notification_slot.h" -#include "os_account_manager.h" -#include "os_account_manager_helper.h" -#include "reminder_event_manager.h" -#include "time_service_client.h" -#include "singleton.h" -#include "locale_config.h" -#include "bundle_manager_helper.h" -#include "datashare_predicates_object.h" -#include "datashare_value_object.h" -#include "datashare_helper.h" -#include "data_share_permission.h" -#include "datashare_errno.h" -#include "datashare_template.h" -#include "system_ability_definition.h" -#include "app_mgr_constants.h" -#include "iservice_registry.h" -#include "config_policy_utils.h" -#include "hitrace_meter_adapter.h" -#ifdef HAS_HISYSEVENT_PART -#include "hisysevent.h" -#endif - -namespace OHOS { -namespace Notification { -namespace { -const std::string ALL_PACKAGES = "allPackages"; -const int32_t MAIN_USER_ID = 100; -#ifdef DEVICE_STANDBY_ENABLE -const int REASON_APP_API = 1; -#endif -const int INDEX_KEY = 0; -const int INDEX_TYPE = 1; -const int INDEX_VALUE = 2; -} - -/** - * Default reminder sound. - */ -const std::string DEFAULT_REMINDER_SOUND_1 = "/system/etc/capture.ogg"; -const std::string DEFAULT_REMINDER_SOUND_2 = "resource/media/audio/alarms/Aegean_Sea.ogg"; - -std::shared_ptr ReminderDataManager::REMINDER_DATA_MANAGER = nullptr; -std::mutex ReminderDataManager::MUTEX; -std::mutex ReminderDataManager::SHOW_MUTEX; -std::mutex ReminderDataManager::ALERT_MUTEX; -std::mutex ReminderDataManager::TIMER_MUTEX; -std::mutex ReminderDataManager::ACTIVE_MUTEX; -constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100; -constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 3; -std::shared_ptr ReminderDataManager::serviceQueue_ = nullptr; -ReminderDataManager::~ReminderDataManager() = default; - -ErrCode ReminderDataManager::PublishReminder(const sptr &reminder, - const sptr &bundleOption) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID(); - if (callerTokenId == 0) { - ANSR_LOGE("pushlish failed, callerTokenId is 0"); - return ERR_REMINDER_CALLER_TOKEN_INVALID; - } - - if (!IsActionButtonDataShareValid(reminder, callerTokenId)) { - return ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED; - } - - if (CheckReminderLimitExceededLocked(bundleOption, reminder)) { - return ERR_REMINDER_NUMBER_OVERLOAD; - } - UpdateAndSaveReminderLocked(reminder, bundleOption); - queue_->submit([this, reminder]() { - StartRecentReminder(); - }); - return ERR_OK; -} - -ErrCode ReminderDataManager::CancelReminder( - const int32_t &reminderId, const sptr &bundleOption) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGI("cancel reminder id: %{public}d", reminderId); - sptr reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName()); - if (reminder == nullptr) { - ANSR_LOGW("Cancel reminder, not find the reminder"); - return ERR_REMINDER_NOT_EXIST; - } - if (!CheckIsSameApp(reminder, bundleOption)) { - ANSR_LOGW("Not find the reminder due to not match"); - return ERR_REMINDER_NOT_EXIST; - } - if (activeReminderId_ == reminderId) { - ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId); - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_->OnStop(); - } - StopTimerLocked(TimerType::TRIGGER_TIMER); - } - if (alertingReminderId_ == reminderId) { - StopSoundAndVibrationLocked(reminder); - StopTimerLocked(TimerType::ALERTING_TIMER); - } - CancelNotification(reminder); - RemoveReminderLocked(reminderId); - StartRecentReminder(); - return ERR_OK; -} - -ErrCode ReminderDataManager::CancelAllReminders(const std::string& packageName, const int32_t userId, - const int32_t uid) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - ANSR_LOGD("CancelAllReminders, userId=%{private}d, pkgName=%{public}s", userId, packageName.c_str()); - CancelRemindersImplLocked(packageName, userId, uid); - return ERR_OK; -} - -sptr ReminderDataManager::CheckExcludeDateParam(const int32_t reminderId, - const sptr &bundleOption) -{ - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGW("Check reminder failed, not find the reminder"); - return nullptr; - } - if (!CheckIsSameApp(reminder, bundleOption)) { - ANSR_LOGW("Check reminder failed, due to not match"); - return nullptr; - } - if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR - || !reminder->IsRepeat()) { - ANSR_LOGW("Check reminder failed, due to type not match or not repeat"); - return nullptr; - } - return reminder; -} - -ErrCode ReminderDataManager::AddExcludeDate(const int32_t reminderId, const uint64_t date, - const sptr &bundleOption) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); - if (reminder == nullptr) { - return ERR_REMINDER_NOT_EXIST; - } - { - std::lock_guard locker(ReminderDataManager::MUTEX); - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - calendar->AddExcludeDate(date); - store_->UpdateOrInsert(reminder, bundleOption); - } - return ERR_OK; -} - -ErrCode ReminderDataManager::DelExcludeDates(const int32_t reminderId, - const sptr &bundleOption) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); - if (reminder == nullptr) { - return ERR_REMINDER_NOT_EXIST; - } - { - std::lock_guard locker(ReminderDataManager::MUTEX); - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - calendar->DelExcludeDates(); - store_->UpdateOrInsert(reminder, bundleOption); - } - return ERR_OK; -} - -ErrCode ReminderDataManager::GetExcludeDates(const int32_t reminderId, - const sptr &bundleOption, std::vector& dates) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); - if (reminder == nullptr) { - return ERR_REMINDER_NOT_EXIST; - } - { - std::lock_guard locker(ReminderDataManager::MUTEX); - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - dates = calendar->GetExcludeDates(); - } - return ERR_OK; -} - -void ReminderDataManager::GetValidReminders( - const sptr &bundleOption, std::vector> &reminders) -{ - HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto& eachReminder : reminderVector_) { - if (eachReminder->IsExpired()) { - continue; - } - - if (CheckIsSameApp(eachReminder, bundleOption)) { - reminders.push_back(eachReminder); - } - } -} - -void ReminderDataManager::CancelAllReminders(const int32_t userId) -{ - ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); - CancelRemindersImplLocked(ALL_PACKAGES, userId, -1); -} - -void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, - const int32_t uid) -{ - MUTEX.lock(); - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - if (activeReminderId_ != -1 && IsMatched(activeReminder_, packageName, userId, uid)) { - activeReminder_->OnStop(); - StopTimer(TimerType::TRIGGER_TIMER); - ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_.load()); - } - } - for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { - if (IsMatched(*vit, packageName, userId, uid)) { - if ((*vit)->IsAlerting()) { - StopAlertingReminder(*vit); - } - CancelNotification(*vit); - RemoveFromShowedReminders(*vit); - vit = reminderVector_.erase(vit); - totalCount_--; - continue; - } - ++vit; - } - if (packageName == ALL_PACKAGES) { - store_->DeleteUser(userId); - } else { - store_->Delete(packageName, userId, uid); - } - MUTEX.unlock(); - StartRecentReminder(); -} - -bool ReminderDataManager::IsMatchedForGroupIdAndPkgName(const sptr &reminder, - const std::string &packageName, const std::string &groupId) const -{ - std::string packageNameTemp = reminder->GetBundleName(); - if (packageNameTemp.empty()) { - ANSR_LOGW("reminder package name is null"); - return false; - } - if (packageNameTemp == packageName && reminder->GetGroupId() == groupId) { - return true; - } - return false; -} - -bool ReminderDataManager::IsMatched(const sptr &reminder, - const std::string &packageName, const int32_t userId, const int32_t uid) const -{ - if (reminder->GetUserId() != userId) { - return false; - } - if (packageName == ALL_PACKAGES) { - return true; - } - if (reminder->GetBundleName() != packageName) { - return false; - } - if (uid != -1 && reminder->GetUid() == uid) { - return true; - } - return false; -} - -void ReminderDataManager::CancelNotification(const sptr &reminder) const -{ - if (!(reminder->IsShowing())) { - ANSR_LOGD("No need to cancel notification"); - return; - } - sptr notification = reminder->GetNotificationRequest(); - if (notification == nullptr) { - ANSR_LOGW("Cancel notification fail"); - return; - } - ANSR_LOGD("Cancel notification"); - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Cancel notification fail"); - return; - } - sptr bundleOption = reminder->GetNotificationBundleOption(); - advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), - ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); -} - -bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption, - const sptr &reminder) const -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { - ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ - and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); - return true; - } - int32_t count = 0; - for (const auto& eachReminder : reminderVector_) { - if (eachReminder->IsExpired()) { - continue; - } - if (CheckIsSameApp(eachReminder, bundleOption)) { - count++; - } - } - auto maxReminderNum = reminder->IsSystemApp() ? MAX_NUM_REMINDER_LIMIT_SYS_APP : MAX_NUM_REMINDER_LIMIT_APP; - if (count >= maxReminderNum) { - ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ - reminder can not be published", maxReminderNum); - return true; - } - return false; -} - -void ReminderDataManager::AddToShowedReminders(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { - if (reminder->GetReminderId() == (*it)->GetReminderId()) { - ANSR_LOGD("Showed reminder is already exist"); - return; - } - } - showedReminderVector_.push_back(reminder); -} - -void ReminderDataManager::OnUserRemove(const int32_t& userId) -{ - if (!IsReminderAgentReady()) { - ANSR_LOGW("Give up to remove user id: %{private}d for reminderAgent is not ready", userId); - return; - } - CancelAllReminders(userId); -} - -void ReminderDataManager::OnUserSwitch(const int32_t& userId) -{ - ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); - currentUserId_ = userId; - std::lock_guard lock(ReminderDataManager::MUTEX); - if ((alertingReminderId_ != -1) && IsReminderAgentReady()) { - TerminateAlerting(alertingReminder_, "OnUserSwitch"); - } -} - -void ReminderDataManager::OnProcessDiedLocked(const sptr &bundleOption) -{ - std::string bundleName = bundleOption->GetBundleName(); - int32_t uid = bundleOption->GetUid(); - ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); - std::lock_guard locker(ReminderDataManager::MUTEX); - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { - if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) { - continue; - } - if ((*it)->IsAlerting()) { - TerminateAlerting((*it), "onProcessDied"); - } else { - CancelNotification(*it); - (*it)->OnClose(false); - showedReminderVector_.erase(it); - --it; - } - store_->UpdateOrInsert((*it), bundleOption); - } -} - -void ReminderDataManager::InitTimerInfo(std::shared_ptr &sharedTimerInfo, - const sptr &reminderRequest, TimerType reminderType) const -{ - uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); - uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); - sharedTimerInfo->SetRepeat(false); - sharedTimerInfo->SetInterval(0); - - sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); - sharedTimerInfo->SetUid(reminderRequest->GetUid()); - - int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); - sharedTimerInfo->SetType(timerType); -} - -std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type, - const sptr &reminderRequest) const -{ - auto sharedTimerInfo = std::make_shared(); - if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { - ANSR_LOGE("Failed to set timer type."); - return nullptr; - } - InitTimerInfo(sharedTimerInfo, reminderRequest, type); - - int32_t requestCode = 10; - std::vector flags; - flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); - - auto want = std::make_shared(); - switch (type) { - case (TimerType::TRIGGER_TIMER): { - want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); - sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); - want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_); - break; - } - case (TimerType::ALERTING_TIMER): { - if (alertingReminderId_ == -1) { - ANSR_LOGE("Create alerting time out timer Illegal."); - return sharedTimerInfo; - } - want->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); - sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); - want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_); - break; - } - default: - ANSR_LOGE("TimerType not support"); - break; - } - std::vector> wants; - wants.push_back(want); - AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( - requestCode, - AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, - flags, wants, nullptr); - - std::string identity = IPCSkeleton::ResetCallingIdentity(); - std::shared_ptr wantAgent = - AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); - IPCSkeleton::SetCallingIdentity(identity); - - sharedTimerInfo->SetWantAgent(wantAgent); - return sharedTimerInfo; -} - -sptr ReminderDataManager::FindReminderRequestLocked(const int32_t &reminderId) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - if (reminderId == (*it)->GetReminderId()) { - return *it; - } - } - ANSR_LOGD("Not find the reminder"); - return nullptr; -} - -sptr ReminderDataManager::FindReminderRequestLocked( - const int32_t &reminderId, const std::string &pkgName) -{ - sptr reminder = FindReminderRequestLocked(reminderId); - std::lock_guard lock(ReminderDataManager::MUTEX); - if (reminder == nullptr) { - return nullptr; - } - if (reminder->GetCreatorBundleName() != pkgName) { - ANSR_LOGW("Not find the reminder due to package name not match"); - return nullptr; - } - return reminder; -} - -bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) -{ - return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); -} - -void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); - return; - } - std::string packageName = reminder->GetBundleName(); - std::string groupId = reminder->GetGroupId(); - if (!(packageName.empty() || groupId.empty())) { - ANSR_LOGD("this reminder can close by groupId"); - CloseRemindersByGroupId(reminderId, packageName, groupId); - } - CloseReminder(reminder, cancelNotification); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); - StartRecentReminder(); -} - -void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, - const std::string &groupId) -{ - if (packageName == "") { - ANSR_LOGD("packageName is empty"); - return; - } - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto vit = reminderVector_.begin(); vit != reminderVector_.end(); vit++) { - sptr reminder = *vit; - if (reminder == nullptr) { - ANSR_LOGD("reminder is null"); - continue; - } - int32_t reminderId = reminder->GetReminderId(); - if (reminderId == oldReminderId) { - ANSR_LOGD("The old and new reminder are the same"); - continue; - } - if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { - reminder->SetExpired(true); - reminder->SetStateToInActive(); - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - ResetStates(TimerType::TRIGGER_TIMER); - ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); - } - } -} - -void ReminderDataManager::CloseReminder(const sptr &reminder, bool cancelNotification) -{ - int32_t reminderId = reminder->GetReminderId(); - if (activeReminderId_ == reminderId) { - ANSR_LOGD("Stop active reminder due to CloseReminder"); - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_->OnStop(); - } - StopTimerLocked(TimerType::TRIGGER_TIMER); - } - if (alertingReminderId_ == reminderId) { - StopSoundAndVibrationLocked(reminder); - StopTimerLocked(TimerType::ALERTING_TIMER); - } - reminder->OnClose(true); - RemoveFromShowedReminders(reminder); - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - if (cancelNotification) { - CancelNotification(reminder); - } -} - -std::shared_ptr ReminderDataManager::GetInstance() -{ - return REMINDER_DATA_MANAGER; -} - -std::shared_ptr ReminderDataManager::InitInstance( - const sptr &advancedNotificationService) -{ - if (REMINDER_DATA_MANAGER == nullptr) { - REMINDER_DATA_MANAGER = std::make_shared(); - REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; - ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); - } - return REMINDER_DATA_MANAGER; -} - -bool ReminderDataManager::CheckUpdateConditions(const sptr &reminder, - const ReminderRequest::ActionButtonType &actionButtonType, - const std::map &actionButtonMap) -{ - if (!reminder->IsSystemApp()) { - ANSR_LOGI("UpdateAppDatabase faild, is not SystemApp"); - return false; - } - if (actionButtonType == ReminderRequest::ActionButtonType::INVALID) { - ANSR_LOGI("actionButtonType is NVALID"); - return false; - } - if (!actionButtonMap.count(actionButtonType)) { - ANSR_LOGI("actionButtonType does not exist"); - return false; - } - if (actionButtonMap.at(actionButtonType).dataShareUpdate == nullptr) { - ANSR_LOGI("dataShareUpdate is null"); - return false; - } - if (actionButtonMap.at(actionButtonType).dataShareUpdate->uri == "" || - actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo == "" || - actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket == "") { - ANSR_LOGI("datashare parameter is invalid"); - return false; - } - return true; -} - -void ReminderDataManager::UpdateAppDatabase(const sptr &reminder, - const ReminderRequest::ActionButtonType &actionButtonType) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - auto actionButtonMap = reminder->GetActionButtons(); - if (!CheckUpdateConditions(reminder, actionButtonType, actionButtonMap)) { - return; - } - // init default dstBundleName - std::string dstBundleName = reminder->GetBundleName(); - GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); - - DataShare::CreateOptions options; - options.enabled_ = true; - auto userID = reminder->GetUserId(); - auto tokenID = IPCSkeleton::GetSelfTokenID(); - std::string uriStr = actionButtonMap.at(actionButtonType).dataShareUpdate->uri + "?user=" + std::to_string(userID) + - "&srcToken=" + std::to_string(tokenID) + "&dstBundleName=" + dstBundleName; - - // create datashareHelper - std::shared_ptr dataShareHelper = DataShare::DataShareHelper::Creator(uriStr, options); - if (dataShareHelper == nullptr) { - ANSR_LOGE("create datashareHelper failed"); - return; - } - // gen uri equalTo valuesBucket - Uri uri(uriStr); - - DataShare::DataSharePredicates predicates; - std::vector equalToVector = ReminderRequest::StringSplit( - actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo, ReminderRequest::SEP_BUTTON_VALUE_TYPE); - GenPredicates(predicates, equalToVector); - - DataShare::DataShareValuesBucket valuesBucket; - std::vector valuesBucketVector = ReminderRequest::StringSplit( - actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket, ReminderRequest::SEP_BUTTON_VALUE_TYPE); - GenValuesBucket(valuesBucket, valuesBucketVector); - - // update app store - int retVal = dataShareHelper->Update(uri, predicates, valuesBucket); - if (retVal > 0) { - // update success - ANSR_LOGI("update app store success retval:%{public}d", retVal); - } -} - -void ReminderDataManager::GenPredicates(DataShare::DataSharePredicates &predicates, - const std::vector &equalToVector) -{ - // predicates - for (auto &it : equalToVector) { - std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); - if (temp.size() <= INDEX_VALUE) { - continue; - } - if (temp[INDEX_TYPE] == "string") { - predicates.EqualTo(temp[INDEX_KEY], temp[INDEX_VALUE]); - } else if (temp[INDEX_TYPE] == "double") { - predicates.EqualTo(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); - } else if (temp[INDEX_TYPE] == "bool") { - bool valueBool = false; - if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true" || temp[INDEX_VALUE] == "True") { - valueBool = true; - } - predicates.EqualTo(temp[INDEX_KEY], valueBool); - } - } -} - -void ReminderDataManager::GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket, - const std::vector &valuesBucketVector) -{ - // valuesBucket - for (auto &it : valuesBucketVector) { - std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); - if (temp.size() <= INDEX_VALUE) { - continue; - } - if (temp[INDEX_TYPE] == "string") { - valuesBucket.Put(temp[INDEX_KEY], temp[INDEX_VALUE]); - } else if (temp[INDEX_TYPE] == "double") { - valuesBucket.Put(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); - } else if (temp[INDEX_TYPE] == "bool") { - bool valueBool = false; - if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true") { - valueBool = true; - } - valuesBucket.Put(temp[INDEX_KEY], valueBool); - } else if (temp[INDEX_TYPE] == "null") { - valuesBucket.Put(temp[INDEX_KEY]); - } else if (temp[INDEX_TYPE] == "vector") { - std::vector arr = ReminderRequest::StringSplit(temp[INDEX_VALUE], - ReminderRequest::SEP_BUTTON_VALUE_BLOB); - std::vector value; - for (auto &num : arr) { - value.emplace_back(static_cast(std::atoi(num.c_str()))); - } - valuesBucket.Put(temp[INDEX_KEY], value); - } - } -} - -void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std::string &uri) const -{ - size_t left = 0; - size_t right = 0; - left = uri.find("/", left); - right = uri.find("/", left + 1); - while (right != std::string::npos && right - left <= 1) { - left = right + 1; - right = uri.find("/", left); - } - if (left == std::string::npos) { - return; - } - if (right != std::string::npos) { - dstBundleName = uri.substr(left, right - left); - } else { - dstBundleName = uri.substr(left); - } -} - -void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) -{ - if (!IsSystemReady()) { - ANSR_LOGW("bundle service or ability service not ready."); - return; - } - std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; - ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); - if (activeReminderId_ != -1) { - ANSR_LOGD("Stop active reminder due to date/time or timeZone change"); - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_->OnStop(); - } - StopTimerLocked(TimerType::TRIGGER_TIMER); - } - std::vector> showImmediately; - std::vector> extensionReminders; - RefreshRemindersLocked(type, showImmediately, extensionReminders); - HandleImmediatelyShow(showImmediately, true); - HandleExtensionReminder(extensionReminders); - StartRecentReminder(); -} - -void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); - return; - } - TerminateAlerting(reminder, "timeOut"); -} - -void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder) -{ - sleep(waitInSecond); - TerminateAlerting(reminder, "waitInMillis"); -} - -void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) -{ - if (reminder == nullptr) { - ANSR_LOGE("TerminateAlerting illegal."); - return; - } - ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", - reminder->Dump().c_str(), reason.c_str()); - StopAlertingReminder(reminder); - - if (!reminder->OnTerminate()) { - return; - } - int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = reminder->GetNotificationBundleOption(); - sptr notificationRequest = reminder->GetNotificationRequest(); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); - return; - } - ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); - UpdateNotification(reminder, false); - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Ans instance is null."); - return; - } - // Set the notification SoundEnabled and VibrationEnabled by soltType - advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - store_->UpdateOrInsert(reminder, bundleOption); -} - -void ReminderDataManager::UpdateAndSaveReminderLocked( - const sptr &reminder, const sptr &bundleOption) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - reminder->InitReminderId(); - int32_t userId = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); - reminder->InitUserId(userId); - reminder->InitUid(bundleOption->GetUid()); - reminder->InitBundleName(bundleOption->GetBundleName()); - - if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) { - ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); - reminder->SetExpired(true); - } - reminder->SetNotificationBundleOption(bundleOption); - reminderVector_.push_back(reminder); - totalCount_++; - store_->UpdateOrInsert(reminder, bundleOption); -} - -void ReminderDataManager::SetService(sptr &advancedNotificationService) -{ - advancedNotificationService_ = advancedNotificationService; -} - -bool ReminderDataManager::ShouldAlert(const sptr &reminder) const -{ - if (reminder == nullptr) { - return false; - } - int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = reminder->GetNotificationBundleOption(); - if (bundleOption == nullptr) { - ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); - return false; - } - int32_t userId = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); - if (currentUserId_ != userId) { - ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ - "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); - return false; - } - - sptr date; - ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); - if (errCode != ERR_OK) { - ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); - return true; - } - if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { - return true; - } - std::vector> slots; - errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); - if (errCode != ERR_OK) { - ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); - return false; - } - for (auto slot : slots) { - if (slot->GetType() != reminder->GetSlotType()) { - continue; - } - if (slot->IsEnableBypassDnd()) { - ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId); - return true; - } - } - ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId); - return false; -} - -void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId); - if (reminderId == activeReminderId_) { - ResetStates(TimerType::TRIGGER_TIMER); - } - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); - return; - } - if (HandleSysTimeChange(reminder)) { - return; - } - ShowActiveReminderExtendLocked(reminder); - StartRecentReminder(); -} - -bool ReminderDataManager::HandleSysTimeChange(const sptr reminder) const -{ - if (reminder->CanShow()) { - return false; - } else { - ANSR_LOGI("handleSystimeChange, no need to show reminder again."); - return true; - } -} - -void ReminderDataManager::SetActiveReminder(const sptr &reminder) -{ - if (reminder == nullptr) { - // activeReminder_ should not be set with null as it point to actual object. - activeReminderId_ = -1; - } else { - activeReminderId_ = reminder->GetReminderId(); - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_ = reminder; - } - ANSR_LOGD("Set activeReminderId=%{public}d", activeReminderId_.load()); -} - -void ReminderDataManager::SetAlertingReminder(const sptr &reminder) -{ - if (reminder == nullptr) { - // alertingReminder_ should not be set with null as it point to actual object. - alertingReminderId_ = -1; - } else { - alertingReminderId_ = reminder->GetReminderId(); - alertingReminder_ = reminder; - } - ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); -} - -void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); - bool isAlerting = false; - sptr playSoundReminder = nullptr; - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - if ((*it)->IsExpired()) { - continue; - } - uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli(); - if (tempTriggerTime < triggerTime) { - ANSR_LOGD("this reminder triggerTime is less than target triggerTime."); - continue; - } - if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { - continue; - } - if (!(*it)->IsNeedNotification()) { - continue; - } - ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); - if ((*it)->CheckExcludeDate()) { - ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); - continue; - } - if (((*it)->GetRingDuration() > 0) && !isAlerting) { - playSoundReminder = (*it); - isAlerting = true; - } else { - ShowReminder((*it), false, false, false, false); - } - } - if (playSoundReminder != nullptr) { - ShowReminder(playSoundReminder, true, false, false, true); - } -} - -bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) -{ - ANSR_LOGD("StartExtensionAbility"); - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - std::shared_ptr wantInfo = calendar->GetRRuleWantAgentInfo(); - if (wantInfo != nullptr && wantInfo->pkgName.size() != 0 && wantInfo->abilityName.size() != 0) { - AAFwk::Want want; - want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); - want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); - int32_t result = IN_PROCESS_CALL( - AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); - if (result != ERR_OK) { - ANSR_LOGE("StartExtensionAbility failed[%{public}d]", result); - return false; - } - } - } - return true; -} - -void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) -{ - auto manager = ReminderDataManager::GetInstance(); - if (manager == nullptr) { - ANSR_LOGW("ReminderDataManager is nullptr."); - return; - } - if (!manager->IsSystemReady()) { - ANSR_LOGW("bundle service or ability service not ready."); - return; - } - if (!reminder->IsSystemApp()) { - ANSR_LOGI("Start extension ability failed, is not system app"); - return; - } - times--; - bool ret = ReminderDataManager::StartExtensionAbility(reminder); - if (!ret && times > 0 && serviceQueue_ != nullptr) { - ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); - ffrt::task_attr taskAttr; - taskAttr.delay(CONNECT_EXTENSION_INTERVAL); - auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; - serviceQueue_->submit(callback, taskAttr); - } -} - -void ReminderDataManager::ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, - const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout) -{ - ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", - static_cast(isNeedToPlaySound), reminder->Dump().c_str()); - int32_t reminderId = reminder->GetReminderId(); - sptr bundleOption = reminder->GetNotificationBundleOption(); - sptr notificationRequest = reminder->GetNotificationRequest(); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); - return; - } - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("ShowReminder fail"); - reminder->OnShow(false, isSysTimeChanged, false); - store_->UpdateOrInsert(reminder, bundleOption); - return; - } - if (!IsAllowedNotify(reminder)) { - ANSR_LOGE("Not allow to notify."); - reminder->OnShow(false, isSysTimeChanged, false); - store_->UpdateOrInsert(reminder, bundleOption); - return; - } - ReportSysEvent(reminder); - bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; - reminder->OnShow(toPlaySound, isSysTimeChanged, true); - AddToShowedReminders(reminder); - UpdateNotification(reminder, false); // this should be called after OnShow - - if (alertingReminderId_ != -1) { - TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); - } - // Set the notification SoundEnabled and VibrationEnabled by soltType - advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - if (errCode != ERR_OK) { - reminder->OnShowFail(); - RemoveFromShowedReminders(reminder); - } else { - if (toPlaySound) { - PlaySoundAndVibration(reminder); // play sound and vibration - if (needScheduleTimeout) { - StartTimer(reminder, TimerType::ALERTING_TIMER); - } else { - TerminateAlerting(1, reminder); - } - } - HandleSameNotificationIdShowing(reminder); - } - store_->UpdateOrInsert(reminder, bundleOption); - - if (isNeedToStartNext) { - StartRecentReminder(); - } -} - -void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) -{ - if (isSnooze) { - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); - } else { - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); - } - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); -} - -void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); - return; - } - SnoozeReminderImpl(reminder); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::SNOOZE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::SNOOZE); -} - -void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) -{ - ANSR_LOGI("Snooze the reminder request, %{public}s", reminder->Dump().c_str()); - int32_t reminderId = reminder->GetReminderId(); - if (activeReminderId_ == reminderId) { - ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_.load()); - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_->OnStop(); - } - StopTimerLocked(TimerType::TRIGGER_TIMER); - } - - // 1) Snooze the reminder by manual - if (alertingReminderId_ == reminder->GetReminderId()) { - StopSoundAndVibrationLocked(reminder); - StopTimerLocked(TimerType::ALERTING_TIMER); - } - reminder->OnSnooze(); - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - - // 2) Show the notification dialog in the systemUI - sptr bundleOption = reminder->GetNotificationBundleOption(); - sptr notificationRequest = reminder->GetNotificationRequest(); - if (bundleOption == nullptr) { - ANSR_LOGW("snoozeReminder, invalid bundle option"); - return; - } - ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); - UpdateNotification(reminder, true); - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Ans instance is null"); - return; - } - // Set the notification SoundEnabled and VibrationEnabled by soltType - advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - StartRecentReminder(); -} - -void ReminderDataManager::StartRecentReminder() -{ - sptr reminder = GetRecentReminderLocked(); - if (reminder == nullptr) { - ANSR_LOGI("No reminder need to start"); - SetActiveReminder(reminder); - return; - } - if (activeReminderId_ == reminder->GetReminderId()) { - ANSR_LOGI("Recent reminder has already run, no need to start again."); - return; - } - if (activeReminderId_ != -1) { - { - std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); - activeReminder_->OnStop(); - store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption()); - } - StopTimerLocked(TimerType::TRIGGER_TIMER); - } - ANSR_LOGI("Start recent reminder"); - StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); - reminder->OnStart(); - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -} - -void ReminderDataManager::StopAlertingReminder(const sptr &reminder) -{ - if (reminder == nullptr) { - ANSR_LOGE("StopAlertingReminder illegal."); - return; - } - if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { - ANSR_LOGE("StopAlertingReminder is illegal."); - return; - } - StopSoundAndVibration(alertingReminder_); - StopTimer(TimerType::ALERTING_TIMER); -} - -std::string ReminderDataManager::Dump() const -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - std::map>> bundleNameMap; - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - if ((*it)->IsExpired()) { - continue; - } - std::string bundleName = (*it)->GetBundleName(); - auto val = bundleNameMap.find(bundleName); - if (val == bundleNameMap.end()) { - std::vector> reminders; - reminders.push_back(*it); - bundleNameMap.insert(std::pair>>(bundleName, reminders)); - } else { - val->second.push_back(*it); - } - } - - std::string allReminders = ""; - for (auto it = bundleNameMap.begin(); it != bundleNameMap.end(); ++it) { - std::string bundleName = it->first; - std::vector> reminders = it->second; - sort(reminders.begin(), reminders.end(), cmp); - std::string oneBundleReminders = bundleName + ":{\n"; - oneBundleReminders += " totalCount:" + std::to_string(reminders.size()) + ",\n"; - oneBundleReminders += " reminders:{\n"; - for (auto vit = reminders.begin(); vit != reminders.end(); ++vit) { - oneBundleReminders += " [\n"; - std::string reminderInfo = (*vit)->Dump(); - oneBundleReminders += " " + reminderInfo + "\n"; - oneBundleReminders += " ],\n"; - } - oneBundleReminders += " },\n"; - oneBundleReminders += "},\n"; - allReminders += oneBundleReminders; - } - - return "ReminderDataManager{ totalCount:" + std::to_string(totalCount_) + ",\n" + - "timerId:" + std::to_string(timerId_) + ",\n" + - "activeReminderId:" + std::to_string(activeReminderId_) + ",\n" + - allReminders + "}"; -} - -sptr ReminderDataManager::GetRecentReminderLocked() -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - sort(reminderVector_.begin(), reminderVector_.end(), cmp); - for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { - if (!(*it)->IsExpired()) { - time_t now; - (void)time(&now); // unit is seconds. - if (now < 0 - || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) { - it++; - continue; - } - ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); - return *it; - } - if (!(*it)->CanRemove()) { - ANSR_LOGD("Reminder has been expired: %{public}s", (*it)->Dump().c_str()); - it++; - continue; - } - int32_t reminderId = (*it)->GetReminderId(); - ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); - it = reminderVector_.erase(it); - totalCount_--; - store_->Delete(reminderId); - } - return nullptr; -} - -void ReminderDataManager::HandleImmediatelyShow( - std::vector> &showImmediately, bool isSysTimeChanged) -{ - bool isAlerting = false; - for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { - if ((*it)->IsShowing()) { - continue; - } - if (((*it)->GetRingDuration() > 0) && !isAlerting) { - std::lock_guard lock(ReminderDataManager::MUTEX); - ShowReminder((*it), true, false, isSysTimeChanged, true); - isAlerting = true; - } else { - std::lock_guard lock(ReminderDataManager::MUTEX); - ShowReminder((*it), false, false, isSysTimeChanged, false); - } - } -} - -void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) -{ - for (auto& reminder : extensionReminders) { - ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); - } -} - -sptr ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr &reminder) -{ - reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE); - uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli(); - bool needShowImmediately = false; - if (type == TIME_ZONE_CHANGE) { - needShowImmediately = reminder->OnTimeZoneChange(); - } - if (type == DATE_TIME_CHANGE) { - needShowImmediately = reminder->OnDateTimeChange(); - } - if (!needShowImmediately) { - uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli(); - if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { - CloseReminder(reminder, true); - } - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - return nullptr; - } - store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - return reminder; -} - -void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) -{ - // not add ReminderDataManager::MUTEX, as ShowActiveReminderExtendLocked has locked - int32_t notificationId = reminder->GetNotificationId(); - ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); - int32_t curReminderId = reminder->GetReminderId(); - sptr option1 = reminder->GetNotificationBundleOption(); - if (option1 == nullptr) { - ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); - return; - } - - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - int32_t tmpId = (*it)->GetReminderId(); - if (tmpId == curReminderId) { - continue; - } - if (!(*it)->IsShowing()) { - continue; - } - sptr bundleOption = (*it)->GetNotificationBundleOption(); - if (bundleOption == nullptr) { - ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); - continue; - } - if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) { - if ((*it)->IsAlerting()) { - StopAlertingReminder(*it); - } - (*it)->OnSameNotificationIdCovered(); - RemoveFromShowedReminders(*it); - store_->UpdateOrInsert((*it), bundleOption); - } - } -} - -void ReminderDataManager::Init(bool isFromBootComplete) -{ - ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete); - if (isFromBootComplete) { - std::vector> immediatelyReminders; - std::vector> extensionReminders; - CheckReminderTime(immediatelyReminders, extensionReminders); - HandleImmediatelyShow(immediatelyReminders, false); - HandleExtensionReminder(extensionReminders); - StartRecentReminder(); - } - if (IsReminderAgentReady()) { - return; - } - // Register config observer for language change - if (!RegisterConfigurationObserver()) { - ANSR_LOGW("Register configuration observer failed."); - return; - } - if (queue_ == nullptr) { - queue_ = std::make_shared("ReminderDataManager"); - if (queue_ == nullptr) { - ANSR_LOGE("create ffrt queue failed!"); - return; - } - } - if (store_ == nullptr) { - store_ = std::make_shared(); - } - if (store_->Init() != ReminderStore::STATE_OK) { - ANSR_LOGW("Db init fail."); - return; - } - InitServiceHandler(); - LoadReminderFromDb(); - InitUserId(); - isReminderAgentReady_ = true; - ANSR_LOGD("ReminderAgent is ready."); -} - -void ReminderDataManager::InitServiceHandler() -{ - ANSR_LOGD("InitServiceHandler started"); - if (serviceQueue_ != nullptr) { - ANSR_LOGD("InitServiceHandler already init."); - return; - } - serviceQueue_ = std::make_shared("ReminderService"); - - ANSR_LOGD("InitServiceHandler suceeded."); -} - -void ReminderDataManager::CheckReminderTime(std::vector>& immediatelyReminders, - std::vector>& extensionReminders) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto reminder : reminderVector_) { - if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR) { - continue; - } - - if (reminder->IsPullUpService()) { - extensionReminders.push_back(reminder); - } - - if (reminder->OnDateTimeChange()) { - immediatelyReminders.push_back(reminder); - } - } -} - -void ReminderDataManager::InitUserId() -{ - currentUserId_ = MAIN_USER_ID; - OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); -} - -bool ReminderDataManager::RegisterConfigurationObserver() -{ - if (configChangeObserver_ != nullptr) { - return true; - } - - auto appMgrClient = std::make_shared(); - configChangeObserver_ = sptr( - new (std::nothrow) ReminderConfigChangeObserver()); - if (appMgrClient->RegisterConfigurationObserver(configChangeObserver_) != ERR_OK) { - ANSR_LOGE("Register configuration observer failed."); - return false; - } - return true; -} - -void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector> &reminders) const -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto reminderSptr : reminderVector_) { - if (!(reminderSptr->ShouldShowImmediately())) { - break; - } - if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) { - reminderSptr->SetSnoozeTimesDynamic(0); - } - reminders.push_back(reminderSptr); - } -} - -bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) const -{ - if (reminder == nullptr) { - return false; - } - auto option = reminder->GetNotificationBundleOption(); - if (option == nullptr) { - ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); - return false; - } - bool isAllowed = false; - ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); - if (errCode != ERR_OK) { - ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); - return false; - } - return isAllowed; -} - -bool ReminderDataManager::IsReminderAgentReady() const -{ - return isReminderAgentReady_; -} - -bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, - const sptr &other) const -{ - std::string bundleName = reminder->GetCreatorBundleName(); - int32_t uid = reminder->GetCreatorUid(); - if (uid == -1) { - uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); - } - return bundleName == other->GetBundleName() && uid == other->GetUid(); -} - -bool ReminderDataManager::IsBelongToSameApp(const sptr &bundleOption, - const sptr &other) const -{ - int32_t uidSrc = bundleOption->GetUid(); - int32_t uidTar = other->GetUid(); - bool result = uidSrc == uidTar; - int32_t userIdSrc = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); - int32_t userIdTar = -1; - OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); - result = result && (userIdSrc == userIdTar); - result = result && (bundleOption->GetBundleName() == other->GetBundleName()); - return result; -} - -void ReminderDataManager::LoadReminderFromDb() -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - std::vector> existReminders = store_->GetAllValidReminders(); - reminderVector_ = existReminders; - ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - if (bundleOption == nullptr) { - ANS_LOGE("Failed to create bundle option due to low memory."); - return; - } - bundleOption->SetBundleName((*it)->GetBundleName()); - bundleOption->SetUid((*it)->GetUid()); - (*it)->SetNotificationBundleOption(bundleOption); - } - totalCount_ = static_cast(reminderVector_.size()); - ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; -} - -void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); - PlaySoundAndVibration(reminder); -} - -std::string ReminderDataManager::GetCustomRingUri(const sptr &reminder) -{ - if (reminder == nullptr) { - return ""; - } - return reminder->GetCustomRingUri(); -} - -std::string ReminderDataManager::GetFullPath(const std::string& oriPath) -{ - char buf[MAX_PATH_LEN] = {0}; - char* path = GetOneCfgFile(oriPath.c_str(), buf, MAX_PATH_LEN); - if (path == nullptr || *path == '\0') { - ANSR_LOGE("GetOneCfgFile failed"); - return ""; - } - std::string filePath = path; - return filePath; -} - -void ReminderDataManager::PlaySoundAndVibration(const sptr &reminder) -{ - if (reminder == nullptr) { - ANSR_LOGE("Play sound and vibration failed as reminder is null."); - return; - } - if (alertingReminderId_ != -1) { - TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); - } - ANSR_LOGD("Play sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); -#ifdef PLAYER_FRAMEWORK_ENABLE - if (soundPlayer_ == nullptr) { - soundPlayer_ = Media::PlayerFactory::CreatePlayer(); - if (soundPlayer_ == nullptr) { - ANSR_LOGE("Fail to creat player."); - return; - } - } - std::string customRingUri = reminder->GetCustomRingUri(); - if (customRingUri.empty()) { - // use default ring - std::string defaultPath; - if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { - defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; - } else { - defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); - } - Uri defaultSound(defaultPath); - soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); - ANSR_LOGI("Play default sound."); - } else { - Global::Resource::ResourceManager::RawFileDescriptor desc; - if (GetCustomRingFileDesc(reminder, desc)) { - soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); - } - ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); - } - soundPlayer_->SetLooping(true); - soundPlayer_->PrepareAsync(); - soundPlayer_->Play(); -#endif - SetAlertingReminder(reminder); -} - -std::string ReminderDataManager::GetSoundUri(const sptr &reminder) -{ - Uri uri = DEFAULT_NOTIFICATION_SOUND; - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Ans instance is null."); - return uri.GetSchemeSpecificPart(); - } - sptr bundle = reminder->GetNotificationBundleOption(); - std::vector> slots; - ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); - if (errCode != ERR_OK) { - ANSR_LOGW("Get sound uri fail, use default sound instead."); - return uri.GetSchemeSpecificPart(); - } - for (auto it = slots.begin(); it != slots.end(); ++it) { - if ((*it)->GetType() == reminder->GetSlotType()) { - uri = (*it)->GetSound(); - break; - } - } - return uri.GetSchemeSpecificPart(); -} - -void ReminderDataManager::StopSoundAndVibrationLocked(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); - StopSoundAndVibration(reminder); -} - -void ReminderDataManager::StopSoundAndVibration(const sptr &reminder) -{ - if (reminder == nullptr) { - ANSR_LOGE("Stop sound and vibration failed as reminder is null."); - return; - } - if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { - ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \ - "%{public}d, tarReminderId=%{public}d", alertingReminderId_.load(), reminder->GetReminderId()); - return; - } - ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); -#ifdef PLAYER_FRAMEWORK_ENABLE - if (soundPlayer_ == nullptr) { - ANSR_LOGW("Sound player is null"); - } else { - std::string customRingUri = reminder->GetCustomRingUri(); - if (customRingUri.empty()) { - ANSR_LOGI("Stop default sound."); - } else { - CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); - } - soundPlayer_->Stop(); - soundPlayer_->Release(); - soundPlayer_ = nullptr; - } -#endif - sptr nullReminder = nullptr; - SetAlertingReminder(nullReminder); -} - -void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) -{ - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { - if ((*it)->GetReminderId() == reminder->GetReminderId()) { - ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); - showedReminderVector_.erase(it); - break; - } - } -} - -void ReminderDataManager::RefreshRemindersLocked(uint8_t type, - std::vector>& immediatelyReminders, std::vector>& extensionReminders) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - if ((*it)->IsPullUpService()) { - extensionReminders.push_back((*it)); - } - - sptr reminder = HandleRefreshReminder(type, (*it)); - if (reminder != nullptr) { - immediatelyReminders.push_back(reminder); - } - } -} - -void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) -{ - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { - if (reminderId == (*it)->GetReminderId()) { - ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); - it = reminderVector_.erase(it); - totalCount_--; - store_->Delete(reminderId); - break; - } else { - ++it; - } - } -} - -void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) -{ - std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); - StartTimer(reminderRequest, type); -} - -void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) -{ - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - if (timer == nullptr) { - ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); - return; - } - time_t now; - (void)time(&now); // unit is seconds. - if (now < 0) { - ANSR_LOGE("Get now time error"); - return; - } - uint64_t triggerTime = 0; - switch (type) { - case TimerType::TRIGGER_TIMER: { - if (timerId_ != 0) { - ANSR_LOGE("Trigger timer has already started."); - break; - } - triggerTime = HandleTriggerTimeInner(reminderRequest, type, timer); - break; - } - case TimerType::ALERTING_TIMER: { - if (timerIdAlerting_ != 0) { - ANSR_LOGE("Alerting time out timer has already started."); - break; - } - triggerTime = HandleAlertingTimeInner(reminderRequest, type, timer, now); - break; - } - default: { - ANSR_LOGE("TimerType not support"); - break; - } - } - if (triggerTime == 0) { - ANSR_LOGW("Start timer fail"); - } else { - ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")", - ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime); - } -} - -uint64_t ReminderDataManager::HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, - const sptr &timer) -{ - uint64_t triggerTime = 0; - SetActiveReminder(reminderRequest); - timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); - triggerTime = reminderRequest->GetTriggerTimeInMilli(); - timer->StartTimer(timerId_, triggerTime); - ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_); - return triggerTime; -} - -uint64_t ReminderDataManager::HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, - const sptr &timer, time_t now) -{ - uint64_t triggerTime = 0; - triggerTime = ReminderRequest::GetDurationSinceEpochInMilli(now) - + static_cast(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS); - timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); - timer->StartTimer(timerIdAlerting_, triggerTime); - ANSR_LOGD("Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_.load()); - return triggerTime; -} - -void ReminderDataManager::StopTimerLocked(TimerType type) -{ - std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); - StopTimer(type); -} - -void ReminderDataManager::StopTimer(TimerType type) -{ - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - if (timer == nullptr) { - ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null."); - return; - } - uint64_t timerId = 0; - switch (type) { - case TimerType::TRIGGER_TIMER: { - timerId = timerId_; - ANSR_LOGD("Stop timing (next triggerTime)"); - break; - } - case TimerType::ALERTING_TIMER: { - timerId = timerIdAlerting_; - ANSR_LOGD("Stop timing (alerting time out)"); - break; - } - default: { - ANSR_LOGE("TimerType not support"); - break; - } - } - if (timerId == 0) { - ANSR_LOGD("Timer is not running"); - return; - } - ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId); - timer->StopTimer(timerId); - ResetStates(type); -} - -void ReminderDataManager::ResetStates(TimerType type) -{ - uint64_t timerId = 0; - switch (type) { - case TimerType::TRIGGER_TIMER: { - ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); - timerId = timerId_; - timerId_ = 0; - activeReminderId_ = -1; - break; - } - case TimerType::ALERTING_TIMER: { - ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); - timerId = timerIdAlerting_; - timerIdAlerting_ = 0; - alertingReminderId_ = -1; - break; - } - default: { - ANSR_LOGE("TimerType not support"); - break; - } - } - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - if (timer == nullptr) { - ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); - return; - } - if (timerId != 0) { - timer->DestroyTimer(timerId); - } -} - -void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); - return; - } - if (!reminder->IsSystemApp()) { - ANSR_LOGI("Custom button click, is not system app"); - return; - } - CloseReminder(reminder, false); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); - std::string buttonPkgName = want.GetStringParam("PkgName"); - std::string buttonAbilityName = want.GetStringParam("AbilityName"); - - AAFwk::Want abilityWant; - abilityWant.SetElementName(buttonPkgName, buttonAbilityName); - abilityWant.SetUri(reminder->GetCustomButtonUri()); - auto client = AppExecFwk::AbilityManagerClient::GetInstance(); - if (client == nullptr) { - return; - } - uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); - int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); - if (result != 0) { - ANSR_LOGE("Start ability failed, result = %{public}d", result); - return; - } -} - -void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) -{ - int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - ANSR_LOGI("click reminder[%{public}d] start", reminderId); - sptr reminder = FindReminderRequestLocked(reminderId); - if (reminder == nullptr) { - ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); - return; - } - CloseReminder(reminder, true); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); - StartRecentReminder(); - - auto wantInfo = reminder->GetWantAgentInfo(); - if (wantInfo == nullptr || (wantInfo->pkgName.empty() && wantInfo->abilityName.empty())) { - ANSR_LOGW("want info is nullptr or no pkg name"); - return; - } - AAFwk::Want abilityWant; - AppExecFwk::ElementName element("", wantInfo->pkgName, wantInfo->abilityName); - abilityWant.SetElement(element); - abilityWant.SetUri(wantInfo->uri); - abilityWant.SetParams(wantInfo->parameters); - int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); - abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); - - auto client = AppExecFwk::AbilityManagerClient::GetInstance(); - if (client == nullptr) { - ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); - return; - } - uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); - int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); - if (result != 0) { - ANSR_LOGE("Start ability failed, result = %{public}d", result); - } -} - -std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, - const int32_t uid) -{ - AppExecFwk::BundleInfo bundleInfo; - if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, - AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { - ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); - return nullptr; - } - // obtains the resource manager - std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); - if (!resourceManager) { - ANSR_LOGE("CreateResourceManager fail."); - return nullptr; - } - // obtains the resource path. - for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { - std::string moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; - if (moduleResPath.empty()) { - continue; - } - if (!resourceManager->AddResource(moduleResPath.c_str())) { - ANSR_LOGW("AddResource fail."); - } - } - // obtains the current system language. - std::unique_ptr resConfig(Global::Resource::CreateResConfig()); - UErrorCode status = U_ZERO_ERROR; - icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); - resConfig->SetLocaleInfo(locale); - resourceManager->UpdateResConfig(*resConfig); - return resourceManager; -} - -void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, - const std::vector>& reminders) -{ - // obtains the bundle info by bundle name - if (reminders.empty()) { - return; - } - - std::string bundleName = reminders[0]->GetBundleName(); - // obtains the resource manager - auto resourceMgr = GetResourceMgr(bundleName, uid); - if (resourceMgr == nullptr) { - ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", - uid, bundleName.c_str()); - return; - } - // update action button title - for (auto reminder : reminders) { - std::lock_guard lock(ReminderDataManager::MUTEX); - reminder->OnLanguageChange(resourceMgr); - } -} - -void ReminderDataManager::OnLanguageChanged() -{ - ANSR_LOGI("System language config changed start."); - std::unordered_map>> reminders; - { - std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - reminders[(*it)->GetUid()].push_back((*it)); - } - } - for (auto& each : reminders) { - UpdateReminderLanguageLocked(each.first, each.second); - } - std::vector> showedReminder; - { - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - showedReminder = showedReminderVector_; - } - for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { - std::lock_guard lock(ReminderDataManager::MUTEX); - ShowReminder((*it), false, false, false, false); - } - ANSR_LOGI("System language config changed end."); -} - -void ReminderDataManager::OnRemoveAppMgr() -{ - std::lock_guard lock(appMgrMutex_); - appMgrProxy_ = nullptr; -} - -bool ReminderDataManager::ConnectAppMgr() -{ - if (appMgrProxy_ != nullptr) { - return true; - } - - sptr systemAbilityManager = - SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (systemAbilityManager == nullptr) { - ANSR_LOGE("get SystemAbilityManager failed"); - return false; - } - - sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); - if (remoteObject == nullptr) { - ANSR_LOGE("get app manager service failed"); - return false; - } - - appMgrProxy_ = iface_cast(remoteObject); - if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { - ANSR_LOGE("get app mgr proxy failed!"); - return false; - } - return true; -} - -void ReminderDataManager::CheckNeedNotifyStatus(const sptr &reminder, - const ReminderRequest::ActionButtonType buttonType) -{ - const std::string bundleName = reminder->GetBundleName(); - if (bundleName.empty()) { - return; - } - bool isRunning = false; - { - std::lock_guard lock(appMgrMutex_); - if (!ConnectAppMgr()) { - return; - } - isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); - } - if (!isRunning) { - return; - } - - EventFwk::Want want; - // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string - want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); - EventFwk::CommonEventData eventData(want); - - std::string data; - data.append(std::to_string(static_cast(buttonType))).append(","); - data.append(std::to_string(reminder->GetReminderId())); - eventData.SetData(data); - - EventFwk::CommonEventPublishInfo info; - info.SetBundleName(bundleName); - if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { - ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); - } -} -} -} +// /* +// * Copyright (c) 2021-2023 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 "reminder_data_manager.h" + +// #include "ability_manager_client.h" +// #include "access_token_helper.h" +// #include "ans_log_wrapper.h" +// #include "ans_const_define.h" +// #include "common_event_support.h" +// #include "common_event_manager.h" +// #include "reminder_request_calendar.h" +// #include "in_process_call_wrapper.h" +// #ifdef DEVICE_STANDBY_ENABLE +// #include "standby_service_client.h" +// #include "allow_type.h" +// #endif +// #include "ipc_skeleton.h" +// #include "notification_slot.h" +// #include "os_account_manager.h" +// #include "os_account_manager_helper.h" +// #include "reminder_event_manager.h" +// #include "time_service_client.h" +// #include "singleton.h" +// #include "locale_config.h" +// #include "bundle_manager_helper.h" +// #include "datashare_predicates_object.h" +// #include "datashare_value_object.h" +// #include "datashare_helper.h" +// #include "data_share_permission.h" +// #include "datashare_errno.h" +// #include "datashare_template.h" +// #include "system_ability_definition.h" +// #include "app_mgr_constants.h" +// #include "iservice_registry.h" +// #include "config_policy_utils.h" +// #include "hitrace_meter_adapter.h" +// #ifdef HAS_HISYSEVENT_PART +// #include "hisysevent.h" +// #endif + +// namespace OHOS { +// namespace Notification { +// namespace { +// const std::string ALL_PACKAGES = "allPackages"; +// const int32_t MAIN_USER_ID = 100; +// #ifdef DEVICE_STANDBY_ENABLE +// const int REASON_APP_API = 1; +// #endif +// const int INDEX_KEY = 0; +// const int INDEX_TYPE = 1; +// const int INDEX_VALUE = 2; +// } + +// /** +// * Default reminder sound. +// */ +// const std::string DEFAULT_REMINDER_SOUND_1 = "/system/etc/capture.ogg"; +// const std::string DEFAULT_REMINDER_SOUND_2 = "resource/media/audio/alarms/Aegean_Sea.ogg"; + +// std::shared_ptr ReminderDataManager::REMINDER_DATA_MANAGER = nullptr; +// std::mutex ReminderDataManager::MUTEX; +// std::mutex ReminderDataManager::SHOW_MUTEX; +// std::mutex ReminderDataManager::ALERT_MUTEX; +// std::mutex ReminderDataManager::TIMER_MUTEX; +// std::mutex ReminderDataManager::ACTIVE_MUTEX; +// constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100; +// constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 3; +// std::shared_ptr ReminderDataManager::serviceQueue_ = nullptr; +// ReminderDataManager::~ReminderDataManager() = default; + +// ErrCode ReminderDataManager::PublishReminder(const sptr &reminder, +// const sptr &bundleOption) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID(); +// if (callerTokenId == 0) { +// ANSR_LOGE("pushlish failed, callerTokenId is 0"); +// return ERR_REMINDER_CALLER_TOKEN_INVALID; +// } + +// if (!IsActionButtonDataShareValid(reminder, callerTokenId)) { +// return ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED; +// } + +// if (CheckReminderLimitExceededLocked(bundleOption, reminder)) { +// return ERR_REMINDER_NUMBER_OVERLOAD; +// } +// UpdateAndSaveReminderLocked(reminder, bundleOption); +// queue_->submit([this, reminder]() { +// StartRecentReminder(); +// }); +// return ERR_OK; +// } + +// ErrCode ReminderDataManager::CancelReminder( +// const int32_t &reminderId, const sptr &bundleOption) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGI("cancel reminder id: %{public}d", reminderId); +// sptr reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName()); +// if (reminder == nullptr) { +// ANSR_LOGW("Cancel reminder, not find the reminder"); +// return ERR_REMINDER_NOT_EXIST; +// } +// if (!CheckIsSameApp(reminder, bundleOption)) { +// ANSR_LOGW("Not find the reminder due to not match"); +// return ERR_REMINDER_NOT_EXIST; +// } +// if (activeReminderId_ == reminderId) { +// ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId); +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_->OnStop(); +// } +// StopTimerLocked(TimerType::TRIGGER_TIMER); +// } +// if (alertingReminderId_ == reminderId) { +// StopSoundAndVibrationLocked(reminder); +// StopTimerLocked(TimerType::ALERTING_TIMER); +// } +// CancelNotification(reminder); +// RemoveReminderLocked(reminderId); +// StartRecentReminder(); +// return ERR_OK; +// } + +// ErrCode ReminderDataManager::CancelAllReminders(const std::string& packageName, const int32_t userId, +// const int32_t uid) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// ANSR_LOGD("CancelAllReminders, userId=%{private}d, pkgName=%{public}s", userId, packageName.c_str()); +// CancelRemindersImplLocked(packageName, userId, uid); +// return ERR_OK; +// } + +// sptr ReminderDataManager::CheckExcludeDateParam(const int32_t reminderId, +// const sptr &bundleOption) +// { +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGW("Check reminder failed, not find the reminder"); +// return nullptr; +// } +// if (!CheckIsSameApp(reminder, bundleOption)) { +// ANSR_LOGW("Check reminder failed, due to not match"); +// return nullptr; +// } +// if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR +// || !reminder->IsRepeat()) { +// ANSR_LOGW("Check reminder failed, due to type not match or not repeat"); +// return nullptr; +// } +// return reminder; +// } + +// ErrCode ReminderDataManager::AddExcludeDate(const int32_t reminderId, const uint64_t date, +// const sptr &bundleOption) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); +// if (reminder == nullptr) { +// return ERR_REMINDER_NOT_EXIST; +// } +// { +// std::lock_guard locker(ReminderDataManager::MUTEX); +// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); +// calendar->AddExcludeDate(date); +// store_->UpdateOrInsert(reminder, bundleOption); +// } +// return ERR_OK; +// } + +// ErrCode ReminderDataManager::DelExcludeDates(const int32_t reminderId, +// const sptr &bundleOption) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); +// if (reminder == nullptr) { +// return ERR_REMINDER_NOT_EXIST; +// } +// { +// std::lock_guard locker(ReminderDataManager::MUTEX); +// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); +// calendar->DelExcludeDates(); +// store_->UpdateOrInsert(reminder, bundleOption); +// } +// return ERR_OK; +// } + +// ErrCode ReminderDataManager::GetExcludeDates(const int32_t reminderId, +// const sptr &bundleOption, std::vector& dates) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); +// if (reminder == nullptr) { +// return ERR_REMINDER_NOT_EXIST; +// } +// { +// std::lock_guard locker(ReminderDataManager::MUTEX); +// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); +// dates = calendar->GetExcludeDates(); +// } +// return ERR_OK; +// } + +// void ReminderDataManager::GetValidReminders( +// const sptr &bundleOption, std::vector> &reminders) +// { +// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto& eachReminder : reminderVector_) { +// if (eachReminder->IsExpired()) { +// continue; +// } + +// if (CheckIsSameApp(eachReminder, bundleOption)) { +// reminders.push_back(eachReminder); +// } +// } +// } + +// void ReminderDataManager::CancelAllReminders(const int32_t userId) +// { +// ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); +// CancelRemindersImplLocked(ALL_PACKAGES, userId, -1); +// } + +// void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, +// const int32_t uid) +// { +// MUTEX.lock(); +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// if (activeReminderId_ != -1 && IsMatched(activeReminder_, packageName, userId, uid)) { +// activeReminder_->OnStop(); +// StopTimer(TimerType::TRIGGER_TIMER); +// ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_.load()); +// } +// } +// for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { +// if (IsMatched(*vit, packageName, userId, uid)) { +// if ((*vit)->IsAlerting()) { +// StopAlertingReminder(*vit); +// } +// CancelNotification(*vit); +// RemoveFromShowedReminders(*vit); +// vit = reminderVector_.erase(vit); +// totalCount_--; +// continue; +// } +// ++vit; +// } +// if (packageName == ALL_PACKAGES) { +// store_->DeleteUser(userId); +// } else { +// store_->Delete(packageName, userId, uid); +// } +// MUTEX.unlock(); +// StartRecentReminder(); +// } + +// bool ReminderDataManager::IsMatchedForGroupIdAndPkgName(const sptr &reminder, +// const std::string &packageName, const std::string &groupId) const +// { +// std::string packageNameTemp = reminder->GetBundleName(); +// if (packageNameTemp.empty()) { +// ANSR_LOGW("reminder package name is null"); +// return false; +// } +// if (packageNameTemp == packageName && reminder->GetGroupId() == groupId) { +// return true; +// } +// return false; +// } + +// bool ReminderDataManager::IsMatched(const sptr &reminder, +// const std::string &packageName, const int32_t userId, const int32_t uid) const +// { +// if (reminder->GetUserId() != userId) { +// return false; +// } +// if (packageName == ALL_PACKAGES) { +// return true; +// } +// if (reminder->GetBundleName() != packageName) { +// return false; +// } +// if (uid != -1 && reminder->GetUid() == uid) { +// return true; +// } +// return false; +// } + +// void ReminderDataManager::CancelNotification(const sptr &reminder) const +// { +// if (!(reminder->IsShowing())) { +// ANSR_LOGD("No need to cancel notification"); +// return; +// } +// sptr notification = reminder->GetNotificationRequest(); +// if (notification == nullptr) { +// ANSR_LOGW("Cancel notification fail"); +// return; +// } +// ANSR_LOGD("Cancel notification"); +// if (advancedNotificationService_ == nullptr) { +// ANSR_LOGE("Cancel notification fail"); +// return; +// } +// sptr bundleOption = reminder->GetNotificationBundleOption(); +// advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), +// ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); +// } + +// bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption, +// const sptr &reminder) const +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { +// ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ +// and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); +// return true; +// } +// int32_t count = 0; +// for (const auto& eachReminder : reminderVector_) { +// if (eachReminder->IsExpired()) { +// continue; +// } +// if (CheckIsSameApp(eachReminder, bundleOption)) { +// count++; +// } +// } +// auto maxReminderNum = reminder->IsSystemApp() ? MAX_NUM_REMINDER_LIMIT_SYS_APP : MAX_NUM_REMINDER_LIMIT_APP; +// if (count >= maxReminderNum) { +// ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ +// reminder can not be published", maxReminderNum); +// return true; +// } +// return false; +// } + +// void ReminderDataManager::AddToShowedReminders(const sptr &reminder) +// { +// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); +// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { +// if (reminder->GetReminderId() == (*it)->GetReminderId()) { +// ANSR_LOGD("Showed reminder is already exist"); +// return; +// } +// } +// showedReminderVector_.push_back(reminder); +// } + +// void ReminderDataManager::OnUserRemove(const int32_t& userId) +// { +// if (!IsReminderAgentReady()) { +// ANSR_LOGW("Give up to remove user id: %{private}d for reminderAgent is not ready", userId); +// return; +// } +// CancelAllReminders(userId); +// } + +// void ReminderDataManager::OnUserSwitch(const int32_t& userId) +// { +// ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); +// currentUserId_ = userId; +// std::lock_guard lock(ReminderDataManager::MUTEX); +// if ((alertingReminderId_ != -1) && IsReminderAgentReady()) { +// TerminateAlerting(alertingReminder_, "OnUserSwitch"); +// } +// } + +// void ReminderDataManager::OnProcessDiedLocked(const sptr &bundleOption) +// { +// std::string bundleName = bundleOption->GetBundleName(); +// int32_t uid = bundleOption->GetUid(); +// ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); +// std::lock_guard locker(ReminderDataManager::MUTEX); +// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); +// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { +// if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) { +// continue; +// } +// if ((*it)->IsAlerting()) { +// TerminateAlerting((*it), "onProcessDied"); +// } else { +// CancelNotification(*it); +// (*it)->OnClose(false); +// showedReminderVector_.erase(it); +// --it; +// } +// store_->UpdateOrInsert((*it), bundleOption); +// } +// } + +// void ReminderDataManager::InitTimerInfo(std::shared_ptr &sharedTimerInfo, +// const sptr &reminderRequest, TimerType reminderType) const +// { +// uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); +// uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); +// sharedTimerInfo->SetRepeat(false); +// sharedTimerInfo->SetInterval(0); + +// sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); +// sharedTimerInfo->SetUid(reminderRequest->GetUid()); + +// int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); +// sharedTimerInfo->SetType(timerType); +// } + +// std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type, +// const sptr &reminderRequest) const +// { +// auto sharedTimerInfo = std::make_shared(); +// if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { +// ANSR_LOGE("Failed to set timer type."); +// return nullptr; +// } +// InitTimerInfo(sharedTimerInfo, reminderRequest, type); + +// int32_t requestCode = 10; +// std::vector flags; +// flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + +// auto want = std::make_shared(); +// switch (type) { +// case (TimerType::TRIGGER_TIMER): { +// want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); +// sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); +// want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_); +// break; +// } +// case (TimerType::ALERTING_TIMER): { +// if (alertingReminderId_ == -1) { +// ANSR_LOGE("Create alerting time out timer Illegal."); +// return sharedTimerInfo; +// } +// want->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); +// sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); +// want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_); +// break; +// } +// default: +// ANSR_LOGE("TimerType not support"); +// break; +// } +// std::vector> wants; +// wants.push_back(want); +// AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( +// requestCode, +// AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, +// flags, wants, nullptr); + +// std::string identity = IPCSkeleton::ResetCallingIdentity(); +// std::shared_ptr wantAgent = +// AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); +// IPCSkeleton::SetCallingIdentity(identity); + +// sharedTimerInfo->SetWantAgent(wantAgent); +// return sharedTimerInfo; +// } + +// sptr ReminderDataManager::FindReminderRequestLocked(const int32_t &reminderId) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// if (reminderId == (*it)->GetReminderId()) { +// return *it; +// } +// } +// ANSR_LOGD("Not find the reminder"); +// return nullptr; +// } + +// sptr ReminderDataManager::FindReminderRequestLocked( +// const int32_t &reminderId, const std::string &pkgName) +// { +// sptr reminder = FindReminderRequestLocked(reminderId); +// std::lock_guard lock(ReminderDataManager::MUTEX); +// if (reminder == nullptr) { +// return nullptr; +// } +// if (reminder->GetCreatorBundleName() != pkgName) { +// ANSR_LOGW("Not find the reminder due to package name not match"); +// return nullptr; +// } +// return reminder; +// } + +// bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) +// { +// return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); +// } + +// void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// std::string packageName = reminder->GetBundleName(); +// std::string groupId = reminder->GetGroupId(); +// if (!(packageName.empty() || groupId.empty())) { +// ANSR_LOGD("this reminder can close by groupId"); +// CloseRemindersByGroupId(reminderId, packageName, groupId); +// } +// CloseReminder(reminder, cancelNotification); +// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); +// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); +// StartRecentReminder(); +// } + +// void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, +// const std::string &groupId) +// { +// if (packageName == "") { +// ANSR_LOGD("packageName is empty"); +// return; +// } +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto vit = reminderVector_.begin(); vit != reminderVector_.end(); vit++) { +// sptr reminder = *vit; +// if (reminder == nullptr) { +// ANSR_LOGD("reminder is null"); +// continue; +// } +// int32_t reminderId = reminder->GetReminderId(); +// if (reminderId == oldReminderId) { +// ANSR_LOGD("The old and new reminder are the same"); +// continue; +// } +// if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { +// reminder->SetExpired(true); +// reminder->SetStateToInActive(); +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); +// ResetStates(TimerType::TRIGGER_TIMER); +// ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); +// } +// } +// } + +// void ReminderDataManager::CloseReminder(const sptr &reminder, bool cancelNotification) +// { +// int32_t reminderId = reminder->GetReminderId(); +// if (activeReminderId_ == reminderId) { +// ANSR_LOGD("Stop active reminder due to CloseReminder"); +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_->OnStop(); +// } +// StopTimerLocked(TimerType::TRIGGER_TIMER); +// } +// if (alertingReminderId_ == reminderId) { +// StopSoundAndVibrationLocked(reminder); +// StopTimerLocked(TimerType::ALERTING_TIMER); +// } +// reminder->OnClose(true); +// RemoveFromShowedReminders(reminder); +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); +// if (cancelNotification) { +// CancelNotification(reminder); +// } +// } + +// std::shared_ptr ReminderDataManager::GetInstance() +// { +// return REMINDER_DATA_MANAGER; +// } + +// std::shared_ptr ReminderDataManager::InitInstance( +// const sptr &advancedNotificationService) +// { +// if (REMINDER_DATA_MANAGER == nullptr) { +// REMINDER_DATA_MANAGER = std::make_shared(); +// REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; +// ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); +// } +// return REMINDER_DATA_MANAGER; +// } + +// bool ReminderDataManager::CheckUpdateConditions(const sptr &reminder, +// const ReminderRequest::ActionButtonType &actionButtonType, +// const std::map &actionButtonMap) +// { +// if (!reminder->IsSystemApp()) { +// ANSR_LOGI("UpdateAppDatabase faild, is not SystemApp"); +// return false; +// } +// if (actionButtonType == ReminderRequest::ActionButtonType::INVALID) { +// ANSR_LOGI("actionButtonType is NVALID"); +// return false; +// } +// if (!actionButtonMap.count(actionButtonType)) { +// ANSR_LOGI("actionButtonType does not exist"); +// return false; +// } +// if (actionButtonMap.at(actionButtonType).dataShareUpdate == nullptr) { +// ANSR_LOGI("dataShareUpdate is null"); +// return false; +// } +// if (actionButtonMap.at(actionButtonType).dataShareUpdate->uri == "" || +// actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo == "" || +// actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket == "") { +// ANSR_LOGI("datashare parameter is invalid"); +// return false; +// } +// return true; +// } + +// void ReminderDataManager::UpdateAppDatabase(const sptr &reminder, +// const ReminderRequest::ActionButtonType &actionButtonType) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// auto actionButtonMap = reminder->GetActionButtons(); +// if (!CheckUpdateConditions(reminder, actionButtonType, actionButtonMap)) { +// return; +// } +// // init default dstBundleName +// std::string dstBundleName = reminder->GetBundleName(); +// GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); + +// DataShare::CreateOptions options; +// options.enabled_ = true; +// auto userID = reminder->GetUserId(); +// auto tokenID = IPCSkeleton::GetSelfTokenID(); +// std::string uriStr = actionButtonMap.at(actionButtonType).dataShareUpdate->uri + "?user=" + std::to_string(userID) + +// "&srcToken=" + std::to_string(tokenID) + "&dstBundleName=" + dstBundleName; + +// // create datashareHelper +// std::shared_ptr dataShareHelper = DataShare::DataShareHelper::Creator(uriStr, options); +// if (dataShareHelper == nullptr) { +// ANSR_LOGE("create datashareHelper failed"); +// return; +// } +// // gen uri equalTo valuesBucket +// Uri uri(uriStr); + +// DataShare::DataSharePredicates predicates; +// std::vector equalToVector = ReminderRequest::StringSplit( +// actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo, ReminderRequest::SEP_BUTTON_VALUE_TYPE); +// GenPredicates(predicates, equalToVector); + +// DataShare::DataShareValuesBucket valuesBucket; +// std::vector valuesBucketVector = ReminderRequest::StringSplit( +// actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket, ReminderRequest::SEP_BUTTON_VALUE_TYPE); +// GenValuesBucket(valuesBucket, valuesBucketVector); + +// // update app store +// int retVal = dataShareHelper->Update(uri, predicates, valuesBucket); +// if (retVal > 0) { +// // update success +// ANSR_LOGI("update app store success retval:%{public}d", retVal); +// } +// } + +// void ReminderDataManager::GenPredicates(DataShare::DataSharePredicates &predicates, +// const std::vector &equalToVector) +// { +// // predicates +// for (auto &it : equalToVector) { +// std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); +// if (temp.size() <= INDEX_VALUE) { +// continue; +// } +// if (temp[INDEX_TYPE] == "string") { +// predicates.EqualTo(temp[INDEX_KEY], temp[INDEX_VALUE]); +// } else if (temp[INDEX_TYPE] == "double") { +// predicates.EqualTo(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); +// } else if (temp[INDEX_TYPE] == "bool") { +// bool valueBool = false; +// if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true" || temp[INDEX_VALUE] == "True") { +// valueBool = true; +// } +// predicates.EqualTo(temp[INDEX_KEY], valueBool); +// } +// } +// } + +// void ReminderDataManager::GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket, +// const std::vector &valuesBucketVector) +// { +// // valuesBucket +// for (auto &it : valuesBucketVector) { +// std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); +// if (temp.size() <= INDEX_VALUE) { +// continue; +// } +// if (temp[INDEX_TYPE] == "string") { +// valuesBucket.Put(temp[INDEX_KEY], temp[INDEX_VALUE]); +// } else if (temp[INDEX_TYPE] == "double") { +// valuesBucket.Put(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); +// } else if (temp[INDEX_TYPE] == "bool") { +// bool valueBool = false; +// if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true") { +// valueBool = true; +// } +// valuesBucket.Put(temp[INDEX_KEY], valueBool); +// } else if (temp[INDEX_TYPE] == "null") { +// valuesBucket.Put(temp[INDEX_KEY]); +// } else if (temp[INDEX_TYPE] == "vector") { +// std::vector arr = ReminderRequest::StringSplit(temp[INDEX_VALUE], +// ReminderRequest::SEP_BUTTON_VALUE_BLOB); +// std::vector value; +// for (auto &num : arr) { +// value.emplace_back(static_cast(std::atoi(num.c_str()))); +// } +// valuesBucket.Put(temp[INDEX_KEY], value); +// } +// } +// } + +// void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std::string &uri) const +// { +// size_t left = 0; +// size_t right = 0; +// left = uri.find("/", left); +// right = uri.find("/", left + 1); +// while (right != std::string::npos && right - left <= 1) { +// left = right + 1; +// right = uri.find("/", left); +// } +// if (left == std::string::npos) { +// return; +// } +// if (right != std::string::npos) { +// dstBundleName = uri.substr(left, right - left); +// } else { +// dstBundleName = uri.substr(left); +// } +// } + +// void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) +// { +// if (!IsSystemReady()) { +// ANSR_LOGW("bundle service or ability service not ready."); +// return; +// } +// std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; +// ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); +// if (activeReminderId_ != -1) { +// ANSR_LOGD("Stop active reminder due to date/time or timeZone change"); +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_->OnStop(); +// } +// StopTimerLocked(TimerType::TRIGGER_TIMER); +// } +// std::vector> showImmediately; +// std::vector> extensionReminders; +// RefreshRemindersLocked(type, showImmediately, extensionReminders); +// HandleImmediatelyShow(showImmediately, true); +// HandleExtensionReminder(extensionReminders); +// StartRecentReminder(); +// } + +// void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// TerminateAlerting(reminder, "timeOut"); +// } + +// void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder) +// { +// sleep(waitInSecond); +// TerminateAlerting(reminder, "waitInMillis"); +// } + +// void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) +// { +// if (reminder == nullptr) { +// ANSR_LOGE("TerminateAlerting illegal."); +// return; +// } +// ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", +// reminder->Dump().c_str(), reason.c_str()); +// StopAlertingReminder(reminder); + +// if (!reminder->OnTerminate()) { +// return; +// } +// int32_t reminderId = reminder->GetReminderId(); +// sptr bundleOption = reminder->GetNotificationBundleOption(); +// sptr notificationRequest = reminder->GetNotificationRequest(); +// if (bundleOption == nullptr) { +// ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); +// return; +// } +// ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); +// UpdateNotification(reminder, false); +// if (advancedNotificationService_ == nullptr) { +// ANSR_LOGE("Ans instance is null."); +// return; +// } +// // Set the notification SoundEnabled and VibrationEnabled by soltType +// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); +// advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); +// store_->UpdateOrInsert(reminder, bundleOption); +// } + +// void ReminderDataManager::UpdateAndSaveReminderLocked( +// const sptr &reminder, const sptr &bundleOption) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// reminder->InitReminderId(); +// int32_t userId = -1; +// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); +// reminder->InitUserId(userId); +// reminder->InitUid(bundleOption->GetUid()); +// reminder->InitBundleName(bundleOption->GetBundleName()); + +// if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) { +// ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); +// reminder->SetExpired(true); +// } +// reminder->SetNotificationBundleOption(bundleOption); +// reminderVector_.push_back(reminder); +// totalCount_++; +// store_->UpdateOrInsert(reminder, bundleOption); +// } + +// void ReminderDataManager::SetService(sptr &advancedNotificationService) +// { +// advancedNotificationService_ = advancedNotificationService; +// } + +// bool ReminderDataManager::ShouldAlert(const sptr &reminder) const +// { +// if (reminder == nullptr) { +// return false; +// } +// int32_t reminderId = reminder->GetReminderId(); +// sptr bundleOption = reminder->GetNotificationBundleOption(); +// if (bundleOption == nullptr) { +// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); +// return false; +// } +// int32_t userId = -1; +// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); +// if (currentUserId_ != userId) { +// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ +// "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); +// return false; +// } + +// sptr date; +// ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); +// if (errCode != ERR_OK) { +// ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); +// return true; +// } +// if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { +// return true; +// } +// std::vector> slots; +// errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); +// if (errCode != ERR_OK) { +// ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); +// return false; +// } +// for (auto slot : slots) { +// if (slot->GetType() != reminder->GetSlotType()) { +// continue; +// } +// if (slot->IsEnableBypassDnd()) { +// ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId); +// return true; +// } +// } +// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId); +// return false; +// } + +// void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId); +// if (reminderId == activeReminderId_) { +// ResetStates(TimerType::TRIGGER_TIMER); +// } +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// if (HandleSysTimeChange(reminder)) { +// return; +// } +// ShowActiveReminderExtendLocked(reminder); +// StartRecentReminder(); +// } + +// bool ReminderDataManager::HandleSysTimeChange(const sptr reminder) const +// { +// if (reminder->CanShow()) { +// return false; +// } else { +// ANSR_LOGI("handleSystimeChange, no need to show reminder again."); +// return true; +// } +// } + +// void ReminderDataManager::SetActiveReminder(const sptr &reminder) +// { +// if (reminder == nullptr) { +// // activeReminder_ should not be set with null as it point to actual object. +// activeReminderId_ = -1; +// } else { +// activeReminderId_ = reminder->GetReminderId(); +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_ = reminder; +// } +// ANSR_LOGD("Set activeReminderId=%{public}d", activeReminderId_.load()); +// } + +// void ReminderDataManager::SetAlertingReminder(const sptr &reminder) +// { +// if (reminder == nullptr) { +// // alertingReminder_ should not be set with null as it point to actual object. +// alertingReminderId_ = -1; +// } else { +// alertingReminderId_ = reminder->GetReminderId(); +// alertingReminder_ = reminder; +// } +// ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); +// } + +// void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); +// bool isAlerting = false; +// sptr playSoundReminder = nullptr; +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// if ((*it)->IsExpired()) { +// continue; +// } +// uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli(); +// if (tempTriggerTime < triggerTime) { +// ANSR_LOGD("this reminder triggerTime is less than target triggerTime."); +// continue; +// } +// if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { +// continue; +// } +// if (!(*it)->IsNeedNotification()) { +// continue; +// } +// ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); +// if ((*it)->CheckExcludeDate()) { +// ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); +// continue; +// } +// if (((*it)->GetRingDuration() > 0) && !isAlerting) { +// playSoundReminder = (*it); +// isAlerting = true; +// } else { +// ShowReminder((*it), false, false, false, false); +// } +// } +// if (playSoundReminder != nullptr) { +// ShowReminder(playSoundReminder, true, false, false, true); +// } +// } + +// bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) +// { +// ANSR_LOGD("StartExtensionAbility"); +// if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { +// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); +// std::shared_ptr wantInfo = calendar->GetRRuleWantAgentInfo(); +// if (wantInfo != nullptr && wantInfo->pkgName.size() != 0 && wantInfo->abilityName.size() != 0) { +// AAFwk::Want want; +// want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); +// want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); +// int32_t result = IN_PROCESS_CALL( +// AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); +// if (result != ERR_OK) { +// ANSR_LOGE("StartExtensionAbility failed[%{public}d]", result); +// return false; +// } +// } +// } +// return true; +// } + +// void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) +// { +// auto manager = ReminderDataManager::GetInstance(); +// if (manager == nullptr) { +// ANSR_LOGW("ReminderDataManager is nullptr."); +// return; +// } +// if (!manager->IsSystemReady()) { +// ANSR_LOGW("bundle service or ability service not ready."); +// return; +// } +// if (!reminder->IsSystemApp()) { +// ANSR_LOGI("Start extension ability failed, is not system app"); +// return; +// } +// times--; +// bool ret = ReminderDataManager::StartExtensionAbility(reminder); +// if (!ret && times > 0 && serviceQueue_ != nullptr) { +// ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); +// ffrt::task_attr taskAttr; +// taskAttr.delay(CONNECT_EXTENSION_INTERVAL); +// auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; +// serviceQueue_->submit(callback, taskAttr); +// } +// } + +// void ReminderDataManager::ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, +// const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout) +// { +// ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", +// static_cast(isNeedToPlaySound), reminder->Dump().c_str()); +// int32_t reminderId = reminder->GetReminderId(); +// sptr bundleOption = reminder->GetNotificationBundleOption(); +// sptr notificationRequest = reminder->GetNotificationRequest(); +// if (bundleOption == nullptr) { +// ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); +// return; +// } +// if (advancedNotificationService_ == nullptr) { +// ANSR_LOGE("ShowReminder fail"); +// reminder->OnShow(false, isSysTimeChanged, false); +// store_->UpdateOrInsert(reminder, bundleOption); +// return; +// } +// if (!IsAllowedNotify(reminder)) { +// ANSR_LOGE("Not allow to notify."); +// reminder->OnShow(false, isSysTimeChanged, false); +// store_->UpdateOrInsert(reminder, bundleOption); +// return; +// } +// ReportSysEvent(reminder); +// bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; +// reminder->OnShow(toPlaySound, isSysTimeChanged, true); +// AddToShowedReminders(reminder); +// UpdateNotification(reminder, false); // this should be called after OnShow + +// if (alertingReminderId_ != -1) { +// TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); +// } +// // Set the notification SoundEnabled and VibrationEnabled by soltType +// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); +// ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); +// if (errCode != ERR_OK) { +// reminder->OnShowFail(); +// RemoveFromShowedReminders(reminder); +// } else { +// if (toPlaySound) { +// PlaySoundAndVibration(reminder); // play sound and vibration +// if (needScheduleTimeout) { +// StartTimer(reminder, TimerType::ALERTING_TIMER); +// } else { +// TerminateAlerting(1, reminder); +// } +// } +// HandleSameNotificationIdShowing(reminder); +// } +// store_->UpdateOrInsert(reminder, bundleOption); + +// if (isNeedToStartNext) { +// StartRecentReminder(); +// } +// } + +// void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) +// { +// if (isSnooze) { +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); +// } else { +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); +// } +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); +// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); +// } + +// void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// SnoozeReminderImpl(reminder); +// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::SNOOZE); +// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::SNOOZE); +// } + +// void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) +// { +// ANSR_LOGI("Snooze the reminder request, %{public}s", reminder->Dump().c_str()); +// int32_t reminderId = reminder->GetReminderId(); +// if (activeReminderId_ == reminderId) { +// ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_.load()); +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_->OnStop(); +// } +// StopTimerLocked(TimerType::TRIGGER_TIMER); +// } + +// // 1) Snooze the reminder by manual +// if (alertingReminderId_ == reminder->GetReminderId()) { +// StopSoundAndVibrationLocked(reminder); +// StopTimerLocked(TimerType::ALERTING_TIMER); +// } +// reminder->OnSnooze(); +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); + +// // 2) Show the notification dialog in the systemUI +// sptr bundleOption = reminder->GetNotificationBundleOption(); +// sptr notificationRequest = reminder->GetNotificationRequest(); +// if (bundleOption == nullptr) { +// ANSR_LOGW("snoozeReminder, invalid bundle option"); +// return; +// } +// ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); +// UpdateNotification(reminder, true); +// if (advancedNotificationService_ == nullptr) { +// ANSR_LOGE("Ans instance is null"); +// return; +// } +// // Set the notification SoundEnabled and VibrationEnabled by soltType +// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); +// advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); +// StartRecentReminder(); +// } + +// void ReminderDataManager::StartRecentReminder() +// { +// sptr reminder = GetRecentReminderLocked(); +// if (reminder == nullptr) { +// ANSR_LOGI("No reminder need to start"); +// SetActiveReminder(reminder); +// return; +// } +// if (activeReminderId_ == reminder->GetReminderId()) { +// ANSR_LOGI("Recent reminder has already run, no need to start again."); +// return; +// } +// if (activeReminderId_ != -1) { +// { +// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); +// activeReminder_->OnStop(); +// store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption()); +// } +// StopTimerLocked(TimerType::TRIGGER_TIMER); +// } +// ANSR_LOGI("Start recent reminder"); +// StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); +// reminder->OnStart(); +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); +// } + +// void ReminderDataManager::StopAlertingReminder(const sptr &reminder) +// { +// if (reminder == nullptr) { +// ANSR_LOGE("StopAlertingReminder illegal."); +// return; +// } +// if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { +// ANSR_LOGE("StopAlertingReminder is illegal."); +// return; +// } +// StopSoundAndVibration(alertingReminder_); +// StopTimer(TimerType::ALERTING_TIMER); +// } + +// std::string ReminderDataManager::Dump() const +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// std::map>> bundleNameMap; +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// if ((*it)->IsExpired()) { +// continue; +// } +// std::string bundleName = (*it)->GetBundleName(); +// auto val = bundleNameMap.find(bundleName); +// if (val == bundleNameMap.end()) { +// std::vector> reminders; +// reminders.push_back(*it); +// bundleNameMap.insert(std::pair>>(bundleName, reminders)); +// } else { +// val->second.push_back(*it); +// } +// } + +// std::string allReminders = ""; +// for (auto it = bundleNameMap.begin(); it != bundleNameMap.end(); ++it) { +// std::string bundleName = it->first; +// std::vector> reminders = it->second; +// sort(reminders.begin(), reminders.end(), cmp); +// std::string oneBundleReminders = bundleName + ":{\n"; +// oneBundleReminders += " totalCount:" + std::to_string(reminders.size()) + ",\n"; +// oneBundleReminders += " reminders:{\n"; +// for (auto vit = reminders.begin(); vit != reminders.end(); ++vit) { +// oneBundleReminders += " [\n"; +// std::string reminderInfo = (*vit)->Dump(); +// oneBundleReminders += " " + reminderInfo + "\n"; +// oneBundleReminders += " ],\n"; +// } +// oneBundleReminders += " },\n"; +// oneBundleReminders += "},\n"; +// allReminders += oneBundleReminders; +// } + +// return "ReminderDataManager{ totalCount:" + std::to_string(totalCount_) + ",\n" + +// "timerId:" + std::to_string(timerId_) + ",\n" + +// "activeReminderId:" + std::to_string(activeReminderId_) + ",\n" + +// allReminders + "}"; +// } + +// sptr ReminderDataManager::GetRecentReminderLocked() +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// sort(reminderVector_.begin(), reminderVector_.end(), cmp); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { +// if (!(*it)->IsExpired()) { +// time_t now; +// (void)time(&now); // unit is seconds. +// if (now < 0 +// || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) { +// it++; +// continue; +// } +// ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); +// return *it; +// } +// if (!(*it)->CanRemove()) { +// ANSR_LOGD("Reminder has been expired: %{public}s", (*it)->Dump().c_str()); +// it++; +// continue; +// } +// int32_t reminderId = (*it)->GetReminderId(); +// ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); +// it = reminderVector_.erase(it); +// totalCount_--; +// store_->Delete(reminderId); +// } +// return nullptr; +// } + +// void ReminderDataManager::HandleImmediatelyShow( +// std::vector> &showImmediately, bool isSysTimeChanged) +// { +// bool isAlerting = false; +// for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { +// if ((*it)->IsShowing()) { +// continue; +// } +// if (((*it)->GetRingDuration() > 0) && !isAlerting) { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// ShowReminder((*it), true, false, isSysTimeChanged, true); +// isAlerting = true; +// } else { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// ShowReminder((*it), false, false, isSysTimeChanged, false); +// } +// } +// } + +// void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) +// { +// for (auto& reminder : extensionReminders) { +// ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); +// } +// } + +// sptr ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr &reminder) +// { +// reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE); +// uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli(); +// bool needShowImmediately = false; +// if (type == TIME_ZONE_CHANGE) { +// needShowImmediately = reminder->OnTimeZoneChange(); +// } +// if (type == DATE_TIME_CHANGE) { +// needShowImmediately = reminder->OnDateTimeChange(); +// } +// if (!needShowImmediately) { +// uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli(); +// if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { +// CloseReminder(reminder, true); +// } +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); +// return nullptr; +// } +// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); +// return reminder; +// } + +// void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) +// { +// // not add ReminderDataManager::MUTEX, as ShowActiveReminderExtendLocked has locked +// int32_t notificationId = reminder->GetNotificationId(); +// ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); +// int32_t curReminderId = reminder->GetReminderId(); +// sptr option1 = reminder->GetNotificationBundleOption(); +// if (option1 == nullptr) { +// ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); +// return; +// } + +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// int32_t tmpId = (*it)->GetReminderId(); +// if (tmpId == curReminderId) { +// continue; +// } +// if (!(*it)->IsShowing()) { +// continue; +// } +// sptr bundleOption = (*it)->GetNotificationBundleOption(); +// if (bundleOption == nullptr) { +// ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); +// continue; +// } +// if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) { +// if ((*it)->IsAlerting()) { +// StopAlertingReminder(*it); +// } +// (*it)->OnSameNotificationIdCovered(); +// RemoveFromShowedReminders(*it); +// store_->UpdateOrInsert((*it), bundleOption); +// } +// } +// } + +// void ReminderDataManager::Init(bool isFromBootComplete) +// { +// ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete); +// if (isFromBootComplete) { +// std::vector> immediatelyReminders; +// std::vector> extensionReminders; +// CheckReminderTime(immediatelyReminders, extensionReminders); +// HandleImmediatelyShow(immediatelyReminders, false); +// HandleExtensionReminder(extensionReminders); +// StartRecentReminder(); +// } +// if (IsReminderAgentReady()) { +// return; +// } +// // Register config observer for language change +// if (!RegisterConfigurationObserver()) { +// ANSR_LOGW("Register configuration observer failed."); +// return; +// } +// if (queue_ == nullptr) { +// queue_ = std::make_shared("ReminderDataManager"); +// if (queue_ == nullptr) { +// ANSR_LOGE("create ffrt queue failed!"); +// return; +// } +// } +// if (store_ == nullptr) { +// store_ = std::make_shared(); +// } +// if (store_->Init() != ReminderStore::STATE_OK) { +// ANSR_LOGW("Db init fail."); +// return; +// } +// InitServiceHandler(); +// LoadReminderFromDb(); +// InitUserId(); +// isReminderAgentReady_ = true; +// ANSR_LOGD("ReminderAgent is ready."); +// } + +// void ReminderDataManager::InitServiceHandler() +// { +// ANSR_LOGD("InitServiceHandler started"); +// if (serviceQueue_ != nullptr) { +// ANSR_LOGD("InitServiceHandler already init."); +// return; +// } +// serviceQueue_ = std::make_shared("ReminderService"); + +// ANSR_LOGD("InitServiceHandler suceeded."); +// } + +// void ReminderDataManager::CheckReminderTime(std::vector>& immediatelyReminders, +// std::vector>& extensionReminders) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto reminder : reminderVector_) { +// if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR) { +// continue; +// } + +// if (reminder->IsPullUpService()) { +// extensionReminders.push_back(reminder); +// } + +// if (reminder->OnDateTimeChange()) { +// immediatelyReminders.push_back(reminder); +// } +// } +// } + +// void ReminderDataManager::InitUserId() +// { +// currentUserId_ = MAIN_USER_ID; +// OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); +// } + +// bool ReminderDataManager::RegisterConfigurationObserver() +// { +// if (configChangeObserver_ != nullptr) { +// return true; +// } + +// auto appMgrClient = std::make_shared(); +// configChangeObserver_ = sptr( +// new (std::nothrow) ReminderConfigChangeObserver()); +// if (appMgrClient->RegisterConfigurationObserver(configChangeObserver_) != ERR_OK) { +// ANSR_LOGE("Register configuration observer failed."); +// return false; +// } +// return true; +// } + +// void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector> &reminders) const +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto reminderSptr : reminderVector_) { +// if (!(reminderSptr->ShouldShowImmediately())) { +// break; +// } +// if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) { +// reminderSptr->SetSnoozeTimesDynamic(0); +// } +// reminders.push_back(reminderSptr); +// } +// } + +// bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) const +// { +// if (reminder == nullptr) { +// return false; +// } +// auto option = reminder->GetNotificationBundleOption(); +// if (option == nullptr) { +// ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); +// return false; +// } +// bool isAllowed = false; +// ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); +// if (errCode != ERR_OK) { +// ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); +// return false; +// } +// return isAllowed; +// } + +// bool ReminderDataManager::IsReminderAgentReady() const +// { +// return isReminderAgentReady_; +// } + +// bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, +// const sptr &other) const +// { +// std::string bundleName = reminder->GetCreatorBundleName(); +// int32_t uid = reminder->GetCreatorUid(); +// if (uid == -1) { +// uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); +// } +// return bundleName == other->GetBundleName() && uid == other->GetUid(); +// } + +// bool ReminderDataManager::IsBelongToSameApp(const sptr &bundleOption, +// const sptr &other) const +// { +// int32_t uidSrc = bundleOption->GetUid(); +// int32_t uidTar = other->GetUid(); +// bool result = uidSrc == uidTar; +// int32_t userIdSrc = -1; +// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); +// int32_t userIdTar = -1; +// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); +// result = result && (userIdSrc == userIdTar); +// result = result && (bundleOption->GetBundleName() == other->GetBundleName()); +// return result; +// } + +// void ReminderDataManager::LoadReminderFromDb() +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// std::vector> existReminders = store_->GetAllValidReminders(); +// reminderVector_ = existReminders; +// ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// sptr bundleOption = new (std::nothrow) NotificationBundleOption(); +// if (bundleOption == nullptr) { +// ANS_LOGE("Failed to create bundle option due to low memory."); +// return; +// } +// bundleOption->SetBundleName((*it)->GetBundleName()); +// bundleOption->SetUid((*it)->GetUid()); +// (*it)->SetNotificationBundleOption(bundleOption); +// } +// totalCount_ = static_cast(reminderVector_.size()); +// ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; +// } + +// void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) +// { +// std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); +// PlaySoundAndVibration(reminder); +// } + +// std::string ReminderDataManager::GetCustomRingUri(const sptr &reminder) +// { +// if (reminder == nullptr) { +// return ""; +// } +// return reminder->GetCustomRingUri(); +// } + +// std::string ReminderDataManager::GetFullPath(const std::string& oriPath) +// { +// char buf[MAX_PATH_LEN] = {0}; +// char* path = GetOneCfgFile(oriPath.c_str(), buf, MAX_PATH_LEN); +// if (path == nullptr || *path == '\0') { +// ANSR_LOGE("GetOneCfgFile failed"); +// return ""; +// } +// std::string filePath = path; +// return filePath; +// } + +// void ReminderDataManager::PlaySoundAndVibration(const sptr &reminder) +// { +// if (reminder == nullptr) { +// ANSR_LOGE("Play sound and vibration failed as reminder is null."); +// return; +// } +// if (alertingReminderId_ != -1) { +// TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); +// } +// ANSR_LOGD("Play sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); +// #ifdef PLAYER_FRAMEWORK_ENABLE +// if (soundPlayer_ == nullptr) { +// soundPlayer_ = Media::PlayerFactory::CreatePlayer(); +// if (soundPlayer_ == nullptr) { +// ANSR_LOGE("Fail to creat player."); +// return; +// } +// } +// std::string customRingUri = reminder->GetCustomRingUri(); +// if (customRingUri.empty()) { +// // use default ring +// std::string defaultPath; +// if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { +// defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; +// } else { +// defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); +// } +// Uri defaultSound(defaultPath); +// soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); +// ANSR_LOGI("Play default sound."); +// } else { +// Global::Resource::ResourceManager::RawFileDescriptor desc; +// if (GetCustomRingFileDesc(reminder, desc)) { +// soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); +// } +// ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); +// } +// soundPlayer_->SetLooping(true); +// soundPlayer_->PrepareAsync(); +// soundPlayer_->Play(); +// #endif +// SetAlertingReminder(reminder); +// } + +// std::string ReminderDataManager::GetSoundUri(const sptr &reminder) +// { +// Uri uri = DEFAULT_NOTIFICATION_SOUND; +// if (advancedNotificationService_ == nullptr) { +// ANSR_LOGE("Ans instance is null."); +// return uri.GetSchemeSpecificPart(); +// } +// sptr bundle = reminder->GetNotificationBundleOption(); +// std::vector> slots; +// ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); +// if (errCode != ERR_OK) { +// ANSR_LOGW("Get sound uri fail, use default sound instead."); +// return uri.GetSchemeSpecificPart(); +// } +// for (auto it = slots.begin(); it != slots.end(); ++it) { +// if ((*it)->GetType() == reminder->GetSlotType()) { +// uri = (*it)->GetSound(); +// break; +// } +// } +// return uri.GetSchemeSpecificPart(); +// } + +// void ReminderDataManager::StopSoundAndVibrationLocked(const sptr &reminder) +// { +// std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); +// StopSoundAndVibration(reminder); +// } + +// void ReminderDataManager::StopSoundAndVibration(const sptr &reminder) +// { +// if (reminder == nullptr) { +// ANSR_LOGE("Stop sound and vibration failed as reminder is null."); +// return; +// } +// if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { +// ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \ +// "%{public}d, tarReminderId=%{public}d", alertingReminderId_.load(), reminder->GetReminderId()); +// return; +// } +// ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); +// #ifdef PLAYER_FRAMEWORK_ENABLE +// if (soundPlayer_ == nullptr) { +// ANSR_LOGW("Sound player is null"); +// } else { +// std::string customRingUri = reminder->GetCustomRingUri(); +// if (customRingUri.empty()) { +// ANSR_LOGI("Stop default sound."); +// } else { +// CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); +// } +// soundPlayer_->Stop(); +// soundPlayer_->Release(); +// soundPlayer_ = nullptr; +// } +// #endif +// sptr nullReminder = nullptr; +// SetAlertingReminder(nullReminder); +// } + +// void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) +// { +// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); +// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { +// if ((*it)->GetReminderId() == reminder->GetReminderId()) { +// ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); +// showedReminderVector_.erase(it); +// break; +// } +// } +// } + +// void ReminderDataManager::RefreshRemindersLocked(uint8_t type, +// std::vector>& immediatelyReminders, std::vector>& extensionReminders) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// if ((*it)->IsPullUpService()) { +// extensionReminders.push_back((*it)); +// } + +// sptr reminder = HandleRefreshReminder(type, (*it)); +// if (reminder != nullptr) { +// immediatelyReminders.push_back(reminder); +// } +// } +// } + +// void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { +// if (reminderId == (*it)->GetReminderId()) { +// ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); +// it = reminderVector_.erase(it); +// totalCount_--; +// store_->Delete(reminderId); +// break; +// } else { +// ++it; +// } +// } +// } + +// void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) +// { +// std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); +// StartTimer(reminderRequest, type); +// } + +// void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) +// { +// sptr timer = MiscServices::TimeServiceClient::GetInstance(); +// if (timer == nullptr) { +// ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); +// return; +// } +// time_t now; +// (void)time(&now); // unit is seconds. +// if (now < 0) { +// ANSR_LOGE("Get now time error"); +// return; +// } +// uint64_t triggerTime = 0; +// switch (type) { +// case TimerType::TRIGGER_TIMER: { +// if (timerId_ != 0) { +// ANSR_LOGE("Trigger timer has already started."); +// break; +// } +// triggerTime = HandleTriggerTimeInner(reminderRequest, type, timer); +// break; +// } +// case TimerType::ALERTING_TIMER: { +// if (timerIdAlerting_ != 0) { +// ANSR_LOGE("Alerting time out timer has already started."); +// break; +// } +// triggerTime = HandleAlertingTimeInner(reminderRequest, type, timer, now); +// break; +// } +// default: { +// ANSR_LOGE("TimerType not support"); +// break; +// } +// } +// if (triggerTime == 0) { +// ANSR_LOGW("Start timer fail"); +// } else { +// ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")", +// ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime); +// } +// } + +// uint64_t ReminderDataManager::HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, +// const sptr &timer) +// { +// uint64_t triggerTime = 0; +// SetActiveReminder(reminderRequest); +// timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); +// triggerTime = reminderRequest->GetTriggerTimeInMilli(); +// timer->StartTimer(timerId_, triggerTime); +// ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_); +// return triggerTime; +// } + +// uint64_t ReminderDataManager::HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, +// const sptr &timer, time_t now) +// { +// uint64_t triggerTime = 0; +// triggerTime = ReminderRequest::GetDurationSinceEpochInMilli(now) +// + static_cast(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS); +// timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); +// timer->StartTimer(timerIdAlerting_, triggerTime); +// ANSR_LOGD("Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_.load()); +// return triggerTime; +// } + +// void ReminderDataManager::StopTimerLocked(TimerType type) +// { +// std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); +// StopTimer(type); +// } + +// void ReminderDataManager::StopTimer(TimerType type) +// { +// sptr timer = MiscServices::TimeServiceClient::GetInstance(); +// if (timer == nullptr) { +// ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null."); +// return; +// } +// uint64_t timerId = 0; +// switch (type) { +// case TimerType::TRIGGER_TIMER: { +// timerId = timerId_; +// ANSR_LOGD("Stop timing (next triggerTime)"); +// break; +// } +// case TimerType::ALERTING_TIMER: { +// timerId = timerIdAlerting_; +// ANSR_LOGD("Stop timing (alerting time out)"); +// break; +// } +// default: { +// ANSR_LOGE("TimerType not support"); +// break; +// } +// } +// if (timerId == 0) { +// ANSR_LOGD("Timer is not running"); +// return; +// } +// ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId); +// timer->StopTimer(timerId); +// ResetStates(type); +// } + +// void ReminderDataManager::ResetStates(TimerType type) +// { +// uint64_t timerId = 0; +// switch (type) { +// case TimerType::TRIGGER_TIMER: { +// ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); +// timerId = timerId_; +// timerId_ = 0; +// activeReminderId_ = -1; +// break; +// } +// case TimerType::ALERTING_TIMER: { +// ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); +// timerId = timerIdAlerting_; +// timerIdAlerting_ = 0; +// alertingReminderId_ = -1; +// break; +// } +// default: { +// ANSR_LOGE("TimerType not support"); +// break; +// } +// } +// sptr timer = MiscServices::TimeServiceClient::GetInstance(); +// if (timer == nullptr) { +// ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); +// return; +// } +// if (timerId != 0) { +// timer->DestroyTimer(timerId); +// } +// } + +// void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// if (!reminder->IsSystemApp()) { +// ANSR_LOGI("Custom button click, is not system app"); +// return; +// } +// CloseReminder(reminder, false); +// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); +// std::string buttonPkgName = want.GetStringParam("PkgName"); +// std::string buttonAbilityName = want.GetStringParam("AbilityName"); + +// AAFwk::Want abilityWant; +// abilityWant.SetElementName(buttonPkgName, buttonAbilityName); +// abilityWant.SetUri(reminder->GetCustomButtonUri()); +// auto client = AppExecFwk::AbilityManagerClient::GetInstance(); +// if (client == nullptr) { +// return; +// } +// uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); +// int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); +// if (result != 0) { +// ANSR_LOGE("Start ability failed, result = %{public}d", result); +// return; +// } +// } + +// void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) +// { +// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); +// ANSR_LOGI("click reminder[%{public}d] start", reminderId); +// sptr reminder = FindReminderRequestLocked(reminderId); +// if (reminder == nullptr) { +// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); +// return; +// } +// CloseReminder(reminder, true); +// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); +// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); +// StartRecentReminder(); + +// auto wantInfo = reminder->GetWantAgentInfo(); +// if (wantInfo == nullptr || (wantInfo->pkgName.empty() && wantInfo->abilityName.empty())) { +// ANSR_LOGW("want info is nullptr or no pkg name"); +// return; +// } +// AAFwk::Want abilityWant; +// AppExecFwk::ElementName element("", wantInfo->pkgName, wantInfo->abilityName); +// abilityWant.SetElement(element); +// abilityWant.SetUri(wantInfo->uri); +// abilityWant.SetParams(wantInfo->parameters); +// int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); +// abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); + +// auto client = AppExecFwk::AbilityManagerClient::GetInstance(); +// if (client == nullptr) { +// ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); +// return; +// } +// uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); +// int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); +// if (result != 0) { +// ANSR_LOGE("Start ability failed, result = %{public}d", result); +// } +// } + +// std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, +// const int32_t uid) +// { +// AppExecFwk::BundleInfo bundleInfo; +// if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, +// AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { +// ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); +// return nullptr; +// } +// // obtains the resource manager +// std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); +// if (!resourceManager) { +// ANSR_LOGE("CreateResourceManager fail."); +// return nullptr; +// } +// // obtains the resource path. +// for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { +// std::string moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; +// if (moduleResPath.empty()) { +// continue; +// } +// if (!resourceManager->AddResource(moduleResPath.c_str())) { +// ANSR_LOGW("AddResource fail."); +// } +// } +// // obtains the current system language. +// std::unique_ptr resConfig(Global::Resource::CreateResConfig()); +// UErrorCode status = U_ZERO_ERROR; +// icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); +// resConfig->SetLocaleInfo(locale); +// resourceManager->UpdateResConfig(*resConfig); +// return resourceManager; +// } + +// void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, +// const std::vector>& reminders) +// { +// // obtains the bundle info by bundle name +// if (reminders.empty()) { +// return; +// } + +// std::string bundleName = reminders[0]->GetBundleName(); +// // obtains the resource manager +// auto resourceMgr = GetResourceMgr(bundleName, uid); +// if (resourceMgr == nullptr) { +// ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", +// uid, bundleName.c_str()); +// return; +// } +// // update action button title +// for (auto reminder : reminders) { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// reminder->OnLanguageChange(resourceMgr); +// } +// } + +// void ReminderDataManager::OnLanguageChanged() +// { +// ANSR_LOGI("System language config changed start."); +// std::unordered_map>> reminders; +// { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { +// reminders[(*it)->GetUid()].push_back((*it)); +// } +// } +// for (auto& each : reminders) { +// UpdateReminderLanguageLocked(each.first, each.second); +// } +// std::vector> showedReminder; +// { +// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); +// showedReminder = showedReminderVector_; +// } +// for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { +// std::lock_guard lock(ReminderDataManager::MUTEX); +// ShowReminder((*it), false, false, false, false); +// } +// ANSR_LOGI("System language config changed end."); +// } + +// void ReminderDataManager::OnRemoveAppMgr() +// { +// std::lock_guard lock(appMgrMutex_); +// appMgrProxy_ = nullptr; +// } + +// bool ReminderDataManager::ConnectAppMgr() +// { +// if (appMgrProxy_ != nullptr) { +// return true; +// } + +// sptr systemAbilityManager = +// SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +// if (systemAbilityManager == nullptr) { +// ANSR_LOGE("get SystemAbilityManager failed"); +// return false; +// } + +// sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); +// if (remoteObject == nullptr) { +// ANSR_LOGE("get app manager service failed"); +// return false; +// } + +// appMgrProxy_ = iface_cast(remoteObject); +// if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { +// ANSR_LOGE("get app mgr proxy failed!"); +// return false; +// } +// return true; +// } + +// void ReminderDataManager::CheckNeedNotifyStatus(const sptr &reminder, +// const ReminderRequest::ActionButtonType buttonType) +// { +// const std::string bundleName = reminder->GetBundleName(); +// if (bundleName.empty()) { +// return; +// } +// bool isRunning = false; +// { +// std::lock_guard lock(appMgrMutex_); +// if (!ConnectAppMgr()) { +// return; +// } +// isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); +// } +// if (!isRunning) { +// return; +// } + +// EventFwk::Want want; +// // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string +// want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); +// EventFwk::CommonEventData eventData(want); + +// std::string data; +// data.append(std::to_string(static_cast(buttonType))).append(","); +// data.append(std::to_string(reminder->GetReminderId())); +// eventData.SetData(data); + +// EventFwk::CommonEventPublishInfo info; +// info.SetBundleName(bundleName); +// if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { +// ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); +// } +// } +// } +// } diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp index 46284fe3a..d73a6e36c 100644 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ b/services/ans/src/reminder_data_manager_inner.cpp @@ -1,168 +1,168 @@ -/* - * Copyright (c) 2024-2024 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. - */ +// /* +// * Copyright (c) 2024-2024 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 "reminder_data_manager.h" +// #include "reminder_data_manager.h" -#include "ability_manager_client.h" -#include "access_token_helper.h" -#include "ans_log_wrapper.h" -#include "ans_const_define.h" -#include "common_event_support.h" -#include "common_event_manager.h" -#include "reminder_request_calendar.h" -#include "in_process_call_wrapper.h" -#ifdef DEVICE_STANDBY_ENABLE -#include "standby_service_client.h" -#include "allow_type.h" -#endif -#include "ipc_skeleton.h" -#include "notification_slot.h" -#include "os_account_manager.h" -#include "reminder_event_manager.h" -#include "time_service_client.h" -#include "singleton.h" -#include "locale_config.h" -#include "bundle_manager_helper.h" -#include "datashare_predicates_object.h" -#include "datashare_value_object.h" -#include "datashare_helper.h" -#include "data_share_permission.h" -#include "datashare_errno.h" -#include "datashare_template.h" -#include "system_ability_definition.h" -#include "app_mgr_constants.h" -#include "iservice_registry.h" -#include "config_policy_utils.h" -#include "hitrace_meter_adapter.h" -#ifdef HAS_HISYSEVENT_PART -#include "hisysevent.h" -#endif +// #include "ability_manager_client.h" +// #include "access_token_helper.h" +// #include "ans_log_wrapper.h" +// #include "ans_const_define.h" +// #include "common_event_support.h" +// #include "common_event_manager.h" +// #include "reminder_request_calendar.h" +// #include "in_process_call_wrapper.h" +// #ifdef DEVICE_STANDBY_ENABLE +// #include "standby_service_client.h" +// #include "allow_type.h" +// #endif +// #include "ipc_skeleton.h" +// #include "notification_slot.h" +// #include "os_account_manager.h" +// #include "reminder_event_manager.h" +// #include "time_service_client.h" +// #include "singleton.h" +// #include "locale_config.h" +// #include "bundle_manager_helper.h" +// #include "datashare_predicates_object.h" +// #include "datashare_value_object.h" +// #include "datashare_helper.h" +// #include "data_share_permission.h" +// #include "datashare_errno.h" +// #include "datashare_template.h" +// #include "system_ability_definition.h" +// #include "app_mgr_constants.h" +// #include "iservice_registry.h" +// #include "config_policy_utils.h" +// #include "hitrace_meter_adapter.h" +// #ifdef HAS_HISYSEVENT_PART +// #include "hisysevent.h" +// #endif -namespace OHOS { -namespace Notification { -namespace { -constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. -} +// namespace OHOS { +// namespace Notification { +// namespace { +// constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. +// } -bool ReminderDataManager::IsSystemReady() -{ - return saReadyFlag_ >= ALL_SA_READY_FLAG; -} +// bool ReminderDataManager::IsSystemReady() +// { +// return saReadyFlag_ >= ALL_SA_READY_FLAG; +// } -bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, - const uint32_t callerTokenId) -{ - auto actionButtonMap = reminder->GetActionButtons(); - for (auto it = actionButtonMap.begin(); it != actionButtonMap.end(); ++it) { - ReminderRequest::ActionButtonInfo& buttonInfo = it->second; - if (buttonInfo.dataShareUpdate->uri.empty()) { - continue; - } - Uri uri(buttonInfo.dataShareUpdate->uri); - auto ret = DataShare::DataSharePermission::VerifyPermission(callerTokenId, uri, false); - if (ret != DataShare::E_OK) { - ANSR_LOGE("publish failed, DataSharePermission::VerifyPermission return error[%{public}d],", - static_cast(ret)); - return false; - } - } - return true; -} +// bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, +// const uint32_t callerTokenId) +// { +// auto actionButtonMap = reminder->GetActionButtons(); +// for (auto it = actionButtonMap.begin(); it != actionButtonMap.end(); ++it) { +// ReminderRequest::ActionButtonInfo& buttonInfo = it->second; +// if (buttonInfo.dataShareUpdate->uri.empty()) { +// continue; +// } +// Uri uri(buttonInfo.dataShareUpdate->uri); +// auto ret = DataShare::DataSharePermission::VerifyPermission(callerTokenId, uri, false); +// if (ret != DataShare::E_OK) { +// ANSR_LOGE("publish failed, DataSharePermission::VerifyPermission return error[%{public}d],", +// static_cast(ret)); +// return false; +// } +// } +// return true; +// } -void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, - const int64_t autoDeletedTime) -{ - ANSR_LOGI("auto delete reminder start"); - std::vector> showedReminder; - { - std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - showedReminder = showedReminderVector_; - } - for (auto reminder : showedReminder) { - if (reminder == nullptr) { - continue; - } +// void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, +// const int64_t autoDeletedTime) +// { +// ANSR_LOGI("auto delete reminder start"); +// std::vector> showedReminder; +// { +// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); +// showedReminder = showedReminderVector_; +// } +// for (auto reminder : showedReminder) { +// if (reminder == nullptr) { +// continue; +// } - if (reminder->GetUid() != uid || notificationId != reminder->GetNotificationId() || - reminder->GetAutoDeletedTime() != autoDeletedTime) { - continue; - } - CloseReminder(reminder, true); - UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); - CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); - } - StartRecentReminder(); -} +// if (reminder->GetUid() != uid || notificationId != reminder->GetNotificationId() || +// reminder->GetAutoDeletedTime() != autoDeletedTime) { +// continue; +// } +// CloseReminder(reminder, true); +// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); +// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); +// } +// StartRecentReminder(); +// } -void ReminderDataManager::OnBundleMgrServiceStart() -{ - saReadyFlag_.fetch_add(1); -} +// void ReminderDataManager::OnBundleMgrServiceStart() +// { +// saReadyFlag_.fetch_add(1); +// } -void ReminderDataManager::OnAbilityMgrServiceStart() -{ - saReadyFlag_.fetch_add(1); -} +// void ReminderDataManager::OnAbilityMgrServiceStart() +// { +// saReadyFlag_.fetch_add(1); +// } -bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, - Global::Resource::ResourceManager::RawFileDescriptor& desc) -{ - // obtains the resource manager - std::lock_guard locker(resourceMutex_); - soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); - if (soundResource_ == nullptr) { - ANSR_LOGE("GetResourceMgr fail."); - return false; - } - auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); - if (result != Global::Resource::SUCCESS) { - ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); - return false; - } - return true; -} +// bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, +// Global::Resource::ResourceManager::RawFileDescriptor& desc) +// { +// // obtains the resource manager +// std::lock_guard locker(resourceMutex_); +// soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); +// if (soundResource_ == nullptr) { +// ANSR_LOGE("GetResourceMgr fail."); +// return false; +// } +// auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); +// if (result != Global::Resource::SUCCESS) { +// ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); +// return false; +// } +// return true; +// } -void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) -{ - std::lock_guard locker(resourceMutex_); - if (soundResource_ == nullptr) { - ANSR_LOGW("ResourceManager is nullptr."); - return; - } - auto result = soundResource_->CloseRawFileDescriptor(customRingUri); - if (result != Global::Resource::SUCCESS) { - ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); - } - ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); - soundResource_ = nullptr; -} +// void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) +// { +// std::lock_guard locker(resourceMutex_); +// if (soundResource_ == nullptr) { +// ANSR_LOGW("ResourceManager is nullptr."); +// return; +// } +// auto result = soundResource_->CloseRawFileDescriptor(customRingUri); +// if (result != Global::Resource::SUCCESS) { +// ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); +// } +// ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); +// soundResource_ = nullptr; +// } -void ReminderDataManager::ReportSysEvent(const sptr& reminder) -{ -#ifdef HAS_HISYSEVENT_PART - std::string event = "ALARM_TRIGGER"; - std::string bundleName = reminder->GetBundleName(); - int32_t uid = reminder->GetUid(); - int32_t type = static_cast(reminder->GetReminderType()); - int32_t repeat = static_cast(reminder->IsRepeat()); - uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); - int32_t ringTime = static_cast(reminder->GetRingDuration()); - HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, - "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, - "RING_TIME", ringTime); -#endif -} -} -} +// void ReminderDataManager::ReportSysEvent(const sptr& reminder) +// { +// #ifdef HAS_HISYSEVENT_PART +// std::string event = "ALARM_TRIGGER"; +// std::string bundleName = reminder->GetBundleName(); +// int32_t uid = reminder->GetUid(); +// int32_t type = static_cast(reminder->GetReminderType()); +// int32_t repeat = static_cast(reminder->IsRepeat()); +// uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); +// int32_t ringTime = static_cast(reminder->GetRingDuration()); +// HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, +// "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, +// "RING_TIME", ringTime); +// #endif +// } +// } +// } diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index 26359baa0..b56f8d9e2 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -1,361 +1,361 @@ -/* - * Copyright (c) 2021-2022 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 "reminder_event_manager.h" - -#include "ans_log_wrapper.h" -#include "bundle_constants.h" -#include "bundle_mgr_interface.h" -#include "common_event_manager.h" -#include "common_event_support.h" -#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 "notification_helper.h" -#include "string_ex.h" - -using namespace OHOS::EventFwk; -namespace OHOS { -namespace Notification { -static const std::string NOTIFICATION_LABEL = "REMINDER_AGENT"; -std::shared_ptr ReminderEventManager::subscriber_ - = nullptr; - -ReminderEventManager::ReminderEventManager(std::shared_ptr &reminderDataManager) -{ - init(reminderDataManager); -} - -void ReminderEventManager::init(std::shared_ptr &reminderDataManager) const -{ - MatchingSkills customMatchingSkills; - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT); - customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLICK_ALERT); - CommonEventSubscribeInfo customSubscriberInfo(customMatchingSkills); - customSubscriberInfo.SetPermission("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); - customSubscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); - auto customSubscriber = std::make_shared(customSubscriberInfo, reminderDataManager); - - MatchingSkills matchingSkills; - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIME_CHANGED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); - matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); - CommonEventSubscribeInfo subscriberInfo(matchingSkills); - subscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); - auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); - - std::string identity = IPCSkeleton::ResetCallingIdentity(); - if (CommonEventManager::SubscribeCommonEvent(subscriber) && - CommonEventManager::SubscribeCommonEvent(customSubscriber)) { - ANSR_LOGD("SubscribeCommonEvent ok"); - } else { - ANSR_LOGD("SubscribeCommonEvent fail"); - } - IPCSkeleton::SetCallingIdentity(identity); - - subscriber_ = std::make_shared(reminderDataManager); - if (NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { - ANSR_LOGD("SubscribeNotification failed"); - } - - SubscribeSystemAbility(reminderDataManager); -} - -void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const -{ - sptr statusChangeListener - = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); - if (statusChangeListener == nullptr) { - ANSR_LOGE("Failed to create statusChangeListener due to no memory."); - return; - } - // app mgr - sptr appMgrStatusChangeListener - = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); - if (appMgrStatusChangeListener == nullptr) { - ANSR_LOGE("Failed to create appMgrStatusChangeListener due to no memory."); - return; - } - // ability mgr - sptr abilityMgrStatusListener - = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); - if (abilityMgrStatusListener == nullptr) { - ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); - return; - } - - sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (samgrProxy == nullptr) { - ANSR_LOGD("samgrProxy is null"); - return; - } - int32_t ret = samgrProxy->SubscribeSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, statusChangeListener); - if (ret != ERR_OK) { - ANSR_LOGE("subscribe system ability id: %{public}d failed", BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); - } - ret = samgrProxy->SubscribeSystemAbility(APP_MGR_SERVICE_ID, appMgrStatusChangeListener); - if (ret != ERR_OK) { - ANSR_LOGE("subscribe system ability id: %{public}d failed", APP_MGR_SERVICE_ID); - } - ret = samgrProxy->SubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); - if (ret != ERR_OK) { - ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); - } -} - -ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( - const CommonEventSubscribeInfo &subscriberInfo, - std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) -{ - reminderDataManager_ = reminderDataManager; -} - -ReminderEventManager::ReminderEventCustomSubscriber::ReminderEventCustomSubscriber( - const CommonEventSubscribeInfo &subscriberInfo, - std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) -{ - reminderDataManager_ = reminderDataManager; -} - -void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) -{ - Want want = data.GetWant(); - std::string action = want.GetAction(); - ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); - if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { - reminderDataManager_->ShowActiveReminder(want); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT) { - reminderDataManager_->TerminateAlerting(want); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_CLOSE_ALERT) { - reminderDataManager_->CloseReminder(want, true); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT) { - reminderDataManager_->SnoozeReminder(want); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT) { - reminderDataManager_->HandleCustomButtonClick(want); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { - reminderDataManager_->CloseReminder(want, false); - return; - } - if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { - reminderDataManager_->ClickReminder(want); - return; - } -} - -void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) -{ - Want want = data.GetWant(); - std::string action = want.GetAction(); - ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); - if (action == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) { - reminderDataManager_->Init(true); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { - HandlePackageRemove(want); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { - HandlePackageRemove(want); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { - HandleProcessDied(want); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { - reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::TIME_ZONE_CHANGE); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_TIME_CHANGED) { - reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::DATE_TIME_CHANGE); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { - reminderDataManager_->OnUserSwitch(data.GetCode()); - return; - } - if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { - reminderDataManager_->OnUserRemove(data.GetCode()); - return; - } -} - -void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const -{ - OHOS::AppExecFwk::ElementName ele = want.GetElement(); - std::string bundleName = ele.GetBundleName(); - int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); - int32_t uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); - reminderDataManager_->CancelAllReminders(bundleName, userId, uid); -} - -void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const -{ - sptr bundleOption = GetBundleOption(want); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option error."); - return; - } - reminderDataManager_->OnProcessDiedLocked(bundleOption); -} - -sptr ReminderEventManager::ReminderEventSubscriber::GetBundleOption( - const OHOS::EventFwk::Want &want) const -{ - OHOS::AppExecFwk::ElementName ele = want.GetElement(); - std::string bundleName = ele.GetBundleName(); - int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); - int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); - ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); - sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); - if (bundleOption == nullptr) { - ANSR_LOGE("new NotificationBundleOption fail due to no memory."); - } - return bundleOption; -} - -ReminderEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener( - std::shared_ptr &reminderDataManager) -{ - reminderDataManager_ = reminderDataManager; -} - -void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( - int32_t systemAbilityId, const std::string& deviceId) -{ - ANSR_LOGD("OnAddSystemAbilityInner"); - switch (systemAbilityId) { - case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: - ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); - reminderDataManager_->OnBundleMgrServiceStart(); - break; - case APP_MGR_SERVICE_ID: - ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); - break; - case ABILITY_MGR_SERVICE_ID: - ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); - reminderDataManager_->OnAbilityMgrServiceStart(); - break; - default: - break; - } -} - -void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( - int32_t systemAbilityId, const std::string& deviceId) -{ - ANSR_LOGD("OnRemoveSystemAbilityInner"); - switch (systemAbilityId) { - case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: - ANSR_LOGD("OnRemoveSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); - break; - case APP_MGR_SERVICE_ID: - ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); - reminderDataManager_->OnRemoveAppMgr(); - break; - case ABILITY_MGR_SERVICE_ID: - ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); - break; - default: - break; - } -} - -ReminderEventManager::ReminderNotificationSubscriber::ReminderNotificationSubscriber( - std::shared_ptr &reminderDataManager) -{ - reminderDataManager_ = reminderDataManager; -} - -ReminderEventManager::ReminderNotificationSubscriber::~ReminderNotificationSubscriber() {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnConnected() {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnDisconnected() {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( - const std::shared_ptr ¬ification, - const std::shared_ptr &sortingMap, int deleteReason) -{ - // Note: Don't modify param notification - if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { - return; - } - if (notification == nullptr) { - return; - } - NotificationRequest request = notification->GetNotificationRequest(); - std::string label = request.GetLabel(); - int64_t autoDeletedTime = request.GetAutoDeletedTime(); - if (autoDeletedTime <= 0 || label != NOTIFICATION_LABEL) { - return; - } - - if (reminderDataManager_ == nullptr) { - return; - } - int32_t notificationId = request.GetNotificationId(); - int32_t uid = request.GetOwnerUid() == 0 ? request.GetCreatorUid() : request.GetOwnerUid(); - reminderDataManager_->HandleAutoDeleteReminder(notificationId, uid, autoDeletedTime); -} - -void ReminderEventManager::ReminderNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, - const std::shared_ptr &sortingMap) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnUpdate( - const std::shared_ptr &sortingMap) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnDied() {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnDoNotDisturbDateChange( - const std::shared_ptr &date) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnEnabledNotificationChanged( - const std::shared_ptr &callbackData) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeChanged( - const std::shared_ptr &badgeData) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeEnabledChanged( - const sptr &callbackData) {} - -void ReminderEventManager::ReminderNotificationSubscriber::OnBatchCanceled( - const std::vector> &requestList, - const std::shared_ptr &sortingMap, int32_t deleteReason) {} -} // namespace OHOS -} // namespace Notification +// /* +// * Copyright (c) 2021-2022 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 "reminder_event_manager.h" + +// #include "ans_log_wrapper.h" +// #include "bundle_constants.h" +// #include "bundle_mgr_interface.h" +// #include "common_event_manager.h" +// #include "common_event_support.h" +// #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 "notification_helper.h" +// #include "string_ex.h" + +// using namespace OHOS::EventFwk; +// namespace OHOS { +// namespace Notification { +// static const std::string NOTIFICATION_LABEL = "REMINDER_AGENT"; +// std::shared_ptr ReminderEventManager::subscriber_ +// = nullptr; + +// ReminderEventManager::ReminderEventManager(std::shared_ptr &reminderDataManager) +// { +// init(reminderDataManager); +// } + +// void ReminderEventManager::init(std::shared_ptr &reminderDataManager) const +// { +// MatchingSkills customMatchingSkills; +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT); +// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLICK_ALERT); +// CommonEventSubscribeInfo customSubscriberInfo(customMatchingSkills); +// customSubscriberInfo.SetPermission("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); +// customSubscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); +// auto customSubscriber = std::make_shared(customSubscriberInfo, reminderDataManager); + +// MatchingSkills matchingSkills; +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIME_CHANGED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); +// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); +// CommonEventSubscribeInfo subscriberInfo(matchingSkills); +// subscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); +// auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); + +// std::string identity = IPCSkeleton::ResetCallingIdentity(); +// if (CommonEventManager::SubscribeCommonEvent(subscriber) && +// CommonEventManager::SubscribeCommonEvent(customSubscriber)) { +// ANSR_LOGD("SubscribeCommonEvent ok"); +// } else { +// ANSR_LOGD("SubscribeCommonEvent fail"); +// } +// IPCSkeleton::SetCallingIdentity(identity); + +// subscriber_ = std::make_shared(reminderDataManager); +// if (NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { +// ANSR_LOGD("SubscribeNotification failed"); +// } + +// SubscribeSystemAbility(reminderDataManager); +// } + +// void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const +// { +// sptr statusChangeListener +// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); +// if (statusChangeListener == nullptr) { +// ANSR_LOGE("Failed to create statusChangeListener due to no memory."); +// return; +// } +// // app mgr +// sptr appMgrStatusChangeListener +// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); +// if (appMgrStatusChangeListener == nullptr) { +// ANSR_LOGE("Failed to create appMgrStatusChangeListener due to no memory."); +// return; +// } +// // ability mgr +// sptr abilityMgrStatusListener +// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); +// if (abilityMgrStatusListener == nullptr) { +// ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); +// return; +// } + +// sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); +// if (samgrProxy == nullptr) { +// ANSR_LOGD("samgrProxy is null"); +// return; +// } +// int32_t ret = samgrProxy->SubscribeSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, statusChangeListener); +// if (ret != ERR_OK) { +// ANSR_LOGE("subscribe system ability id: %{public}d failed", BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); +// } +// ret = samgrProxy->SubscribeSystemAbility(APP_MGR_SERVICE_ID, appMgrStatusChangeListener); +// if (ret != ERR_OK) { +// ANSR_LOGE("subscribe system ability id: %{public}d failed", APP_MGR_SERVICE_ID); +// } +// ret = samgrProxy->SubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); +// if (ret != ERR_OK) { +// ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); +// } +// } + +// ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( +// const CommonEventSubscribeInfo &subscriberInfo, +// std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) +// { +// reminderDataManager_ = reminderDataManager; +// } + +// ReminderEventManager::ReminderEventCustomSubscriber::ReminderEventCustomSubscriber( +// const CommonEventSubscribeInfo &subscriberInfo, +// std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) +// { +// reminderDataManager_ = reminderDataManager; +// } + +// void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +// { +// Want want = data.GetWant(); +// std::string action = want.GetAction(); +// ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); +// if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { +// reminderDataManager_->ShowActiveReminder(want); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT) { +// reminderDataManager_->TerminateAlerting(want); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_CLOSE_ALERT) { +// reminderDataManager_->CloseReminder(want, true); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT) { +// reminderDataManager_->SnoozeReminder(want); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT) { +// reminderDataManager_->HandleCustomButtonClick(want); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { +// reminderDataManager_->CloseReminder(want, false); +// return; +// } +// if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { +// reminderDataManager_->ClickReminder(want); +// return; +// } +// } + +// void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +// { +// Want want = data.GetWant(); +// std::string action = want.GetAction(); +// ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); +// if (action == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) { +// reminderDataManager_->Init(true); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { +// HandlePackageRemove(want); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { +// HandlePackageRemove(want); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { +// HandleProcessDied(want); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { +// reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::TIME_ZONE_CHANGE); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_TIME_CHANGED) { +// reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::DATE_TIME_CHANGE); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { +// reminderDataManager_->OnUserSwitch(data.GetCode()); +// return; +// } +// if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { +// reminderDataManager_->OnUserRemove(data.GetCode()); +// return; +// } +// } + +// void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const +// { +// OHOS::AppExecFwk::ElementName ele = want.GetElement(); +// std::string bundleName = ele.GetBundleName(); +// int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); +// int32_t uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); +// reminderDataManager_->CancelAllReminders(bundleName, userId, uid); +// } + +// void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const +// { +// sptr bundleOption = GetBundleOption(want); +// if (bundleOption == nullptr) { +// ANSR_LOGE("Get bundle option error."); +// return; +// } +// reminderDataManager_->OnProcessDiedLocked(bundleOption); +// } + +// sptr ReminderEventManager::ReminderEventSubscriber::GetBundleOption( +// const OHOS::EventFwk::Want &want) const +// { +// OHOS::AppExecFwk::ElementName ele = want.GetElement(); +// std::string bundleName = ele.GetBundleName(); +// int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); +// int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); +// ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); +// sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); +// if (bundleOption == nullptr) { +// ANSR_LOGE("new NotificationBundleOption fail due to no memory."); +// } +// return bundleOption; +// } + +// ReminderEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener( +// std::shared_ptr &reminderDataManager) +// { +// reminderDataManager_ = reminderDataManager; +// } + +// void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( +// int32_t systemAbilityId, const std::string& deviceId) +// { +// ANSR_LOGD("OnAddSystemAbilityInner"); +// switch (systemAbilityId) { +// case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: +// ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); +// reminderDataManager_->OnBundleMgrServiceStart(); +// break; +// case APP_MGR_SERVICE_ID: +// ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); +// break; +// case ABILITY_MGR_SERVICE_ID: +// ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); +// reminderDataManager_->OnAbilityMgrServiceStart(); +// break; +// default: +// break; +// } +// } + +// void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( +// int32_t systemAbilityId, const std::string& deviceId) +// { +// ANSR_LOGD("OnRemoveSystemAbilityInner"); +// switch (systemAbilityId) { +// case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: +// ANSR_LOGD("OnRemoveSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); +// break; +// case APP_MGR_SERVICE_ID: +// ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); +// reminderDataManager_->OnRemoveAppMgr(); +// break; +// case ABILITY_MGR_SERVICE_ID: +// ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); +// break; +// default: +// break; +// } +// } + +// ReminderEventManager::ReminderNotificationSubscriber::ReminderNotificationSubscriber( +// std::shared_ptr &reminderDataManager) +// { +// reminderDataManager_ = reminderDataManager; +// } + +// ReminderEventManager::ReminderNotificationSubscriber::~ReminderNotificationSubscriber() {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnConnected() {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnDisconnected() {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( +// const std::shared_ptr ¬ification, +// const std::shared_ptr &sortingMap, int deleteReason) +// { +// // Note: Don't modify param notification +// if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { +// return; +// } +// if (notification == nullptr) { +// return; +// } +// NotificationRequest request = notification->GetNotificationRequest(); +// std::string label = request.GetLabel(); +// int64_t autoDeletedTime = request.GetAutoDeletedTime(); +// if (autoDeletedTime <= 0 || label != NOTIFICATION_LABEL) { +// return; +// } + +// if (reminderDataManager_ == nullptr) { +// return; +// } +// int32_t notificationId = request.GetNotificationId(); +// int32_t uid = request.GetOwnerUid() == 0 ? request.GetCreatorUid() : request.GetOwnerUid(); +// reminderDataManager_->HandleAutoDeleteReminder(notificationId, uid, autoDeletedTime); +// } + +// void ReminderEventManager::ReminderNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, +// const std::shared_ptr &sortingMap) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnUpdate( +// const std::shared_ptr &sortingMap) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnDied() {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnDoNotDisturbDateChange( +// const std::shared_ptr &date) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnEnabledNotificationChanged( +// const std::shared_ptr &callbackData) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeChanged( +// const std::shared_ptr &badgeData) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeEnabledChanged( +// const sptr &callbackData) {} + +// void ReminderEventManager::ReminderNotificationSubscriber::OnBatchCanceled( +// const std::vector> &requestList, +// const std::shared_ptr &sortingMap, int32_t deleteReason) {} +// } // namespace OHOS +// } // namespace Notification diff --git a/services/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp index 3a8b08677..6429468fe 100644 --- a/services/ans/src/reminder_store.cpp +++ b/services/ans/src/reminder_store.cpp @@ -1,817 +1,817 @@ -/* - * Copyright (c) 2022 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 "reminder_store.h" - -#include -#include -#include -#include - -#include "fa_ability_context.h" -#include "ans_log_wrapper.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_request_alarm.h" -#include "reminder_request_timer.h" -#include "reminder_request_calendar.h" -#include "reminder_store_strategy.h" - -namespace OHOS { -namespace Notification { -namespace { -const int32_t REMINDER_RDB_VERSION_V1 = 1; -const int32_t REMINDER_RDB_VERSION_V2 = 2; -const int32_t REMINDER_RDB_VERSION_V3 = 3; -const int32_t REMINDER_RDB_VERSION_V4 = 4; -const int32_t REMINDER_RDB_VERSION_V5 = 5; -const int32_t REMINDER_RDB_VERSION_V6 = 6; -const int32_t REMINDER_RDB_VERSION = 7; -} - -const int32_t ReminderStore::STATE_OK = 0; -const int32_t ReminderStore::STATE_FAIL = -1; -const std::string ReminderStore::REMINDER_DB_DIR = "/data/service/el1/public/notification/"; -const std::string ReminderStore::REMINDER_DB_NAME = "notification.db"; - -int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore& store) -{ - ANSR_LOGI("Create table"); - return CreateTable(store); -} - -int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade( - NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) -{ - ANSR_LOGI("OnUpgrade oldVersion is %{public}d, newVersion is %{public}d", oldVersion, newVersion); - if (oldVersion < newVersion && newVersion == REMINDER_RDB_VERSION) { - switch (oldVersion) { - case REMINDER_RDB_VERSION_V1: - AddRdbColum(store, ReminderTable::TABLE_NAME, "groupId", "TEXT", "''"); - [[fallthrough]]; - case REMINDER_RDB_VERSION_V2: - AddRdbColum(store, ReminderTable::TABLE_NAME, "custom_ring_uri", "TEXT", "''"); - AddRdbColum(store, ReminderTable::TABLE_NAME, "snooze_slot_id", "INT", "3"); - [[fallthrough]]; - case REMINDER_RDB_VERSION_V3: - AddRdbColum(store, ReminderTable::TABLE_NAME, "creator_bundle_name", "TEXT", "''"); - [[fallthrough]]; - case REMINDER_RDB_VERSION_V4: - CreateTable(store); - CopyData(store); - [[fallthrough]]; - case REMINDER_RDB_VERSION_V5: - AddRdbColum(store, ReminderBaseTable::TABLE_NAME, ReminderBaseTable::CREATOR_UID, "INT", "-1"); - [[fallthrough]]; - case REMINDER_RDB_VERSION_V6: - AddRdbColum(store, ReminderCalendarTable::TABLE_NAME, - ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, "BIGINT", "0"); - [[fallthrough]]; - default: - break; - } - } - store.SetVersion(newVersion); - return NativeRdb::E_OK; -} - -int32_t ReminderStore::ReminderStoreDataCallBack::OnDowngrade( - NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) -{ - ANSR_LOGI("OnDowngrade currentVersion is %{public}d, targetVersion is %{public}d", currentVersion, targetVersion); - if (currentVersion > targetVersion && targetVersion <= REMINDER_RDB_VERSION_V4) { - std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTable::TABLE_NAME + " (" - + ReminderTable::ADD_COLUMNS + ")"; - int32_t ret = store.ExecuteSql(createSql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Create reminder table failed:%{public}d", ret); - } - return ret; - } - store.SetVersion(targetVersion); - return NativeRdb::E_OK; -} - -int32_t ReminderStore::ReminderStoreDataCallBack::CreateTable(NativeRdb::RdbStore& store) -{ - std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderBaseTable::TABLE_NAME + " (" - + ReminderBaseTable::ADD_COLUMNS + ")"; - int32_t ret = store.ExecuteSql(createSql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Create reminder_base table failed:%{public}d", ret); - return ret; - } - - createSql = "CREATE TABLE IF NOT EXISTS " + ReminderAlarmTable::TABLE_NAME + " (" - + ReminderAlarmTable::ADD_COLUMNS + ")"; - ret = store.ExecuteSql(createSql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Create reminder_alarm table failed:%{public}d", ret); - return ret; - } - - createSql = "CREATE TABLE IF NOT EXISTS " + ReminderCalendarTable::TABLE_NAME + " (" - + ReminderCalendarTable::ADD_COLUMNS + ")"; - ret = store.ExecuteSql(createSql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Create reminder_calendar table failed:%{public}d", ret); - return ret; - } - - createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTimerTable::TABLE_NAME + " (" - + ReminderTimerTable::ADD_COLUMNS + ")"; - ret = store.ExecuteSql(createSql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Create reminder_timer table failed:%{public}d", ret); - return ret; - } - return ret; -} - -int32_t ReminderStore::ReminderStoreDataCallBack::CopyData(NativeRdb::RdbStore& store) -{ - // select old data - auto reminders = GetOldReminders(store); - // insert new data - if (!reminders.empty()) { - InsertNewReminders(store, reminders); - } - // delete old table - std::string sql = "DELETE FROM " + ReminderTable::TABLE_NAME; - store.ExecuteSql(sql); - return NativeRdb::E_OK; -} - -std::vector> ReminderStore::ReminderStoreDataCallBack::GetOldReminders(NativeRdb::RdbStore& store) -{ - std::string sql = "SELECT " + ReminderTable::SELECT_COLUMNS + " FROM " - + ReminderTable::TABLE_NAME; - std::vector> reminders; - std::vector whereArgs; - auto queryResult = store.QuerySql(sql, whereArgs); - if (queryResult == nullptr) { - return reminders; - } - - bool isLastRow = false; - queryResult->IsAtLastRow(isLastRow); - while (!isLastRow) { - queryResult->GoToNextRow(); - int32_t reminderId; - int32_t reminderType; - GetInt32Val(queryResult, ReminderTable::REMINDER_ID, reminderId); - GetInt32Val(queryResult, ReminderTable::REMINDER_TYPE, reminderType); - - sptr reminderReq = nullptr; - switch (reminderType) { - case (static_cast(ReminderRequest::ReminderType::TIMER)): { - reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); - ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); - break; - } - case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { - reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); - ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); - break; - } - case (static_cast(ReminderRequest::ReminderType::ALARM)): { - reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); - ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); - break; - } - default: { - break; - } - } - if (reminderReq != nullptr) { - reminders.push_back(reminderReq); - } - queryResult->IsAtLastRow(isLastRow); - } - return reminders; -} - -void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::RdbStore& store, - const std::vector>& reminders) -{ - for (auto reminder : reminders) { - int64_t rowId = STATE_FAIL; - sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - if (bundleOption == nullptr) { - continue; - } - bundleOption->SetBundleName(reminder->GetBundleName()); - NativeRdb::ValuesBucket baseValues; - ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); - - store.BeginTransaction(); - // insert reminder_base - int32_t ret = store.Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - store.RollBack(); - continue; - } - - // insert reminder_alarm or reminder_calendar - NativeRdb::ValuesBucket values; - rowId = STATE_FAIL; - switch (reminder->GetReminderType()) { - case ReminderRequest::ReminderType::CALENDAR: - ReminderCalendarStrategy::AppendValuesBucket(reminder, values); - ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); - break; - case ReminderRequest::ReminderType::ALARM: - ReminderAlarmStrategy::AppendValuesBucket(reminder, values); - ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); - break; - case ReminderRequest::ReminderType::TIMER: - ReminderTimerStrategy::AppendValuesBucket(reminder, values); - ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); - break; - default: - ANSR_LOGE("Insert reminder_base operation failed, unkown type."); - ret = STATE_FAIL; - break; - } - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - store.RollBack(); - continue; - } - store.Commit(); - ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); - } -} - -void ReminderStore::ReminderStoreDataCallBack::AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, - const std::string& columnName, const std::string& columnType, const std::string& defValue) -{ - std::string sqlStr = ""; - sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType + " DEFAULT " + defValue + ";"; - ANSR_LOGD("AddRdbColum sqlStr = %{public}s", sqlStr.c_str()); - int errorCode = store.ExecuteSql(sqlStr); - if (errorCode != NativeRdb::E_OK) { - ANSR_LOGE("AddRdbColum error,errorCode is = %{public}d", errorCode); - } -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Init() -{ - ANSR_LOGD("Reminder store init."); - if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) { - int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU); - if (createDir != 0) { - ANSR_LOGE("Failed to create directory %{private}s", REMINDER_DB_DIR.c_str()); - return STATE_FAIL; - } - } +// /* +// * Copyright (c) 2022 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 "reminder_store.h" + +// #include +// #include +// #include +// #include + +// #include "fa_ability_context.h" +// #include "ans_log_wrapper.h" +// #include "reminder_table.h" +// #include "reminder_table_old.h" +// #include "reminder_request_alarm.h" +// #include "reminder_request_timer.h" +// #include "reminder_request_calendar.h" +// #include "reminder_store_strategy.h" + +// namespace OHOS { +// namespace Notification { +// namespace { +// const int32_t REMINDER_RDB_VERSION_V1 = 1; +// const int32_t REMINDER_RDB_VERSION_V2 = 2; +// const int32_t REMINDER_RDB_VERSION_V3 = 3; +// const int32_t REMINDER_RDB_VERSION_V4 = 4; +// const int32_t REMINDER_RDB_VERSION_V5 = 5; +// const int32_t REMINDER_RDB_VERSION_V6 = 6; +// const int32_t REMINDER_RDB_VERSION = 7; +// } + +// const int32_t ReminderStore::STATE_OK = 0; +// const int32_t ReminderStore::STATE_FAIL = -1; +// const std::string ReminderStore::REMINDER_DB_DIR = "/data/service/el1/public/notification/"; +// const std::string ReminderStore::REMINDER_DB_NAME = "notification.db"; + +// int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore& store) +// { +// ANSR_LOGI("Create table"); +// return CreateTable(store); +// } + +// int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade( +// NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) +// { +// ANSR_LOGI("OnUpgrade oldVersion is %{public}d, newVersion is %{public}d", oldVersion, newVersion); +// if (oldVersion < newVersion && newVersion == REMINDER_RDB_VERSION) { +// switch (oldVersion) { +// case REMINDER_RDB_VERSION_V1: +// AddRdbColum(store, ReminderTable::TABLE_NAME, "groupId", "TEXT", "''"); +// [[fallthrough]]; +// case REMINDER_RDB_VERSION_V2: +// AddRdbColum(store, ReminderTable::TABLE_NAME, "custom_ring_uri", "TEXT", "''"); +// AddRdbColum(store, ReminderTable::TABLE_NAME, "snooze_slot_id", "INT", "3"); +// [[fallthrough]]; +// case REMINDER_RDB_VERSION_V3: +// AddRdbColum(store, ReminderTable::TABLE_NAME, "creator_bundle_name", "TEXT", "''"); +// [[fallthrough]]; +// case REMINDER_RDB_VERSION_V4: +// CreateTable(store); +// CopyData(store); +// [[fallthrough]]; +// case REMINDER_RDB_VERSION_V5: +// AddRdbColum(store, ReminderBaseTable::TABLE_NAME, ReminderBaseTable::CREATOR_UID, "INT", "-1"); +// [[fallthrough]]; +// case REMINDER_RDB_VERSION_V6: +// AddRdbColum(store, ReminderCalendarTable::TABLE_NAME, +// ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, "BIGINT", "0"); +// [[fallthrough]]; +// default: +// break; +// } +// } +// store.SetVersion(newVersion); +// return NativeRdb::E_OK; +// } + +// int32_t ReminderStore::ReminderStoreDataCallBack::OnDowngrade( +// NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) +// { +// ANSR_LOGI("OnDowngrade currentVersion is %{public}d, targetVersion is %{public}d", currentVersion, targetVersion); +// if (currentVersion > targetVersion && targetVersion <= REMINDER_RDB_VERSION_V4) { +// std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTable::TABLE_NAME + " (" +// + ReminderTable::ADD_COLUMNS + ")"; +// int32_t ret = store.ExecuteSql(createSql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Create reminder table failed:%{public}d", ret); +// } +// return ret; +// } +// store.SetVersion(targetVersion); +// return NativeRdb::E_OK; +// } + +// int32_t ReminderStore::ReminderStoreDataCallBack::CreateTable(NativeRdb::RdbStore& store) +// { +// std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderBaseTable::TABLE_NAME + " (" +// + ReminderBaseTable::ADD_COLUMNS + ")"; +// int32_t ret = store.ExecuteSql(createSql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Create reminder_base table failed:%{public}d", ret); +// return ret; +// } + +// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderAlarmTable::TABLE_NAME + " (" +// + ReminderAlarmTable::ADD_COLUMNS + ")"; +// ret = store.ExecuteSql(createSql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Create reminder_alarm table failed:%{public}d", ret); +// return ret; +// } + +// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderCalendarTable::TABLE_NAME + " (" +// + ReminderCalendarTable::ADD_COLUMNS + ")"; +// ret = store.ExecuteSql(createSql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Create reminder_calendar table failed:%{public}d", ret); +// return ret; +// } + +// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTimerTable::TABLE_NAME + " (" +// + ReminderTimerTable::ADD_COLUMNS + ")"; +// ret = store.ExecuteSql(createSql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Create reminder_timer table failed:%{public}d", ret); +// return ret; +// } +// return ret; +// } + +// int32_t ReminderStore::ReminderStoreDataCallBack::CopyData(NativeRdb::RdbStore& store) +// { +// // select old data +// auto reminders = GetOldReminders(store); +// // insert new data +// if (!reminders.empty()) { +// InsertNewReminders(store, reminders); +// } +// // delete old table +// std::string sql = "DELETE FROM " + ReminderTable::TABLE_NAME; +// store.ExecuteSql(sql); +// return NativeRdb::E_OK; +// } + +// std::vector> ReminderStore::ReminderStoreDataCallBack::GetOldReminders(NativeRdb::RdbStore& store) +// { +// std::string sql = "SELECT " + ReminderTable::SELECT_COLUMNS + " FROM " +// + ReminderTable::TABLE_NAME; +// std::vector> reminders; +// std::vector whereArgs; +// auto queryResult = store.QuerySql(sql, whereArgs); +// if (queryResult == nullptr) { +// return reminders; +// } + +// bool isLastRow = false; +// queryResult->IsAtLastRow(isLastRow); +// while (!isLastRow) { +// queryResult->GoToNextRow(); +// int32_t reminderId; +// int32_t reminderType; +// GetInt32Val(queryResult, ReminderTable::REMINDER_ID, reminderId); +// GetInt32Val(queryResult, ReminderTable::REMINDER_TYPE, reminderType); + +// sptr reminderReq = nullptr; +// switch (reminderType) { +// case (static_cast(ReminderRequest::ReminderType::TIMER)): { +// reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); +// ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); +// break; +// } +// case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { +// reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); +// ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); +// break; +// } +// case (static_cast(ReminderRequest::ReminderType::ALARM)): { +// reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); +// ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); +// break; +// } +// default: { +// break; +// } +// } +// if (reminderReq != nullptr) { +// reminders.push_back(reminderReq); +// } +// queryResult->IsAtLastRow(isLastRow); +// } +// return reminders; +// } + +// void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::RdbStore& store, +// const std::vector>& reminders) +// { +// for (auto reminder : reminders) { +// int64_t rowId = STATE_FAIL; +// sptr bundleOption = new (std::nothrow) NotificationBundleOption(); +// if (bundleOption == nullptr) { +// continue; +// } +// bundleOption->SetBundleName(reminder->GetBundleName()); +// NativeRdb::ValuesBucket baseValues; +// ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); + +// store.BeginTransaction(); +// // insert reminder_base +// int32_t ret = store.Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// store.RollBack(); +// continue; +// } + +// // insert reminder_alarm or reminder_calendar +// NativeRdb::ValuesBucket values; +// rowId = STATE_FAIL; +// switch (reminder->GetReminderType()) { +// case ReminderRequest::ReminderType::CALENDAR: +// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); +// ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); +// break; +// case ReminderRequest::ReminderType::ALARM: +// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); +// ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); +// break; +// case ReminderRequest::ReminderType::TIMER: +// ReminderTimerStrategy::AppendValuesBucket(reminder, values); +// ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); +// break; +// default: +// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); +// ret = STATE_FAIL; +// break; +// } +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// store.RollBack(); +// continue; +// } +// store.Commit(); +// ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); +// } +// } + +// void ReminderStore::ReminderStoreDataCallBack::AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, +// const std::string& columnName, const std::string& columnType, const std::string& defValue) +// { +// std::string sqlStr = ""; +// sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType + " DEFAULT " + defValue + ";"; +// ANSR_LOGD("AddRdbColum sqlStr = %{public}s", sqlStr.c_str()); +// int errorCode = store.ExecuteSql(sqlStr); +// if (errorCode != NativeRdb::E_OK) { +// ANSR_LOGE("AddRdbColum error,errorCode is = %{public}d", errorCode); +// } +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Init() +// { +// ANSR_LOGD("Reminder store init."); +// if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) { +// int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU); +// if (createDir != 0) { +// ANSR_LOGE("Failed to create directory %{private}s", REMINDER_DB_DIR.c_str()); +// return STATE_FAIL; +// } +// } - ReminderTable::InitDbColumns(); - ReminderBaseTable::InitDbColumns(); - ReminderTimerTable::InitDbColumns(); - ReminderAlarmTable::InitDbColumns(); - ReminderCalendarTable::InitDbColumns(); - - std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME; - NativeRdb::RdbStoreConfig config(dbConfig); - config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); - - ReminderStoreDataCallBack rdbDataCallBack; - int32_t errCode = STATE_FAIL; - rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, REMINDER_RDB_VERSION, rdbDataCallBack, errCode); - if (rdbStore_ == nullptr) { - ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode); - return STATE_FAIL; - } - return InitData(); -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const int32_t reminderId) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - std::string condition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); - rdbStore_->BeginTransaction(); - int32_t delRows = STATE_FAIL; - std::vector whereArgs; - int32_t ret = rdbStore_->Delete(delRows, ReminderBaseTable::TABLE_NAME, condition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", - ReminderBaseTable::TABLE_NAME.c_str(), reminderId); - rdbStore_->RollBack(); - return STATE_FAIL; - } - delRows = STATE_FAIL; - ret = rdbStore_->Delete(delRows, ReminderAlarmTable::TABLE_NAME, condition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", - ReminderAlarmTable::TABLE_NAME.c_str(), reminderId); - rdbStore_->RollBack(); - return STATE_FAIL; - } - delRows = STATE_FAIL; - ret = rdbStore_->Delete(delRows, ReminderCalendarTable::TABLE_NAME, condition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", - ReminderCalendarTable::TABLE_NAME.c_str(), reminderId); - rdbStore_->RollBack(); - return STATE_FAIL; - } - delRows = STATE_FAIL; - ret = rdbStore_->Delete(delRows, ReminderTimerTable::TABLE_NAME, condition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", - ReminderTimerTable::TABLE_NAME.c_str(), reminderId); - rdbStore_->RollBack(); - return STATE_FAIL; - } - rdbStore_->Commit(); - return STATE_OK; -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& pkg, const int32_t userId, - const int32_t uid) -{ - std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME - + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg - + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - - std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " - + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - - if (uid != -1) { - assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID - + " = " + std::to_string(uid); - baseCondtion += " AND " + ReminderBaseTable::UID + " = " + std::to_string(uid); - } - assoConditon += ")"; - return Delete(baseCondtion, assoConditon); -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteUser(const int32_t userId) -{ - std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME - + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " - + std::to_string(userId) + ")"; - - std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - return Delete(baseCondtion, assoConditon); -} - -int32_t ReminderStore::UpdateOrInsert( - const sptr& reminder, const sptr& bundleOption) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - if (bundleOption == nullptr) { - ANSR_LOGE("BundleOption is null."); - return STATE_FAIL; - } - if (IsReminderExist(reminder)) { - return Update(reminder, bundleOption); - } else { - return Insert(reminder, bundleOption); - } -} - -int32_t ReminderStore::GetMaxId() -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - std::string queryCondition = "SELECT " + ReminderBaseTable::REMINDER_ID - + " FROM " + ReminderBaseTable::TABLE_NAME + " ORDER BY " - + ReminderBaseTable::REMINDER_ID + " DESC"; - auto queryResultSet = Query(queryCondition); - if (queryResultSet == nullptr) { - ANSR_LOGE("QueryResultSet is null."); - return STATE_FAIL; - } - int32_t resultNum = 0; - queryResultSet->GetRowCount(resultNum); - if (resultNum == 0) { - ANSR_LOGI("QueryResultSet is zero."); - return STATE_FAIL; - } - queryResultSet->GoToNextRow(); - int32_t maxId = STATE_FAIL; - int32_t result = queryResultSet->GetInt(0, maxId); - if (result != NativeRdb::E_OK) { - ANSR_LOGE("Query operation failed, result %{public}d.", result); - } - ANSR_LOGD("MaxId: %{public}d.", maxId); - return maxId; -} - -__attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() -{ - std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " - + ReminderBaseTable::TABLE_NAME + " WHERE " - + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " - + ReminderBaseTable::TRIGGER_TIME + " ASC"; - ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); - return GetReminders(sql); -} - -void ReminderStore::GetUInt8Val(const std::shared_ptr& resultSet, - const std::string& name, uint8_t& value) -{ - int32_t val; - GetInt32Val(resultSet, name, val); - value = static_cast(val); -} - -void ReminderStore::GetUInt16Val(const std::shared_ptr& resultSet, - const std::string& name, uint16_t& value) -{ - int32_t val; - GetInt32Val(resultSet, name, val); - value = static_cast(val); -} - -void ReminderStore::GetInt32Val(const std::shared_ptr& resultSet, - const std::string& name, int32_t& value) -{ - value = 0; - int32_t columnIndex = -1; - resultSet->GetColumnIndex(name, columnIndex); - if (columnIndex == -1) { - ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); - return; - } - resultSet->GetInt(columnIndex, value); -} - -void ReminderStore::GetInt64Val(const std::shared_ptr& resultSet, - const std::string& name, int64_t& value) -{ - value = 0; - int32_t columnIndex = -1; - resultSet->GetColumnIndex(name, columnIndex); - if (columnIndex == -1) { - ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); - return; - } - resultSet->GetLong(columnIndex, value); -} - -void ReminderStore::GetUInt64Val(const std::shared_ptr& resultSet, - const std::string& name, uint64_t& value) -{ - int64_t val; - GetInt64Val(resultSet, name, val); - value = static_cast(val); -} - -void ReminderStore::GetStringVal(const std::shared_ptr& resultSet, - const std::string& name, std::string& value) -{ - int32_t columnIndex = -1; - resultSet->GetColumnIndex(name, columnIndex); - if (columnIndex == -1) { - ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); - return; - } - resultSet->GetString(columnIndex, value); -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::InitData() -{ - ANSR_LOGD("Reminder data init."); - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - // delete all the reminders which IS_EXPIRED is true. - std::string deleteCondition = ReminderBaseTable::IS_EXPIRED + " is true"; - DeleteBase(deleteCondition); - - // set all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE - NativeRdb::ValuesBucket statusValues; - statusValues.PutInt(ReminderBaseTable::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE); - int32_t statusChangedRows = STATE_FAIL; - int32_t ret = rdbStore_->Update(statusChangedRows, ReminderBaseTable::TABLE_NAME, statusValues); - ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Init data failed."); - return STATE_FAIL; - } - return STATE_OK; -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteBase(const std::string& deleteCondition) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - int32_t deletedRows = STATE_FAIL; - std::vector whereArgs; - int32_t ret = rdbStore_->Delete(deletedRows, ReminderBaseTable::TABLE_NAME, deleteCondition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \ - "result: %{public}d.", deleteCondition.c_str(), ret); - } - ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \ - "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows); - return deletedRows; -} - -__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& baseCondition, - const std::string& assoConditon) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - rdbStore_->BeginTransaction(); - // delete reminder_calendar - std::string sql = "DELETE FROM " + ReminderCalendarTable::TABLE_NAME + " WHERE " - + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::REMINDER_ID - + " IN " + assoConditon; - int32_t ret = rdbStore_->ExecuteSql(sql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - - // delete reminder_alarm - sql = "DELETE FROM " + ReminderAlarmTable::TABLE_NAME + " WHERE " - + ReminderAlarmTable::TABLE_NAME + "." + ReminderAlarmTable::REMINDER_ID - + " IN " + assoConditon; - ret = rdbStore_->ExecuteSql(sql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - - // delete reminder_timer - sql = "DELETE FROM " + ReminderTimerTable::TABLE_NAME + " WHERE " - + ReminderTimerTable::TABLE_NAME + "." + ReminderTimerTable::REMINDER_ID - + " IN " + assoConditon; - ret = rdbStore_->ExecuteSql(sql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed", ReminderTimerTable::TABLE_NAME.c_str()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - - // delete reminder_base - sql = "DELETE FROM " + ReminderBaseTable::TABLE_NAME + " WHERE " + baseCondition; - ret = rdbStore_->ExecuteSql(sql); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - rdbStore_->Commit(); - return STATE_OK; -} - -int32_t ReminderStore::Insert( - const sptr& reminder, const sptr& bundleOption) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - int64_t rowId = STATE_FAIL; - NativeRdb::ValuesBucket baseValues; - ReminderStrategy::AppendValuesBucket(reminder, baseValues); +// ReminderTable::InitDbColumns(); +// ReminderBaseTable::InitDbColumns(); +// ReminderTimerTable::InitDbColumns(); +// ReminderAlarmTable::InitDbColumns(); +// ReminderCalendarTable::InitDbColumns(); + +// std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME; +// NativeRdb::RdbStoreConfig config(dbConfig); +// config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + +// ReminderStoreDataCallBack rdbDataCallBack; +// int32_t errCode = STATE_FAIL; +// rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, REMINDER_RDB_VERSION, rdbDataCallBack, errCode); +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode); +// return STATE_FAIL; +// } +// return InitData(); +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const int32_t reminderId) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// std::string condition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); +// rdbStore_->BeginTransaction(); +// int32_t delRows = STATE_FAIL; +// std::vector whereArgs; +// int32_t ret = rdbStore_->Delete(delRows, ReminderBaseTable::TABLE_NAME, condition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", +// ReminderBaseTable::TABLE_NAME.c_str(), reminderId); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// delRows = STATE_FAIL; +// ret = rdbStore_->Delete(delRows, ReminderAlarmTable::TABLE_NAME, condition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", +// ReminderAlarmTable::TABLE_NAME.c_str(), reminderId); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// delRows = STATE_FAIL; +// ret = rdbStore_->Delete(delRows, ReminderCalendarTable::TABLE_NAME, condition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", +// ReminderCalendarTable::TABLE_NAME.c_str(), reminderId); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// delRows = STATE_FAIL; +// ret = rdbStore_->Delete(delRows, ReminderTimerTable::TABLE_NAME, condition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", +// ReminderTimerTable::TABLE_NAME.c_str(), reminderId); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// rdbStore_->Commit(); +// return STATE_OK; +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& pkg, const int32_t userId, +// const int32_t uid) +// { +// std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME +// + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg +// + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + +// std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " +// + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + +// if (uid != -1) { +// assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID +// + " = " + std::to_string(uid); +// baseCondtion += " AND " + ReminderBaseTable::UID + " = " + std::to_string(uid); +// } +// assoConditon += ")"; +// return Delete(baseCondtion, assoConditon); +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteUser(const int32_t userId) +// { +// std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME +// + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " +// + std::to_string(userId) + ")"; + +// std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); +// return Delete(baseCondtion, assoConditon); +// } + +// int32_t ReminderStore::UpdateOrInsert( +// const sptr& reminder, const sptr& bundleOption) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// if (bundleOption == nullptr) { +// ANSR_LOGE("BundleOption is null."); +// return STATE_FAIL; +// } +// if (IsReminderExist(reminder)) { +// return Update(reminder, bundleOption); +// } else { +// return Insert(reminder, bundleOption); +// } +// } + +// int32_t ReminderStore::GetMaxId() +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// std::string queryCondition = "SELECT " + ReminderBaseTable::REMINDER_ID +// + " FROM " + ReminderBaseTable::TABLE_NAME + " ORDER BY " +// + ReminderBaseTable::REMINDER_ID + " DESC"; +// auto queryResultSet = Query(queryCondition); +// if (queryResultSet == nullptr) { +// ANSR_LOGE("QueryResultSet is null."); +// return STATE_FAIL; +// } +// int32_t resultNum = 0; +// queryResultSet->GetRowCount(resultNum); +// if (resultNum == 0) { +// ANSR_LOGI("QueryResultSet is zero."); +// return STATE_FAIL; +// } +// queryResultSet->GoToNextRow(); +// int32_t maxId = STATE_FAIL; +// int32_t result = queryResultSet->GetInt(0, maxId); +// if (result != NativeRdb::E_OK) { +// ANSR_LOGE("Query operation failed, result %{public}d.", result); +// } +// ANSR_LOGD("MaxId: %{public}d.", maxId); +// return maxId; +// } + +// __attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() +// { +// std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " +// + ReminderBaseTable::TABLE_NAME + " WHERE " +// + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " +// + ReminderBaseTable::TRIGGER_TIME + " ASC"; +// ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); +// return GetReminders(sql); +// } + +// void ReminderStore::GetUInt8Val(const std::shared_ptr& resultSet, +// const std::string& name, uint8_t& value) +// { +// int32_t val; +// GetInt32Val(resultSet, name, val); +// value = static_cast(val); +// } + +// void ReminderStore::GetUInt16Val(const std::shared_ptr& resultSet, +// const std::string& name, uint16_t& value) +// { +// int32_t val; +// GetInt32Val(resultSet, name, val); +// value = static_cast(val); +// } + +// void ReminderStore::GetInt32Val(const std::shared_ptr& resultSet, +// const std::string& name, int32_t& value) +// { +// value = 0; +// int32_t columnIndex = -1; +// resultSet->GetColumnIndex(name, columnIndex); +// if (columnIndex == -1) { +// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); +// return; +// } +// resultSet->GetInt(columnIndex, value); +// } + +// void ReminderStore::GetInt64Val(const std::shared_ptr& resultSet, +// const std::string& name, int64_t& value) +// { +// value = 0; +// int32_t columnIndex = -1; +// resultSet->GetColumnIndex(name, columnIndex); +// if (columnIndex == -1) { +// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); +// return; +// } +// resultSet->GetLong(columnIndex, value); +// } + +// void ReminderStore::GetUInt64Val(const std::shared_ptr& resultSet, +// const std::string& name, uint64_t& value) +// { +// int64_t val; +// GetInt64Val(resultSet, name, val); +// value = static_cast(val); +// } + +// void ReminderStore::GetStringVal(const std::shared_ptr& resultSet, +// const std::string& name, std::string& value) +// { +// int32_t columnIndex = -1; +// resultSet->GetColumnIndex(name, columnIndex); +// if (columnIndex == -1) { +// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); +// return; +// } +// resultSet->GetString(columnIndex, value); +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::InitData() +// { +// ANSR_LOGD("Reminder data init."); +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// // delete all the reminders which IS_EXPIRED is true. +// std::string deleteCondition = ReminderBaseTable::IS_EXPIRED + " is true"; +// DeleteBase(deleteCondition); + +// // set all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE +// NativeRdb::ValuesBucket statusValues; +// statusValues.PutInt(ReminderBaseTable::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE); +// int32_t statusChangedRows = STATE_FAIL; +// int32_t ret = rdbStore_->Update(statusChangedRows, ReminderBaseTable::TABLE_NAME, statusValues); +// ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Init data failed."); +// return STATE_FAIL; +// } +// return STATE_OK; +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteBase(const std::string& deleteCondition) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// int32_t deletedRows = STATE_FAIL; +// std::vector whereArgs; +// int32_t ret = rdbStore_->Delete(deletedRows, ReminderBaseTable::TABLE_NAME, deleteCondition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \ +// "result: %{public}d.", deleteCondition.c_str(), ret); +// } +// ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \ +// "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows); +// return deletedRows; +// } + +// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& baseCondition, +// const std::string& assoConditon) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// rdbStore_->BeginTransaction(); +// // delete reminder_calendar +// std::string sql = "DELETE FROM " + ReminderCalendarTable::TABLE_NAME + " WHERE " +// + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::REMINDER_ID +// + " IN " + assoConditon; +// int32_t ret = rdbStore_->ExecuteSql(sql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } + +// // delete reminder_alarm +// sql = "DELETE FROM " + ReminderAlarmTable::TABLE_NAME + " WHERE " +// + ReminderAlarmTable::TABLE_NAME + "." + ReminderAlarmTable::REMINDER_ID +// + " IN " + assoConditon; +// ret = rdbStore_->ExecuteSql(sql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } + +// // delete reminder_timer +// sql = "DELETE FROM " + ReminderTimerTable::TABLE_NAME + " WHERE " +// + ReminderTimerTable::TABLE_NAME + "." + ReminderTimerTable::REMINDER_ID +// + " IN " + assoConditon; +// ret = rdbStore_->ExecuteSql(sql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed", ReminderTimerTable::TABLE_NAME.c_str()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } + +// // delete reminder_base +// sql = "DELETE FROM " + ReminderBaseTable::TABLE_NAME + " WHERE " + baseCondition; +// ret = rdbStore_->ExecuteSql(sql); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// rdbStore_->Commit(); +// return STATE_OK; +// } + +// int32_t ReminderStore::Insert( +// const sptr& reminder, const sptr& bundleOption) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// int64_t rowId = STATE_FAIL; +// NativeRdb::ValuesBucket baseValues; +// ReminderStrategy::AppendValuesBucket(reminder, baseValues); - rdbStore_->BeginTransaction(); - // insert reminder_base - int32_t ret = rdbStore_->Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - - // insert reminder_alarm or reminder_calendar - NativeRdb::ValuesBucket values; - rowId = STATE_FAIL; - switch (reminder->GetReminderType()) { - case ReminderRequest::ReminderType::CALENDAR: { - ReminderCalendarStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); - break; - } - case ReminderRequest::ReminderType::ALARM: { - ReminderAlarmStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); - break; - } - case ReminderRequest::ReminderType::TIMER: { - ReminderTimerStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); - break; - } - default: { - ANSR_LOGE("Insert reminder_base operation failed, unkown type."); - ret = STATE_FAIL; - break; - } - } - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - rdbStore_->Commit(); - ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); - return STATE_OK; -} - -int32_t ReminderStore::Update( - const sptr& reminder, const sptr& bundleOption) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return STATE_FAIL; - } - int32_t rowId = STATE_FAIL; - NativeRdb::ValuesBucket baseValues; - ReminderStrategy::AppendValuesBucket(reminder, baseValues); - - std::string updateCondition = ReminderBaseTable::REMINDER_ID - + " = " + std::to_string(reminder->GetReminderId()); - - rdbStore_->BeginTransaction(); - // update reminder_base - std::vector whereArgs; - int32_t ret = rdbStore_->Update(rowId, ReminderBaseTable::TABLE_NAME, baseValues, updateCondition, whereArgs); - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Update reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - - // update reminder_alarm or reminder_calendar - NativeRdb::ValuesBucket values; - rowId = STATE_FAIL; - switch (reminder->GetReminderType()) { - case ReminderRequest::ReminderType::CALENDAR: - ReminderCalendarStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); - break; - case ReminderRequest::ReminderType::ALARM: - ReminderAlarmStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); - break; - case ReminderRequest::ReminderType::TIMER: - ReminderTimerStrategy::AppendValuesBucket(reminder, values); - ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); - break; - default: - ANSR_LOGE("Insert reminder_base operation failed, unkown type."); - ret = STATE_FAIL; - break; - } - if (ret != NativeRdb::E_OK) { - ANSR_LOGE("Update operation failed, result: %{public}d, reminderId=%{public}d.", - ret, reminder->GetReminderId()); - rdbStore_->RollBack(); - return STATE_FAIL; - } - rdbStore_->Commit(); - ANSR_LOGD("Update successfully, reminderId=%{public}d.", reminder->GetReminderId()); - return STATE_OK; -} - -bool ReminderStore::IsReminderExist(const sptr& reminder) -{ - NativeRdb::AbsRdbPredicates absRdbPredicates(ReminderBaseTable::TABLE_NAME); - absRdbPredicates.EqualTo(ReminderBaseTable::REMINDER_ID, std::to_string(reminder->GetReminderId())); - auto queryResultSet = rdbStore_->Query(absRdbPredicates, std::vector()); - if (queryResultSet == nullptr) { - ANSR_LOGE("QueryResultSet is null."); - return false; - } - int32_t resultNum; - queryResultSet->GetRowCount(resultNum); - return resultNum != 0; -} - -std::vector> ReminderStore::GetReminders(const std::string& queryCondition) -{ - std::vector> reminders; - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return reminders; - } - auto queryResultSet = Query(queryCondition); - if (queryResultSet == nullptr) { - return reminders; - } - bool isAtLastRow = false; - int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); - while (ret == NativeRdb::E_OK && !isAtLastRow) { - queryResultSet->GoToNextRow(); - sptr reminder = BuildReminder(queryResultSet); - if (reminder != nullptr) { - reminders.push_back(reminder); - } - ret = queryResultSet->IsAtLastRow(isAtLastRow); - } - ANSR_LOGD("Size=%{public}zu", reminders.size()); - return reminders; -} - -sptr ReminderStore::BuildReminder(const std::shared_ptr& resultBase) -{ - int32_t reminderId; - int32_t reminderType; - GetInt32Val(resultBase, ReminderBaseTable::REMINDER_ID, reminderId); - GetInt32Val(resultBase, ReminderBaseTable::REMINDER_TYPE, reminderType); - - sptr reminder = nullptr; - std::shared_ptr resultSet; - switch (reminderType) { - case (static_cast(ReminderRequest::ReminderType::TIMER)): { - reminder = new (std::nothrow) ReminderRequestTimer(reminderId); - resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); - ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); - break; - } - case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { - reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); - resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); - ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); - break; - } - case (static_cast(ReminderRequest::ReminderType::ALARM)): { - reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); - resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); - ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); - break; - } - default: { - ANSR_LOGE("ReminderType from database is error, reminderType %{public}d.", reminderType); - break; - } - } - if (reminder == nullptr) { - ANSR_LOGW("BuildReminder fail."); - } - return reminder; -} - -std::shared_ptr ReminderStore::Query(const std::string& tableName, const std::string& colums, - const int32_t reminderId) -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return nullptr; - } - std::string queryCondition = "SELECT " + colums + " FROM " + tableName - + " WHERE " + ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); - auto queryResultSet = Query(queryCondition); - if (queryResultSet == nullptr) { - return nullptr; - } - int32_t resultNum = 0; - queryResultSet->GetRowCount(resultNum); - if (resultNum == 0) { - return nullptr; - } - queryResultSet->GoToNextRow(); - return queryResultSet; -} - -std::shared_ptr ReminderStore::Query(const std::string& queryCondition) const -{ - if (rdbStore_ == nullptr) { - ANSR_LOGE("Rdb store is not initialized."); - return nullptr; - } - std::vector whereArgs; - return rdbStore_->QuerySql(queryCondition, whereArgs); -} -} // namespace Notification -} // namespace OHOS +// rdbStore_->BeginTransaction(); +// // insert reminder_base +// int32_t ret = rdbStore_->Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } + +// // insert reminder_alarm or reminder_calendar +// NativeRdb::ValuesBucket values; +// rowId = STATE_FAIL; +// switch (reminder->GetReminderType()) { +// case ReminderRequest::ReminderType::CALENDAR: { +// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); +// break; +// } +// case ReminderRequest::ReminderType::ALARM: { +// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); +// break; +// } +// case ReminderRequest::ReminderType::TIMER: { +// ReminderTimerStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); +// break; +// } +// default: { +// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); +// ret = STATE_FAIL; +// break; +// } +// } +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// rdbStore_->Commit(); +// ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); +// return STATE_OK; +// } + +// int32_t ReminderStore::Update( +// const sptr& reminder, const sptr& bundleOption) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return STATE_FAIL; +// } +// int32_t rowId = STATE_FAIL; +// NativeRdb::ValuesBucket baseValues; +// ReminderStrategy::AppendValuesBucket(reminder, baseValues); + +// std::string updateCondition = ReminderBaseTable::REMINDER_ID +// + " = " + std::to_string(reminder->GetReminderId()); + +// rdbStore_->BeginTransaction(); +// // update reminder_base +// std::vector whereArgs; +// int32_t ret = rdbStore_->Update(rowId, ReminderBaseTable::TABLE_NAME, baseValues, updateCondition, whereArgs); +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Update reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } + +// // update reminder_alarm or reminder_calendar +// NativeRdb::ValuesBucket values; +// rowId = STATE_FAIL; +// switch (reminder->GetReminderType()) { +// case ReminderRequest::ReminderType::CALENDAR: +// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); +// break; +// case ReminderRequest::ReminderType::ALARM: +// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); +// break; +// case ReminderRequest::ReminderType::TIMER: +// ReminderTimerStrategy::AppendValuesBucket(reminder, values); +// ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); +// break; +// default: +// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); +// ret = STATE_FAIL; +// break; +// } +// if (ret != NativeRdb::E_OK) { +// ANSR_LOGE("Update operation failed, result: %{public}d, reminderId=%{public}d.", +// ret, reminder->GetReminderId()); +// rdbStore_->RollBack(); +// return STATE_FAIL; +// } +// rdbStore_->Commit(); +// ANSR_LOGD("Update successfully, reminderId=%{public}d.", reminder->GetReminderId()); +// return STATE_OK; +// } + +// bool ReminderStore::IsReminderExist(const sptr& reminder) +// { +// NativeRdb::AbsRdbPredicates absRdbPredicates(ReminderBaseTable::TABLE_NAME); +// absRdbPredicates.EqualTo(ReminderBaseTable::REMINDER_ID, std::to_string(reminder->GetReminderId())); +// auto queryResultSet = rdbStore_->Query(absRdbPredicates, std::vector()); +// if (queryResultSet == nullptr) { +// ANSR_LOGE("QueryResultSet is null."); +// return false; +// } +// int32_t resultNum; +// queryResultSet->GetRowCount(resultNum); +// return resultNum != 0; +// } + +// std::vector> ReminderStore::GetReminders(const std::string& queryCondition) +// { +// std::vector> reminders; +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return reminders; +// } +// auto queryResultSet = Query(queryCondition); +// if (queryResultSet == nullptr) { +// return reminders; +// } +// bool isAtLastRow = false; +// int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); +// while (ret == NativeRdb::E_OK && !isAtLastRow) { +// queryResultSet->GoToNextRow(); +// sptr reminder = BuildReminder(queryResultSet); +// if (reminder != nullptr) { +// reminders.push_back(reminder); +// } +// ret = queryResultSet->IsAtLastRow(isAtLastRow); +// } +// ANSR_LOGD("Size=%{public}zu", reminders.size()); +// return reminders; +// } + +// sptr ReminderStore::BuildReminder(const std::shared_ptr& resultBase) +// { +// int32_t reminderId; +// int32_t reminderType; +// GetInt32Val(resultBase, ReminderBaseTable::REMINDER_ID, reminderId); +// GetInt32Val(resultBase, ReminderBaseTable::REMINDER_TYPE, reminderType); + +// sptr reminder = nullptr; +// std::shared_ptr resultSet; +// switch (reminderType) { +// case (static_cast(ReminderRequest::ReminderType::TIMER)): { +// reminder = new (std::nothrow) ReminderRequestTimer(reminderId); +// resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); +// ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); +// break; +// } +// case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { +// reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); +// resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); +// ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); +// break; +// } +// case (static_cast(ReminderRequest::ReminderType::ALARM)): { +// reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); +// resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); +// ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); +// break; +// } +// default: { +// ANSR_LOGE("ReminderType from database is error, reminderType %{public}d.", reminderType); +// break; +// } +// } +// if (reminder == nullptr) { +// ANSR_LOGW("BuildReminder fail."); +// } +// return reminder; +// } + +// std::shared_ptr ReminderStore::Query(const std::string& tableName, const std::string& colums, +// const int32_t reminderId) +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return nullptr; +// } +// std::string queryCondition = "SELECT " + colums + " FROM " + tableName +// + " WHERE " + ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); +// auto queryResultSet = Query(queryCondition); +// if (queryResultSet == nullptr) { +// return nullptr; +// } +// int32_t resultNum = 0; +// queryResultSet->GetRowCount(resultNum); +// if (resultNum == 0) { +// return nullptr; +// } +// queryResultSet->GoToNextRow(); +// return queryResultSet; +// } + +// std::shared_ptr ReminderStore::Query(const std::string& queryCondition) const +// { +// if (rdbStore_ == nullptr) { +// ANSR_LOGE("Rdb store is not initialized."); +// return nullptr; +// } +// std::vector whereArgs; +// return rdbStore_->QuerySql(queryCondition, whereArgs); +// } +// } // namespace Notification +// } // namespace OHOS diff --git a/services/ans/src/reminder_table.cpp b/services/ans/src/reminder_table.cpp index 5e85b7289..bd0096ab8 100644 --- a/services/ans/src/reminder_table.cpp +++ b/services/ans/src/reminder_table.cpp @@ -1,178 +1,178 @@ -/* - * Copyright (c) 2023 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. - */ +// /* +// * Copyright (c) 2023 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 "reminder_table.h" +// #include "reminder_table.h" -namespace OHOS { -namespace Notification { -// reminder base table -const std::string ReminderBaseTable::TABLE_NAME = "reminder_base"; -const std::string ReminderBaseTable::REMINDER_ID = "reminder_id"; -const std::string ReminderBaseTable::PACKAGE_NAME = "package_name"; -const std::string ReminderBaseTable::USER_ID = "user_id"; -const std::string ReminderBaseTable::UID = "uid"; -const std::string ReminderBaseTable::SYSTEM_APP = "system_app"; -const std::string ReminderBaseTable::REMINDER_TYPE = "reminder_type"; -const std::string ReminderBaseTable::REMINDER_TIME = "reminder_time"; -const std::string ReminderBaseTable::TRIGGER_TIME = "trigger_time"; -const std::string ReminderBaseTable::TIME_INTERVAL = "time_interval"; -const std::string ReminderBaseTable::SNOOZE_TIMES = "snooze_times"; -const std::string ReminderBaseTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; -const std::string ReminderBaseTable::RING_DURATION = "ring_duration"; -const std::string ReminderBaseTable::IS_EXPIRED = "is_expired"; -const std::string ReminderBaseTable::STATE = "state"; -const std::string ReminderBaseTable::ACTION_BUTTON_INFO = "button_info"; -const std::string ReminderBaseTable::CUSTOM_BUTTON_URI = "custom_button_uri"; -const std::string ReminderBaseTable::SLOT_ID = "slot_id"; -const std::string ReminderBaseTable::SNOOZE_SLOT_ID = "snooze_slot_id"; -const std::string ReminderBaseTable::NOTIFICATION_ID = "notification_id"; -const std::string ReminderBaseTable::TITLE = "title"; -const std::string ReminderBaseTable::CONTENT = "content"; -const std::string ReminderBaseTable::SNOOZE_CONTENT = "snooze_content"; -const std::string ReminderBaseTable::EXPIRED_CONTENT = "expired_content"; -const std::string ReminderBaseTable::WANT_AGENT = "want_agent"; -const std::string ReminderBaseTable::MAX_SCREEN_WANT_AGENT = "max_screen_want_agent"; -const std::string ReminderBaseTable::TAP_DISMISSED = "tap_dismissed"; -const std::string ReminderBaseTable::AUTO_DELETED_TIME = "auto_deleted_time"; -const std::string ReminderBaseTable::GROUP_ID = "group_id"; -const std::string ReminderBaseTable::CUSTOM_RING_URI = "custom_ring_uri"; -const std::string ReminderBaseTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; -const std::string ReminderBaseTable::CREATOR_UID = "creator_uid"; +// namespace OHOS { +// namespace Notification { +// // reminder base table +// const std::string ReminderBaseTable::TABLE_NAME = "reminder_base"; +// const std::string ReminderBaseTable::REMINDER_ID = "reminder_id"; +// const std::string ReminderBaseTable::PACKAGE_NAME = "package_name"; +// const std::string ReminderBaseTable::USER_ID = "user_id"; +// const std::string ReminderBaseTable::UID = "uid"; +// const std::string ReminderBaseTable::SYSTEM_APP = "system_app"; +// const std::string ReminderBaseTable::REMINDER_TYPE = "reminder_type"; +// const std::string ReminderBaseTable::REMINDER_TIME = "reminder_time"; +// const std::string ReminderBaseTable::TRIGGER_TIME = "trigger_time"; +// const std::string ReminderBaseTable::TIME_INTERVAL = "time_interval"; +// const std::string ReminderBaseTable::SNOOZE_TIMES = "snooze_times"; +// const std::string ReminderBaseTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; +// const std::string ReminderBaseTable::RING_DURATION = "ring_duration"; +// const std::string ReminderBaseTable::IS_EXPIRED = "is_expired"; +// const std::string ReminderBaseTable::STATE = "state"; +// const std::string ReminderBaseTable::ACTION_BUTTON_INFO = "button_info"; +// const std::string ReminderBaseTable::CUSTOM_BUTTON_URI = "custom_button_uri"; +// const std::string ReminderBaseTable::SLOT_ID = "slot_id"; +// const std::string ReminderBaseTable::SNOOZE_SLOT_ID = "snooze_slot_id"; +// const std::string ReminderBaseTable::NOTIFICATION_ID = "notification_id"; +// const std::string ReminderBaseTable::TITLE = "title"; +// const std::string ReminderBaseTable::CONTENT = "content"; +// const std::string ReminderBaseTable::SNOOZE_CONTENT = "snooze_content"; +// const std::string ReminderBaseTable::EXPIRED_CONTENT = "expired_content"; +// const std::string ReminderBaseTable::WANT_AGENT = "want_agent"; +// const std::string ReminderBaseTable::MAX_SCREEN_WANT_AGENT = "max_screen_want_agent"; +// const std::string ReminderBaseTable::TAP_DISMISSED = "tap_dismissed"; +// const std::string ReminderBaseTable::AUTO_DELETED_TIME = "auto_deleted_time"; +// const std::string ReminderBaseTable::GROUP_ID = "group_id"; +// const std::string ReminderBaseTable::CUSTOM_RING_URI = "custom_ring_uri"; +// const std::string ReminderBaseTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; +// const std::string ReminderBaseTable::CREATOR_UID = "creator_uid"; -// reminder alarm table -const std::string ReminderAlarmTable::TABLE_NAME = "reminder_alarm"; -const std::string ReminderAlarmTable::REMINDER_ID = "reminder_id"; -const std::string ReminderAlarmTable::ALARM_HOUR = "alarm_hour"; -const std::string ReminderAlarmTable::ALARM_MINUTE = "alarm_minute"; -const std::string ReminderAlarmTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +// // reminder alarm table +// const std::string ReminderAlarmTable::TABLE_NAME = "reminder_alarm"; +// const std::string ReminderAlarmTable::REMINDER_ID = "reminder_id"; +// const std::string ReminderAlarmTable::ALARM_HOUR = "alarm_hour"; +// const std::string ReminderAlarmTable::ALARM_MINUTE = "alarm_minute"; +// const std::string ReminderAlarmTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; -// reminder calendar table -const std::string ReminderCalendarTable::TABLE_NAME = "reminder_calendar"; -const std::string ReminderCalendarTable::REMINDER_ID = "reminder_id"; -const std::string ReminderCalendarTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; -const std::string ReminderCalendarTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; -const std::string ReminderCalendarTable::FIRST_DESIGNATE_DAY = "first_designate_day"; -const std::string ReminderCalendarTable::CALENDAR_DATE_TIME = "calendar_date_time"; -const std::string ReminderCalendarTable::CALENDAR_END_DATE_TIME = "calendar_end_date_time"; -const std::string ReminderCalendarTable::REPEAT_DAYS = "repeat_days"; -const std::string ReminderCalendarTable::REPEAT_MONTHS = "repeat_months"; -const std::string ReminderCalendarTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; -const std::string ReminderCalendarTable::RRULE_WANT_AGENT = "rrule_want_agent"; -const std::string ReminderCalendarTable::EXCLUDE_DATES = "exclude_dates"; -const std::string ReminderCalendarTable::CALENDAR_LAST_DATE_TIME = "calendar_last_date_time"; +// // reminder calendar table +// const std::string ReminderCalendarTable::TABLE_NAME = "reminder_calendar"; +// const std::string ReminderCalendarTable::REMINDER_ID = "reminder_id"; +// const std::string ReminderCalendarTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; +// const std::string ReminderCalendarTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; +// const std::string ReminderCalendarTable::FIRST_DESIGNATE_DAY = "first_designate_day"; +// const std::string ReminderCalendarTable::CALENDAR_DATE_TIME = "calendar_date_time"; +// const std::string ReminderCalendarTable::CALENDAR_END_DATE_TIME = "calendar_end_date_time"; +// const std::string ReminderCalendarTable::REPEAT_DAYS = "repeat_days"; +// const std::string ReminderCalendarTable::REPEAT_MONTHS = "repeat_months"; +// const std::string ReminderCalendarTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +// const std::string ReminderCalendarTable::RRULE_WANT_AGENT = "rrule_want_agent"; +// const std::string ReminderCalendarTable::EXCLUDE_DATES = "exclude_dates"; +// const std::string ReminderCalendarTable::CALENDAR_LAST_DATE_TIME = "calendar_last_date_time"; -// reminder timer table -const std::string ReminderTimerTable::TABLE_NAME = "reminder_timer"; -const std::string ReminderTimerTable::REMINDER_ID = "reminder_id"; -const std::string ReminderTimerTable::TRIGGER_SECOND = "trigger_second"; -const std::string ReminderTimerTable::START_DATE_TIME = "start_date_time"; -const std::string ReminderTimerTable::END_DATE_TIME = "end_date_time"; +// // reminder timer table +// const std::string ReminderTimerTable::TABLE_NAME = "reminder_timer"; +// const std::string ReminderTimerTable::REMINDER_ID = "reminder_id"; +// const std::string ReminderTimerTable::TRIGGER_SECOND = "trigger_second"; +// const std::string ReminderTimerTable::START_DATE_TIME = "start_date_time"; +// const std::string ReminderTimerTable::END_DATE_TIME = "end_date_time"; -std::string ReminderBaseTable::ADD_COLUMNS = ""; -std::string ReminderBaseTable::SELECT_COLUMNS = ""; +// std::string ReminderBaseTable::ADD_COLUMNS = ""; +// std::string ReminderBaseTable::SELECT_COLUMNS = ""; -std::string ReminderAlarmTable::ADD_COLUMNS = ""; -std::string ReminderAlarmTable::SELECT_COLUMNS = ""; +// std::string ReminderAlarmTable::ADD_COLUMNS = ""; +// std::string ReminderAlarmTable::SELECT_COLUMNS = ""; -std::string ReminderCalendarTable::ADD_COLUMNS = ""; -std::string ReminderCalendarTable::SELECT_COLUMNS = ""; +// std::string ReminderCalendarTable::ADD_COLUMNS = ""; +// std::string ReminderCalendarTable::SELECT_COLUMNS = ""; -std::string ReminderTimerTable::ADD_COLUMNS = ""; -std::string ReminderTimerTable::SELECT_COLUMNS = ""; +// std::string ReminderTimerTable::ADD_COLUMNS = ""; +// std::string ReminderTimerTable::SELECT_COLUMNS = ""; -static inline void AddColumn(const std::string& name, const std::string& type, std::string& sqlOfColumns, - std::string& columns) -{ - columns.append(name).append(","); - sqlOfColumns.append(name).append(" "); - sqlOfColumns.append(type).append(", "); -} +// static inline void AddColumn(const std::string& name, const std::string& type, std::string& sqlOfColumns, +// std::string& columns) +// { +// columns.append(name).append(","); +// sqlOfColumns.append(name).append(" "); +// sqlOfColumns.append(type).append(", "); +// } -static inline void AddColumnEnd(const std::string& name, const std::string& type, std::string& sqlOfColumns, - std::string& columns) -{ - columns.append(name); - sqlOfColumns.append(name).append(" "); - sqlOfColumns.append(type); -} +// static inline void AddColumnEnd(const std::string& name, const std::string& type, std::string& sqlOfColumns, +// std::string& columns) +// { +// columns.append(name); +// sqlOfColumns.append(name).append(" "); +// sqlOfColumns.append(type); +// } -void ReminderBaseTable::InitDbColumns() -{ - AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(PACKAGE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(USER_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(SYSTEM_APP, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(REMINDER_TYPE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(REMINDER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(RING_DURATION, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(IS_EXPIRED, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(STATE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(ACTION_BUTTON_INFO, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CUSTOM_BUTTON_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(SNOOZE_SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(NOTIFICATION_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(TITLE, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(SNOOZE_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(EXPIRED_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(MAX_SCREEN_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(TAP_DISMISSED, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(AUTO_DELETED_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(GROUP_ID, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CUSTOM_RING_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CREATOR_BUNDLE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumnEnd(CREATOR_UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -} +// void ReminderBaseTable::InitDbColumns() +// { +// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(PACKAGE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(USER_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(SYSTEM_APP, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(REMINDER_TYPE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(REMINDER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(RING_DURATION, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(IS_EXPIRED, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(STATE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(ACTION_BUTTON_INFO, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CUSTOM_BUTTON_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(SNOOZE_SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(NOTIFICATION_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(TITLE, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(SNOOZE_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(EXPIRED_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(MAX_SCREEN_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(TAP_DISMISSED, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(AUTO_DELETED_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(GROUP_ID, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CUSTOM_RING_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CREATOR_BUNDLE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumnEnd(CREATOR_UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// } -void ReminderAlarmTable::InitDbColumns() -{ - AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(ALARM_HOUR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(ALARM_MINUTE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumnEnd(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); -} +// void ReminderAlarmTable::InitDbColumns() +// { +// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(ALARM_HOUR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(ALARM_MINUTE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumnEnd(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// } -void ReminderCalendarTable::InitDbColumns() -{ - AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(FIRST_DESIGNATE_YEAR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(FIRST_DESIGNATE_MONTH, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(FIRST_DESIGNATE_DAY, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CALENDAR_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(CALENDAR_END_DATE_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(REPEAT_DAYS, "INT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(REPEAT_MONTHS, "INT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(RRULE_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(EXCLUDE_DATES, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); - AddColumnEnd(CALENDAR_LAST_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -} +// void ReminderCalendarTable::InitDbColumns() +// { +// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(FIRST_DESIGNATE_YEAR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(FIRST_DESIGNATE_MONTH, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(FIRST_DESIGNATE_DAY, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CALENDAR_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(CALENDAR_END_DATE_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(REPEAT_DAYS, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(REPEAT_MONTHS, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(RRULE_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(EXCLUDE_DATES, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumnEnd(CALENDAR_LAST_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// } -void ReminderTimerTable::InitDbColumns() -{ - AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(TRIGGER_SECOND, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumn(START_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); - AddColumnEnd(END_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -} -} -} +// void ReminderTimerTable::InitDbColumns() +// { +// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(TRIGGER_SECOND, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumn(START_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// AddColumnEnd(END_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +// } +// } +// } diff --git a/services/ans/src/reminder_table_old.cpp b/services/ans/src/reminder_table_old.cpp index 1def1b8bc..bbcac59c4 100644 --- a/services/ans/src/reminder_table_old.cpp +++ b/services/ans/src/reminder_table_old.cpp @@ -1,157 +1,157 @@ -/* - * Copyright (c) 2024 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. - */ +// /* +// * Copyright (c) 2024 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 "reminder_table_old.h" +// #include "reminder_table_old.h" -namespace OHOS { -namespace Notification { -// Reminder Table Basic Columns. -const std::string ReminderTable::TABLE_NAME = "reminder"; -const std::string ReminderTable::REMINDER_ID = "reminder_id"; -const std::string ReminderTable::PKG_NAME = "package_name"; -const std::string ReminderTable::USER_ID = "user_id"; -const std::string ReminderTable::UID = "uid"; -const std::string ReminderTable::SYS_APP = "system_app"; -const std::string ReminderTable::APP_LABEL = "app_label"; -const std::string ReminderTable::REMINDER_TYPE = "reminder_type"; -const std::string ReminderTable::REMINDER_TIME = "reminder_time"; -const std::string ReminderTable::TRIGGER_TIME = "trigger_time"; -const std::string ReminderTable::RTC_TRIGGER_TIME = "rtc_trigger_time"; -const std::string ReminderTable::TIME_INTERVAL = "time_interval"; -const std::string ReminderTable::SNOOZE_TIMES = "snooze_times"; -const std::string ReminderTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; -const std::string ReminderTable::RING_DURATION = "ring_duration"; -const std::string ReminderTable::IS_EXPIRED = "is_expired"; -const std::string ReminderTable::IS_ACTIVE = "is_active"; -const std::string ReminderTable::STATE = "state"; -const std::string ReminderTable::ZONE_ID = "zone_id"; -const std::string ReminderTable::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout"; -const std::string ReminderTable::ACTION_BUTTON_INFO = "button_info"; -const std::string ReminderTable::CUSTOM_BUTTON_URI = "custom_button_uri"; -const std::string ReminderTable::SLOT_ID = "slot_id"; -const std::string ReminderTable::SNOOZE_SLOT_ID = "snooze_slot_id"; -const std::string ReminderTable::NOTIFICATION_ID = "notification_id"; -const std::string ReminderTable::TITLE = "title"; -const std::string ReminderTable::CONTENT = "content"; -const std::string ReminderTable::SNOOZE_CONTENT = "snooze_content"; -const std::string ReminderTable::EXPIRED_CONTENT = "expired_content"; -const std::string ReminderTable::AGENT = "agent"; -const std::string ReminderTable::MAX_SCREEN_AGENT = "maxScreen_agent"; -const std::string ReminderTable::TAP_DISMISSED = "tapDismissed"; -const std::string ReminderTable::AUTO_DELETED_TIME = "autoDeletedTime"; -const std::string ReminderTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; -const std::string ReminderTable::GROUP_ID = "groupId"; -const std::string ReminderTable::CUSTOM_RING_URI = "custom_ring_uri"; -const std::string ReminderTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; +// namespace OHOS { +// namespace Notification { +// // Reminder Table Basic Columns. +// const std::string ReminderTable::TABLE_NAME = "reminder"; +// const std::string ReminderTable::REMINDER_ID = "reminder_id"; +// const std::string ReminderTable::PKG_NAME = "package_name"; +// const std::string ReminderTable::USER_ID = "user_id"; +// const std::string ReminderTable::UID = "uid"; +// const std::string ReminderTable::SYS_APP = "system_app"; +// const std::string ReminderTable::APP_LABEL = "app_label"; +// const std::string ReminderTable::REMINDER_TYPE = "reminder_type"; +// const std::string ReminderTable::REMINDER_TIME = "reminder_time"; +// const std::string ReminderTable::TRIGGER_TIME = "trigger_time"; +// const std::string ReminderTable::RTC_TRIGGER_TIME = "rtc_trigger_time"; +// const std::string ReminderTable::TIME_INTERVAL = "time_interval"; +// const std::string ReminderTable::SNOOZE_TIMES = "snooze_times"; +// const std::string ReminderTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; +// const std::string ReminderTable::RING_DURATION = "ring_duration"; +// const std::string ReminderTable::IS_EXPIRED = "is_expired"; +// const std::string ReminderTable::IS_ACTIVE = "is_active"; +// const std::string ReminderTable::STATE = "state"; +// const std::string ReminderTable::ZONE_ID = "zone_id"; +// const std::string ReminderTable::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout"; +// const std::string ReminderTable::ACTION_BUTTON_INFO = "button_info"; +// const std::string ReminderTable::CUSTOM_BUTTON_URI = "custom_button_uri"; +// const std::string ReminderTable::SLOT_ID = "slot_id"; +// const std::string ReminderTable::SNOOZE_SLOT_ID = "snooze_slot_id"; +// const std::string ReminderTable::NOTIFICATION_ID = "notification_id"; +// const std::string ReminderTable::TITLE = "title"; +// const std::string ReminderTable::CONTENT = "content"; +// const std::string ReminderTable::SNOOZE_CONTENT = "snooze_content"; +// const std::string ReminderTable::EXPIRED_CONTENT = "expired_content"; +// const std::string ReminderTable::AGENT = "agent"; +// const std::string ReminderTable::MAX_SCREEN_AGENT = "maxScreen_agent"; +// const std::string ReminderTable::TAP_DISMISSED = "tapDismissed"; +// const std::string ReminderTable::AUTO_DELETED_TIME = "autoDeletedTime"; +// const std::string ReminderTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +// const std::string ReminderTable::GROUP_ID = "groupId"; +// const std::string ReminderTable::CUSTOM_RING_URI = "custom_ring_uri"; +// const std::string ReminderTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; -// Reminder Table Calendar Columns. -const std::string ReminderTable::REPEAT_DAYS = "repeat_days"; -const std::string ReminderTable::REPEAT_MONTHS = "repeat_months"; -const std::string ReminderTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; -const std::string ReminderTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; -const std::string ReminderTable::FIRST_DESIGNATE_DAY = "first_designate_day"; -const std::string ReminderTable::CALENDAR_YEAR = "calendar_year"; -const std::string ReminderTable::CALENDAR_MONTH = "calendar_month"; -const std::string ReminderTable::CALENDAR_DAY = "calendar_day"; -const std::string ReminderTable::CALENDAR_HOUR = "calendar_hour"; -const std::string ReminderTable::CALENDAR_MINUTE = "calendar_minute"; +// // Reminder Table Calendar Columns. +// const std::string ReminderTable::REPEAT_DAYS = "repeat_days"; +// const std::string ReminderTable::REPEAT_MONTHS = "repeat_months"; +// const std::string ReminderTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; +// const std::string ReminderTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; +// const std::string ReminderTable::FIRST_DESIGNATE_DAY = "first_designate_day"; +// const std::string ReminderTable::CALENDAR_YEAR = "calendar_year"; +// const std::string ReminderTable::CALENDAR_MONTH = "calendar_month"; +// const std::string ReminderTable::CALENDAR_DAY = "calendar_day"; +// const std::string ReminderTable::CALENDAR_HOUR = "calendar_hour"; +// const std::string ReminderTable::CALENDAR_MINUTE = "calendar_minute"; -// Reminder Table Alarm Columns. -const std::string ReminderTable::ALARM_HOUR = "alarm_hour"; -const std::string ReminderTable::ALARM_MINUTE = "alarm_minute"; +// // Reminder Table Alarm Columns. +// const std::string ReminderTable::ALARM_HOUR = "alarm_hour"; +// const std::string ReminderTable::ALARM_MINUTE = "alarm_minute"; -std::string ReminderTable::ADD_COLUMNS = ""; -std::string ReminderTable::SELECT_COLUMNS = ""; +// std::string ReminderTable::ADD_COLUMNS = ""; +// std::string ReminderTable::SELECT_COLUMNS = ""; -void ReminderTable::InitDbColumns() -{ - InitBasicColumns(); - InitCalendarColumns(); - InitAlarmColumns(); -} +// void ReminderTable::InitDbColumns() +// { +// InitBasicColumns(); +// InitCalendarColumns(); +// InitAlarmColumns(); +// } -void ReminderTable::InitBasicColumns() -{ - AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY"); - AddColumn(PKG_NAME, "TEXT NOT NULL"); - AddColumn(USER_ID, "INT NOT NULL"); - AddColumn(UID, "INT NOT NULL"); - AddColumn(SYS_APP, "TEXT NOT NULL"); - AddColumn(APP_LABEL, "TEXT"); - AddColumn(REMINDER_TYPE, "INT NOT NULL"); - AddColumn(REMINDER_TIME, "BIGINT NOT NULL"); - AddColumn(TRIGGER_TIME, "BIGINT NOT NULL"); - AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL"); - AddColumn(TIME_INTERVAL, "BIGINT NOT NULL"); - AddColumn(SNOOZE_TIMES, "INT NOT NULL"); - AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL"); - AddColumn(RING_DURATION, "BIGINT NOT NULL"); - AddColumn(IS_EXPIRED, "TEXT NOT NULL"); - AddColumn(IS_ACTIVE, "TEXT NOT NULL"); - AddColumn(STATE, "INT NOT NULL"); - AddColumn(ZONE_ID, "TEXT"); - AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT"); - AddColumn(ACTION_BUTTON_INFO, "TEXT"); - AddColumn(CUSTOM_BUTTON_URI, "TEXT"); - AddColumn(SLOT_ID, "INT"); - AddColumn(SNOOZE_SLOT_ID, "INT"); - AddColumn(NOTIFICATION_ID, "INT NOT NULL"); - AddColumn(TITLE, "TEXT"); - AddColumn(CONTENT, "TEXT"); - AddColumn(SNOOZE_CONTENT, "TEXT"); - AddColumn(EXPIRED_CONTENT, "TEXT"); - AddColumn(AGENT, "TEXT"); - AddColumn(MAX_SCREEN_AGENT, "TEXT"); - AddColumn(TAP_DISMISSED, "TEXT"); - AddColumn(AUTO_DELETED_TIME, "BIGINT"); - AddColumn(REPEAT_DAYS_OF_WEEK, "INT"); - AddColumn(GROUP_ID, "TEXT"); - AddColumn(CUSTOM_RING_URI, "TEXT"); - AddColumn(CREATOR_BUNDLE_NAME, "TEXT", false); -} +// void ReminderTable::InitBasicColumns() +// { +// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY"); +// AddColumn(PKG_NAME, "TEXT NOT NULL"); +// AddColumn(USER_ID, "INT NOT NULL"); +// AddColumn(UID, "INT NOT NULL"); +// AddColumn(SYS_APP, "TEXT NOT NULL"); +// AddColumn(APP_LABEL, "TEXT"); +// AddColumn(REMINDER_TYPE, "INT NOT NULL"); +// AddColumn(REMINDER_TIME, "BIGINT NOT NULL"); +// AddColumn(TRIGGER_TIME, "BIGINT NOT NULL"); +// AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL"); +// AddColumn(TIME_INTERVAL, "BIGINT NOT NULL"); +// AddColumn(SNOOZE_TIMES, "INT NOT NULL"); +// AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL"); +// AddColumn(RING_DURATION, "BIGINT NOT NULL"); +// AddColumn(IS_EXPIRED, "TEXT NOT NULL"); +// AddColumn(IS_ACTIVE, "TEXT NOT NULL"); +// AddColumn(STATE, "INT NOT NULL"); +// AddColumn(ZONE_ID, "TEXT"); +// AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT"); +// AddColumn(ACTION_BUTTON_INFO, "TEXT"); +// AddColumn(CUSTOM_BUTTON_URI, "TEXT"); +// AddColumn(SLOT_ID, "INT"); +// AddColumn(SNOOZE_SLOT_ID, "INT"); +// AddColumn(NOTIFICATION_ID, "INT NOT NULL"); +// AddColumn(TITLE, "TEXT"); +// AddColumn(CONTENT, "TEXT"); +// AddColumn(SNOOZE_CONTENT, "TEXT"); +// AddColumn(EXPIRED_CONTENT, "TEXT"); +// AddColumn(AGENT, "TEXT"); +// AddColumn(MAX_SCREEN_AGENT, "TEXT"); +// AddColumn(TAP_DISMISSED, "TEXT"); +// AddColumn(AUTO_DELETED_TIME, "BIGINT"); +// AddColumn(REPEAT_DAYS_OF_WEEK, "INT"); +// AddColumn(GROUP_ID, "TEXT"); +// AddColumn(CUSTOM_RING_URI, "TEXT"); +// AddColumn(CREATOR_BUNDLE_NAME, "TEXT", false); +// } -void ReminderTable::InitCalendarColumns() -{ - AddColumn(REPEAT_DAYS, "INT"); - AddColumn(REPEAT_MONTHS, "INT"); - AddColumn(FIRST_DESIGNATE_YEAR, "INT"); - AddColumn(FIRST_DESIGNATE_MONTH, "INT"); - AddColumn(FIRST_DESIGNATE_DAY, "INT"); - AddColumn(CALENDAR_YEAR, "INT"); - AddColumn(CALENDAR_MONTH, "INT"); - AddColumn(CALENDAR_DAY, "INT"); - AddColumn(CALENDAR_HOUR, "INT"); - AddColumn(CALENDAR_MINUTE, "INT"); -} +// void ReminderTable::InitCalendarColumns() +// { +// AddColumn(REPEAT_DAYS, "INT"); +// AddColumn(REPEAT_MONTHS, "INT"); +// AddColumn(FIRST_DESIGNATE_YEAR, "INT"); +// AddColumn(FIRST_DESIGNATE_MONTH, "INT"); +// AddColumn(FIRST_DESIGNATE_DAY, "INT"); +// AddColumn(CALENDAR_YEAR, "INT"); +// AddColumn(CALENDAR_MONTH, "INT"); +// AddColumn(CALENDAR_DAY, "INT"); +// AddColumn(CALENDAR_HOUR, "INT"); +// AddColumn(CALENDAR_MINUTE, "INT"); +// } -void ReminderTable::InitAlarmColumns() -{ - AddColumn(ALARM_HOUR, "INT"); - AddColumn(ALARM_MINUTE, "INT", true); -} +// void ReminderTable::InitAlarmColumns() +// { +// AddColumn(ALARM_HOUR, "INT"); +// AddColumn(ALARM_MINUTE, "INT", true); +// } -void ReminderTable ::AddColumn( - const std::string& name, const std::string& type, bool isEnd) -{ - if (!isEnd) { - SELECT_COLUMNS.append(name).append(","); - ADD_COLUMNS += name + " " + type + ", "; - } else { - SELECT_COLUMNS.append(name); - ADD_COLUMNS += name + " " + type; - } -} -} -} +// void ReminderTable ::AddColumn( +// const std::string& name, const std::string& type, bool isEnd) +// { +// if (!isEnd) { +// SELECT_COLUMNS.append(name).append(","); +// ADD_COLUMNS += name + " " + type + ", "; +// } else { +// SELECT_COLUMNS.append(name); +// ADD_COLUMNS += name + " " + type; +// } +// } +// } +// } diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp index d11fa91f5..13360671d 100644 --- a/services/ans/src/reminder_timer_info.cpp +++ b/services/ans/src/reminder_timer_info.cpp @@ -1,51 +1,51 @@ -/* - * Copyright (c) 2021-2022 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. - */ +// /* +// * Copyright (c) 2021-2022 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 "reminder_timer_info.h" +// #include "reminder_timer_info.h" -#include "ans_log_wrapper.h" -#include "common_event_manager.h" -#include "reminder_request.h" +// #include "ans_log_wrapper.h" +// #include "common_event_manager.h" +// #include "reminder_request.h" -using namespace OHOS::EventFwk; -using namespace OHOS::HiviewDFX; -namespace OHOS { -namespace Notification { -void ReminderTimerInfo::SetType(const int &_type) -{ - type = _type; -} +// using namespace OHOS::EventFwk; +// using namespace OHOS::HiviewDFX; +// namespace OHOS { +// namespace Notification { +// void ReminderTimerInfo::SetType(const int &_type) +// { +// type = _type; +// } -void ReminderTimerInfo::SetRepeat(bool _repeat) -{ - repeat = _repeat; -} +// void ReminderTimerInfo::SetRepeat(bool _repeat) +// { +// repeat = _repeat; +// } -void ReminderTimerInfo::SetInterval(const uint64_t &_interval) -{ - interval = _interval; -} +// void ReminderTimerInfo::SetInterval(const uint64_t &_interval) +// { +// interval = _interval; +// } -void ReminderTimerInfo::SetWantAgent(std::shared_ptr _wantAgent) -{ - wantAgent = _wantAgent; -} +// void ReminderTimerInfo::SetWantAgent(std::shared_ptr _wantAgent) +// { +// wantAgent = _wantAgent; +// } -void ReminderTimerInfo::OnTrigger() -{ - ANSR_LOGI("Timing is arrivelled."); -} -} -} +// void ReminderTimerInfo::OnTrigger() +// { +// ANSR_LOGI("Timing is arrivelled."); +// } +// } +// } diff --git a/services/reminder/BUILD.gn b/services/reminder/BUILD.gn new file mode 100644 index 000000000..ba726c81f --- /dev/null +++ b/services/reminder/BUILD.gn @@ -0,0 +1,295 @@ +# Copyright (c) 2021-2024 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/distributed_notification_service/notification.gni") +import("//build/ohos.gni") + +group("reminder_service") { + deps = [ ":libreminder" ] +} + +config("public_reminder_config") { + include_dirs = [ + "${services_path}/reminder/include", + "${core_path}/include", + ] +} + +ohos_source_set("reminder_service_sources") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + + cflags = [ + "-fno-math-errno", + "-fno-unroll-loops", + "-fmerge-all-constants", + "-fno-ident", + "-Oz", + "-flto", + "-ffunction-sections", + "-fdata-sections", + ] + + include_dirs = [ "${services_path}/reminder/include" ] + + defines = [] + + sources = [ + "src/reminder_notification_inline.cpp", + "src/reminder_access_token_helper.cpp", + "src/reminder_os_account_manager_helper.cpp", + "src/reminder_bundle_manager_helper.cpp", + "src/reminder_service.cpp", + "src/reminder_service_ability.cpp", + "src/reminder_config_change_observer.cpp", + "src/reminder_data_manager.cpp", + "src/reminder_data_manager_inner.cpp", + "src/reminder_event_manager.cpp", + "src/reminder_store.cpp", + "src/reminder_store_strategy.cpp", + "src/reminder_table.cpp", + "src/reminder_table_old.cpp", + "src/reminder_timer_info.cpp", + ] + + deps = [ + "${frameworks_module_reminder_path}:reminder_innerkits", + "${frameworks_module_ans_path}:ans_innerkits" + ] + + if (is_double_framework) { + cflags += [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + if (notification_smart_reminder_supported) { + defines += [ "NOTIFICATION_SMART_REMINDER_SUPPORTED" ] + } + + external_deps = [ + "ability_base:configuration", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:appkit_native", + "ability_runtime:dataobs_manager", + "ability_runtime:extension_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "data_share:datashare_common", + "data_share:datashare_consumer", + "data_share:datashare_permission", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "i18n:intl_util", + "image_framework:image_native", + "init:libbegetutil", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "resource_management:global_resmgr", + "time_service:time_client", + ] + external_deps += component_external_deps + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (hisysevent_usage) { + cflags += [ "-DHAS_HISYSEVENT_PART" ] + external_deps += [ "hisysevent:libhisysevent" ] + } + + if (standby_enable) { + external_deps += [ "device_standby:standby_innerkits" ] + defines += [ "DEVICE_STANDBY_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + if (ans_hitrace_usage) { + external_deps += [ "hitrace:hitrace_meter" ] + defines += [ "HITRACE_METER_ENABLE" ] + } + + if (ans_config_policy_enable) { + external_deps += [ "config_policy:configpolicy_util" ] + defines += [ "CONFIG_POLICY_ENABLE" ] + } + + if (screenlock_mgr_enable) { + external_deps += [ "screenlock_mgr:screenlock_client" ] + defines += [ "SCREENLOCK_MGR_ENABLE" ] + } + + if (distributed_notification_service_feature_summary) { + defines += [ "ENABLE_ANS_EXT_WRAPPER" ] + } + + if (telephony_cust) { + defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] + } + + if (distributed_notification_service_feature_disable_fa_model) { + defines += [ "ANS_DISABLE_FA_MODEL" ] + } + + if (is_emulator) { + defines += [ "IS_EMULATOR" ] + } + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_shared_library("libreminder") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" + + shlib_type = "sa" + cflags = [ + "-fno-math-errno", + "-fno-unroll-loops", + "-fmerge-all-constants", + "-fno-ident", + "-Oz", + "-flto", + "-ffunction-sections", + "-fdata-sections", + ] + sources = [] + + configs = [ ":public_reminder_config" ] + + defines = [] + + if (is_double_framework) { + cflags += [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + deps = [ + "${services_path}/reminder:reminder_service_sources", + "//third_party/icu/icu4c:shared_icuuc", + "//third_party/libxml2:libxml2", + ] + + if (distributed_notification_supported) { + deps += [ "${services_path}/distributed:libans_distributed" ] + } + + external_deps = [ + "ability_base:configuration", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:appkit_native", + "ability_runtime:dataobs_manager", + "ability_runtime:extension_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "data_share:datashare_common", + "data_share:datashare_consumer", + "data_share:datashare_permission", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "i18n:intl_util", + "image_framework:image_native", + "init:libbegetutil", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "resource_management:global_resmgr", + "time_service:time_client", + ] + external_deps += component_external_deps + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + } + + if (hisysevent_usage) { + cflags += [ "-DHAS_HISYSEVENT_PART" ] + external_deps += [ "hisysevent:libhisysevent" ] + } + + if (standby_enable) { + external_deps += [ "device_standby:standby_innerkits" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + } + + if (ans_hitrace_usage) { + external_deps += [ "hitrace:hitrace_meter" ] + } + + if (ans_config_policy_enable) { + external_deps += [ "config_policy:configpolicy_util" ] + } + + if (screenlock_mgr_enable) { + external_deps += [ "screenlock_mgr:screenlock_client" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_prebuilt_etc("ans.para") { + source = "etc/ans.para" + relative_install_dir = "param" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_prebuilt_etc("ans.para.dac") { + source = "etc/ans.para.dac" + relative_install_dir = "param" + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} diff --git a/services/reminder/include/reminder_access_token_helper.h b/services/reminder/include/reminder_access_token_helper.h new file mode 100644 index 000000000..e2359d28e --- /dev/null +++ b/services/reminder/include/reminder_access_token_helper.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H + +#include +#include "refbase.h" + +#include "accesstoken_kit.h" + +namespace OHOS { +namespace Notification { +class ReminderAccessTokenHelper { +public: + static bool IsSystemApp(); + static bool VerifyNativeToken(const OHOS::Security::AccessToken::AccessTokenID &callerToken); +private: +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_bundle_manager_helper.h b/services/reminder/include/reminder_bundle_manager_helper.h new file mode 100644 index 000000000..af57b395b --- /dev/null +++ b/services/reminder/include/reminder_bundle_manager_helper.h @@ -0,0 +1,85 @@ +/* + * Copyright (c) 2021-2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H + +#include +#include +#include + +#include "bundle_mgr_interface.h" +#include "ipc_skeleton.h" +#include "iremote_object.h" +#include "refbase.h" +#include "remote_death_recipient.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +class ReminderBundleManagerHelper : public DelayedSingleton { +public: + /** + * @brief Obtains the bundle name base on the specified uid. + * + * @param uid Indicates the specified uid. + * @return Returns the bundle name. + */ + std::string GetBundleNameByUid(int32_t uid); + + /** + * @brief Obtains the default uid. + * + * @param bundle Indicates the bundle name. + * @param userId Indicates the user id. + * @return Returns the uid. + */ + int32_t GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId); + + /** + * @brief Obtains bundle info by bundle name. + * + * @param bundleName Indicates the bundle name. + * @param flag Indicates the bundle flag. + * @param bundleInfo Indicates the bundle info. + * @param userId Indicates the user id. + * @return Returns the check result. + */ + bool GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + int32_t userId, AppExecFwk::BundleInfo &bundleInfo); + + /** + * @brief Obtains the app index by uid. + * @param uid Indicates uid. + * @return Returns the query result if succeed, retrun 0(main index) otherwise. + */ + int32_t GetAppIndexByUid(const int32_t uid); + +private: + void Connect(); + void Disconnect(); + + void OnRemoteDied(const wptr &object); + +private: + sptr bundleMgr_ = nullptr; + std::mutex connectionMutex_; + sptr deathRecipient_ = nullptr; + + DECLARE_DELAYED_SINGLETON(ReminderBundleManagerHelper) +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H diff --git a/services/reminder/include/reminder_config_change_observer.h b/services/reminder/include/reminder_config_change_observer.h new file mode 100644 index 000000000..c7981b0b8 --- /dev/null +++ b/services/reminder/include/reminder_config_change_observer.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H + +#include "configuration_observer_stub.h" + +namespace OHOS { +namespace Notification { + +/** + * @brief Listening system language change, when the system language changes, + * notify ReminderDataManager. +*/ +class ReminderConfigChangeObserver final : public AppExecFwk::ConfigurationObserverStub { +public: + ReminderConfigChangeObserver() = default; + ~ReminderConfigChangeObserver() = default; + +public: + void OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) override; + +private: + std::string languageInfo_; +}; +} // namespace Notification +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h new file mode 100644 index 000000000..a52c4d84b --- /dev/null +++ b/services/reminder/include/reminder_data_manager.h @@ -0,0 +1,752 @@ +/* + * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H + +#include +#include + +#include "reminder_service.h" +#include "ans_inner_errors.h" +#ifdef PLAYER_FRAMEWORK_ENABLE +#include "player.h" +#endif +#include "ffrt.h" +#include "app_mgr_client.h" +#include "reminder_request.h" +#include "reminder_store.h" +#include "reminder_timer_info.h" +#include "reminder_config_change_observer.h" +#include "datashare_predicates.h" +#include "datashare_values_bucket.h" +#include "app_mgr_interface.h" +#include "time_service_client.h" + +namespace OHOS { +namespace Notification { +class ReminderDataManager final { +public: + ReminderDataManager() + { + Init(false); + }; + ~ReminderDataManager(); + + ReminderDataManager(ReminderDataManager &other) = delete; + ReminderDataManager& operator = (const ReminderDataManager &other) = delete; + + /** + * @brief Cancels all the reminders relative to the bundle option. + * + * @param packageName Indicates the package name. + * @param userId Indicates the user id which the bundle belong to. + * @param uid Indicates the uid which the bundle belong to. + * @return ERR_OK if success, else not. + */ + ErrCode CancelAllReminders(const int32_t userId, const int32_t uid); + + /** + * @brief Cancels the target reminder relative to the reminder id and bundle option. + * + * @param reminderId Indicates the reminder id. + * @param bundleOption Indicates the bundle option. + * @return ERR_OK if success, else not. + */ + ErrCode CancelReminder(const int32_t &reminderId, const int32_t callingUid); + + sptr CheckExcludeDateParam(const int32_t reminderId, + const int32_t callingUid); + + /** + * @brief Add exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param date exclude date + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddExcludeDate(const int32_t reminderId, const int64_t date, + const int32_t callingUid); + + /** + * @brief Clear exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DelExcludeDates(const int32_t reminderId, const int32_t callingUid); + + /** + * @brief Get exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param dates exclude dates + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetExcludeDates(const int32_t reminderId, const int32_t callingUid, + std::vector& dates); + + /** + * @brief Close the target reminder which is showing on panel. + * This is manul operation by user: 1.Click close button of the reminder, 2.remove reminder notification. + * + * @param want Want information that transferred when the event trigger by user. + * @param cancelNotification Indicates whether need to cancel notification or not. + */ + void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification); + + /** + * Dump all the reminders information. + * + * @return reminders informations. + */ + std::string Dump() const; + + /** + * Obtains the single instance. + * + * @return Single instance of ReminderDataManager. + */ + static std::shared_ptr GetInstance(); + static std::shared_ptr InitInstance(); + // fengyang static std::shared_ptr InitInstance( + // const sptr &advancedNotificationService); + + /** + * Obtains all the valid reminders (which are not expired) relative to the bundle option. + * + * @param bundleOption Indicates the bundle option. + * @param[out] reminders return the valid reminders. + */ + void GetValidReminders( + const int32_t callingUid, std::vector &reminders); + + /** + * @brief Inits and recovery data from database. + * + * @param isFromBootComplete Indicates the init is called when boot completed. + */ + void Init(bool isFromBootComplete); + + void InitUserId(); + + /** + * @brief Check all reminders, Whether an immediate reminder is needed; + * whether a pull up service extension is required. + * Use when powering on and changing the system time. + */ + void CheckReminderTime(std::vector>& immediatelyReminders, + std::vector>& extensionReminders); + + /** + * @brief Register configuration observer, the listening system language is changed. + */ + bool RegisterConfigurationObserver(); + + void OnUserRemove(const int32_t& userId); + + /** + * @brief Bundle manager service start. + */ + void OnBundleMgrServiceStart(); + + /** + * @brief Ability manager service start. + */ + void OnAbilityMgrServiceStart(); + + void OnUserSwitch(const int32_t& userId); + + /** + * @brief Triggered when third party application died. + * + * @param bundleOption Indicates the bundleOption of third party application. + */ + void OnProcessDiedLocked(const int32_t callingUid); + + /** + * Publishs a scheduled reminder. + * + * @param reminder Indicates the reminder. + * @param bundleOption Indicates bundle option the reminder belongs to. + * @return ERR_OK if success, else not. + */ + ErrCode PublishReminder(const sptr &reminder, + const int32_t callingUid); + + /** + * @brief Refresh all reminders when date/time or timeZone of device changed by user. + * + * @param type Indicates it is triggered by dateTime change or timeZone change. + */ + void RefreshRemindersDueToSysTimeChange(uint8_t type); + + /** + * @brief Indicates the single instance of ans that used to execute operations in service. + * + * @param Indicates the single instance of ans notification service. + */ + // fengyang void SetService(sptr &advancedNotificationService); + + bool ShouldAlert(const sptr &reminder) const; + + /** + * @brief Show the reminder. + * + * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. + * @param want Which contains the given reminder. + */ + void ShowActiveReminder(const EventFwk::Want &want); + + /** + * @brief Snooze the reminder by manual. + * 1) Snooze the trigger time to the next. + * 2) Update the notification(Update notification lable/content...; Stop audio player and vibrator) + * 3) Show the notification dialog in the SystemUI + * 4) Start a new reminder, which is recent one now. + * + * @param want Which contains the given reminder. + */ + void SnoozeReminder(const OHOS::EventFwk::Want &want); + + /** + * Starts the recent reminder timing. + */ + void StartRecentReminder(); + + /** + * Handle custom button click event. + */ + void HandleCustomButtonClick(const OHOS::EventFwk::Want &want); + + /** + * Handle click notification, no button. + */ + void ClickReminder(const OHOS::EventFwk::Want &want); + + /** + * Handle auto delete time + */ + void HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, const int64_t autoDeletedTime); + + /** + * @brief Terminate the alerting reminder. + * + * 1. Stop sound and vibrate. + * 2. Stop the alerting timer. + * 3. Update the reminder state. + * 4. Update the display content of the notification. + * + * @param want Which contains the given reminder. + */ + void TerminateAlerting(const OHOS::EventFwk::Want &want); + + /** + * @brief Update reminders based on the system language. + * + * Update action button title. + */ + void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); + + /** + * @brief System language change + */ + void OnLanguageChanged(); + + /** + * @brief When OnRemoveSystemAbility occurs. + */ + void OnRemoveAppMgr(); + + /** + * @brief Whether the device is ready or not. + */ + bool IsSystemReady(); + + static constexpr uint8_t TIME_ZONE_CHANGE = 0; + static constexpr uint8_t DATE_TIME_CHANGE = 1; + +private: + enum class TimerType : uint8_t { + TRIGGER_TIMER, + ALERTING_TIMER + }; + + static std::shared_ptr serviceQueue_; + /** + * Add default slot to the reminder if no slot set by user. + * + * @param reminder Indicates the reminder. + */ + void AddDefaultSlotIfNeeded(sptr &reminder); + + /** + * Add reminder to showed reminder vector. + * + * @param reminder Indicates the showed reminder. + */ + void AddToShowedReminders(const sptr &reminder); + + void CancelAllReminders(const int32_t userId); + + /** + * @brief Check the update conditions. + * + * @param reminder Indicates the showed reminder. + * @param actionButtonType Button type of the button. + * @param actionButtonMap Button map. + * @return True if check successful. + */ + bool CheckUpdateConditions(const sptr &reminder, + const ReminderRequest::ActionButtonType &actionButtonType, + const std::map &actionButtonMap); + + /** + * @brief update app database. + * + * @param reminder Indicates the showed reminder. + * @param actionButtonType Button type of the button. + */ + void UpdateAppDatabase(const sptr &reminder, + const ReminderRequest::ActionButtonType &actionButtonType); + + /** + * @brief generate Predicates for dataShare. + * + * @param predicates find fields from database. + * @param equalToVector Split from dataShareUpdate->equaleTo. + */ + void GenPredicates(DataShare::DataSharePredicates &predicates, const std::vector &equalToVector); + + /** + * @brief generate ValuesBucket for dataShare. + * + * @param valuesBucket update fields at database. + * @param valuesBucketVector Split from dataShareUpdate->valuesBucket. + */ + void GenValuesBucket(DataShare::DataShareValuesBucket &valuesBucket, + const std::vector &valuesBucketVector); + + /** + * @brief get bundleName from uri. + * + * @param dstBundleName The package name required to update the database. + * @param uri Database address. + */ + void GenDstBundleName(std::string &dstBundleName, const std::string &uri) const; + + /** + * @brief get custom ring uri. + * + * @param reminder Indicates the reminder. + * @return Returns the uri of ring tone. + */ + std::string GetCustomRingUri(const sptr &reminder); + + /** + * @brief Cancels all the reminders of the target bundle or user. + * + * @param packageName Indicates the packageName need to cancel. + * @param userId Indicates the userId to cancel. + */ + void CancelRemindersImplLocked(const int32_t userId, const int32_t uid, bool isCancelAllPackage = false); + + /** + * @brief Close reminders with the same group id. + * + * @param oldReminderId Indicates the reminderId that are currently bing showed. + * @param packageName Indicates the packageName need to cancel. + * @param groupId Indicates the group id to cancel. + */ + void CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, + const std::string &groupId); + + /** + * Cancels the notification relative to the reminder. + * + * @param reminder Indicates the reminder. + */ + void CancelNotification(const sptr &reminder) const; + + /** + * Check whether the number limit of reminders if exceeded. + * + * @param bundleName Indicates the target bundle. + * @return true if number limit is exceeded. + */ + bool CheckReminderLimitExceededLocked(const int32_t callingUid, + const sptr& reminder) const; + void CloseReminder(const sptr &reminder, bool cancelNotification); + + /** + * Create a information for timer, such as timer type, repeat policy, interval and want agent. + * + * @param type Indicates the timer type. + * @param reminderRequest Indicates the reminder request. + * @return pointer of ReminderTimerInfo. + */ + std::shared_ptr CreateTimerInfo(TimerType type, + const sptr &reminderRequest) const; + void InitTimerInfo(std::shared_ptr &timerInfo, + const sptr &reminderRequest, TimerType reminderType) const; + + void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; + + std::string GetSoundUri(const sptr &reminder); + + /** + * Find the reminder from reminderVector_ by reminder id. + * + * @param reminderId Indicates the reminder id. + * @return pointer of reminder request or nullptr. + */ + sptr FindReminderRequestLocked(const int32_t &reminderId); + + /** + * Obtains the recent reminder which is not expired from reminder vector. + * + * The expired reminders will be removed from reminderVector_ and notificationBundleOptionMap_. + * + * @return pointer of reminder object. + */ + sptr GetRecentReminderLocked(); + + void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); + void HandleExtensionReminder(std::vector> &extensionReminders); + + /** + * @brief Refresh the reminder due to date/time or timeZone change by user. + * + * @param type Indicates it is date/time change or timeZone change. + * @param reminder Indicates the target reminder. + * @return sptr Returns the target reminder if it is need to show immediately, otherwise nullptr. + */ + sptr HandleRefreshReminder(const uint8_t &type, sptr &reminder); + + /** + * @brief Handles all the reminders that have the same notification id and belong to same application + * with the current reminder. Unset the state of "showing". + * + * @param reminder Indicates the current reminder. + */ + void HandleSameNotificationIdShowing(const sptr reminder); + + bool HandleSysTimeChange(const sptr reminder) const; + + /** + * @brief Judge the two reminders is belong to the same application or not. + * + * @param bundleOption Indicates the bundleOption of first reminder. + * @param other Indicates the bundleOption of second reminder. + * @return true if the two reminders belong to the same application. + */ + bool IsBelongToSameApp(const int32_t uidSrc, const int32_t uidTar) const; + bool CheckIsSameApp(const sptr &reminder, const int32_t callingUid) const; + + /** + * @brief Judges whether the reminder is matched with the bundleOption or userId. + * + * @param reminder Indicates the target reminder. + * @param packageName Indicates the package name. + * @param userId Indicates the user id. + * @param uid Indicates the uid. + * @return true If the reminder is matched with the bundleOption or userId. + */ + bool IsMatched(const sptr &reminder, const int32_t userId, const int32_t uid, + bool isCancelAllPackage = false) const; + + /** + * @brief Judges whether the reminder is matched with the packageName or groupId. + * + * @param reminder Indicates the target reminder. + * @param packageName Indicates the package name. + * @param groupId Indicates the group id. + * @return true If the reminder is matched with the packageName and groupId. + */ + bool IsMatchedForGroupIdAndPkgName(const sptr &reminder, const std::string &packageName, + const std::string &groupId) const; + + bool IsAllowedNotify(const sptr &reminder) const; + + bool IsReminderAgentReady() const; + + void LoadReminderFromDb(); + + void PlaySoundAndVibrationLocked(const sptr &reminder); + void PlaySoundAndVibration(const sptr &reminder); + void StopSoundAndVibrationLocked(const sptr &reminder); + void StopSoundAndVibration(const sptr &reminder); + + /** + * Remove from showed reminder vector. + * + * @param reminder Indicates the reminder need to remove. + */ + void RemoveFromShowedReminders(const sptr &reminder); + + /** + * @brief Refresh the all reminders due to date/time or timeZone change by user. + * + * @param type Indicates it is date/time change or timeZone change. + * @return reminders that need to show immediately. + */ + void RefreshRemindersLocked(uint8_t type, std::vector>& immediatelyReminders, + std::vector>& extensionReminders); + + /** + * Removes the reminder. + * 1. removes the reminder from reminderVector_ and notificationBundleOptionMap_. + * 2. cancels the notification. + * + * @param reminderId Indicates the reminder id. + */ + void RemoveReminderLocked(const int32_t &reminderId); + + /** + * Resets timer status. + * 1. Sets timerId_ or timerIdAlerting_ with 0. + * 2. Sets activeReminderId_ or alertingReminderId with -1. + * + * @param type Indicates the timer type. + */ + void ResetStates(TimerType type); + + void SetActiveReminder(const sptr &reminder); + void SetAlertingReminder(const sptr &reminder); + void ShowActiveReminderExtendLocked(sptr &reminder); + static bool StartExtensionAbility(const sptr &reminder); + static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); + void InitServiceHandler(); + /** + * @brief Show the reminder on SystemUI. + * + * @param reminder Indicates the reminder to show. + * @param isNeedToPlaySound Indicates whether need to play sound. + * @param isNeedToStartNext Indicates whether need to start next reminder. + * @param isSysTimeChanged Indicates whether it is triggerred as system time changed by user. + * @param needScheduleTimeout Indicates whether need to control the ring duration. + */ + void ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, + const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout); + + void SnoozeReminderImpl(sptr &reminder); + + /** + * Starts timing actually. + * + * @param reminderRequest Indicates the reminder. + * @param type Indicates the timer type. + */ + void StartTimerLocked(const sptr &reminderRequest, TimerType type); + void StartTimer(const sptr &reminderRequest, TimerType type); + + uint64_t HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, + const sptr &timer); + + uint64_t HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, + const sptr &timer, time_t now); + + /** + * @brief Stop the alerting timer and update reminder information. + * + * 1. Stop sound and vibrate. + * 2. Stop the alerting timer. + * + * @param reminder Indicates the target reminder. + */ + void StopAlertingReminder(const sptr &reminder); + + /** + * Stops timing. + * + * @param type Indicates the timer type. + */ + void StopTimer(TimerType type); + void StopTimerLocked(TimerType type); + + /** + * @brief Terminate the alerting reminder. + * + * 1. Stop sound and vibrate. + * 2. Stop the alerting timer. + * 3. Update the reminder state. + * 4. Update the display content of the notification. + * + * @param reminder Indicates the reminder. + * @param reason Indicates the description information. + */ + void TerminateAlerting(const sptr &reminder, const std::string &reason); + void TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder); + + /** + * @brief Assign unique reminder id and save reminder in memory. + * + * @param reminder Indicates a reminder. + * @param bundleOption Indicates bundle option relative to the reminder. + */ + void UpdateAndSaveReminderLocked( + const sptr &reminder, const int32_t callingUid); + + void UpdateNotification(const sptr &reminder, bool isSnooze); + + static bool cmp(sptr &reminderRequest, sptr &other); + + /** + * @brief Connect App Manager to get the current foreground application. + */ + bool ConnectAppMgr(); + + /** + * @brief Check need to notify the application, if the current foreground application + * is the creator of the reminder, notify the application of the reminder status + * change; otherwise, do not noitfy. + * + * @param reminder Indicates a reminder. + * @param buttonType The type of button clicked by the user. + */ + void CheckNeedNotifyStatus(const sptr &reminder, + const ReminderRequest::ActionButtonType buttonType); + + std::string GetFullPath(const std::string& path); + + /** + * @brief Check action button data share permission + */ + bool IsActionButtonDataShareValid(const sptr& reminder, + const uint32_t callerTokenId); + + /** + * @brief Get resource manager by bundlename and uid. + */ + std::shared_ptr GetResourceMgr(const std::string& bundleName, + const int32_t uid); + + /** + * @brief Get custom ring file desc. + * lock by resourceMutex_ in function + */ + bool GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc); + + /** + * @brief Close custom ring file desc. + * lock by resourceMutex_ in function + */ + void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); + + /** + * @brief report event to dfx + */ + void ReportSysEvent(const sptr& reminder); + + /** + * Single instance. + */ + static std::shared_ptr REMINDER_DATA_MANAGER; + + /** + * Used for multi-thread synchronise. + */ + static std::mutex MUTEX; + static std::mutex SHOW_MUTEX; + static std::mutex ALERT_MUTEX; + static std::mutex TIMER_MUTEX; + static std::mutex ACTIVE_MUTEX; + + /** + * Max number of reminders limit for the whole system. + */ + static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYSTEM = 12000; + + /** + * Max number of reminders limit for one system application. + */ + static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYS_APP = 10000; + + /** + * Max number of reminders limit for one application. + */ + static constexpr int16_t MAX_NUM_REMINDER_LIMIT_APP = 30; + + bool isReminderAgentReady_ = false; + + /** + * Vector used to record all the reminders in system. + */ + std::vector> reminderVector_; + + /** + * Vector used to record all the reminders which has been shown on panel. + */ + std::vector> showedReminderVector_; + + /** + * This timer is used to control the triggerTime of next reminder. + */ + uint64_t timerId_ {0}; + + /** + * This timer is used to control the ringDuration of the alerting reminder. + */ + std::atomic timerIdAlerting_ {0}; + + /** + * Indicates the active reminder that timing is taking effect. + */ + std::atomic activeReminderId_ = -1; + sptr activeReminder_ = nullptr; + + /** + * Indicates the reminder which is playing sound or vibration. + */ + std::atomic alertingReminderId_ = -1; + sptr alertingReminder_ = nullptr; +#ifdef PLAYER_FRAMEWORK_ENABLE + std::shared_ptr soundPlayer_ = nullptr; + std::mutex resourceMutex_; // for soundResource_ + std::shared_ptr soundResource_ = nullptr; +#endif + /** + * Indicates the total count of reminders in system. + */ + int16_t totalCount_ {0}; + int currentUserId_ {0}; + // fengyang sptr advancedNotificationService_ = nullptr; + std::shared_ptr store_ = nullptr; + + /** + * Indicates config change observer for language + */ + sptr configChangeObserver_ = nullptr; + + /** + * Indicates app mananger for get foreground application + */ + std::mutex appMgrMutex_; + sptr appMgrProxy_ = nullptr; + + /** + * async queue + */ + std::shared_ptr queue_ = nullptr; + + /** + * Sa ready flag + */ + std::atomic saReadyFlag_{ 0 }; +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H diff --git a/services/reminder/include/reminder_event_manager.h b/services/reminder/include/reminder_event_manager.h new file mode 100644 index 000000000..654bcca95 --- /dev/null +++ b/services/reminder/include/reminder_event_manager.h @@ -0,0 +1,102 @@ +/* + * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H + +#include "reminder_service.h" +#include "common_event_subscriber.h" +#include "reminder_data_manager.h" +#include "system_ability_status_change_stub.h" +#include "notification_subscriber.h" + +#include + +namespace OHOS { +namespace Notification { +class ReminderEventManager { +public: + explicit ReminderEventManager(std::shared_ptr &reminderDataManager); + virtual ~ReminderEventManager() {}; + ReminderEventManager(ReminderEventManager &other) = delete; + ReminderEventManager& operator = (const ReminderEventManager &other) = delete; + +private: + void init(std::shared_ptr &reminderDataManager) const; + void SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const; + +class ReminderEventSubscriber : public EventFwk::CommonEventSubscriber { +public: + ReminderEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, + std::shared_ptr &reminderDataManager); + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + +private: + sptr GetBundleOption(const OHOS::EventFwk::Want &want) const; + int32_t GetUid(const OHOS::EventFwk::Want &want) const; + void HandlePackageRemove(const EventFwk::Want &want) const; + void HandleProcessDied(const EventFwk::Want &want) const; + std::shared_ptr reminderDataManager_ = nullptr; +}; + +class ReminderEventCustomSubscriber : public EventFwk::CommonEventSubscriber { +public: + ReminderEventCustomSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, + std::shared_ptr &reminderDataManager); + virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); + +private: + std::shared_ptr reminderDataManager_ = nullptr; +}; + +class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { +public: + explicit SystemAbilityStatusChangeListener(std::shared_ptr &reminderDataManager); + ~SystemAbilityStatusChangeListener() {}; + virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +private: + std::shared_ptr reminderDataManager_ = nullptr; +}; + +class ReminderNotificationSubscriber : public NotificationSubscriber { +public: + explicit ReminderNotificationSubscriber(std::shared_ptr &reminderDataManager); + ~ReminderNotificationSubscriber() override; + void OnConnected() override; + void OnDisconnected() override; + void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override; + void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override; + void OnUpdate(const std::shared_ptr &sortingMap) override; + void OnDied() override; + void OnDoNotDisturbDateChange( + const std::shared_ptr &date) override; + void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override; + void OnBadgeChanged(const std::shared_ptr &badgeData) override; + void OnBadgeEnabledChanged(const sptr &callbackData) override; + void OnBatchCanceled(const std::vector> &requestList, + const std::shared_ptr &sortingMap, int32_t deleteReason) override; +private: + std::shared_ptr reminderDataManager_ = nullptr; +}; + + static std::shared_ptr subscriber_; +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H diff --git a/services/reminder/include/reminder_os_account_manager_helper.h b/services/reminder/include/reminder_os_account_manager_helper.h new file mode 100644 index 000000000..55a2c1e27 --- /dev/null +++ b/services/reminder/include/reminder_os_account_manager_helper.h @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2024 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_OS_ACCOUNT_MANAGER_HELPER_H +#define BASE_NOTIFICATION_OS_ACCOUNT_MANAGER_HELPER_H + +#include "errors.h" +#include "singleton.h" +#include + +namespace OHOS { +namespace Notification { +class ReminderOsAccountManagerHelper : public DelayedSingleton { +public: + + ReminderOsAccountManagerHelper() = default; + ~ReminderOsAccountManagerHelper() = default; + + /** + * @brief Get OsAccountManagerHelper instance object. + */ + static ReminderOsAccountManagerHelper &GetInstance(); + + /** + * Gets operating system account local ID from uid. + * + * @param uid Indicates the uid. + * @param id Indicates the account ID. + * @return Returns result code. + */ + ErrCode GetOsAccountLocalIdFromUid(const int32_t uid, int32_t &id); + + /** + * Gets operating system account local ID from current active. + * + * @param id Indicates the current active account ID. + * @return Returns result code. + */ + ErrCode GetCurrentActiveUserId(int32_t &id); +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h new file mode 100644 index 000000000..5a733ce44 --- /dev/null +++ b/services/reminder/include/reminder_service.h @@ -0,0 +1,150 @@ +/* + * Copyright (c) 2021-2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H + +#include +#include +#include +#include +#include + +#include "event_handler.h" +#include "event_runner.h" +#include "ffrt.h" +#include "refbase.h" + +#include "ans_const_define.h" +#include "reminder_manager_stub.h" +// #include "common_notification_publish_process.h" +// #include "distributed_kv_data_manager.h" +// #include "distributed_kvstore_death_recipient.h" +// #include "live_publish_process.h" +// #include "notification.h" +// #include "notification_dialog_manager.h" +// #include "notification_do_not_disturb_profile.h" +// #include "notification_record.h" +// #include "notification_slot_filter.h" +// #include "notification_sorting_map.h" +// #include "permission_filter.h" +// #include "push_callback_interface.h" +// #include "system_event_observer.h" +// #include "notification_subscriber_manager.h" +// #include "distributed_device_status.h" +// #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED +// #include "reminder_swing_decision_center.h" +// #endif + +namespace OHOS { +namespace Notification { + +static const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 +class ReminderService final : public ReminderManagerStub, + public std::enable_shared_from_this { +public: + // struct NotificationRequestDb { + // sptr request {nullptr}; + // sptr bundleOption {nullptr}; + // }; + + // struct RecentNotification { + // sptr notification = nullptr; + // bool isActive = false; + // int32_t deleteReason = 0; + // int64_t deleteTime = 0; + // }; + + ~ReminderService() override; + + DISALLOW_COPY_AND_MOVE(ReminderService); + + /** + * @brief Get the instance of service. + * + * @return Returns the instance. + */ + static sptr GetInstance(); + + /** + * @brief Check reminder permission + */ + bool CheckReminderPermission(); + + /** + * @brief Publishes a reminder notification. + * + * @param reminder Identifies the reminder notification request that needs to be published. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode PublishReminder(const ReminderRequest &reminder, int32_t& reminderId) override; + + /** + * @brief Cancel a reminder notifications. + * + * @param reminderId Identifies the reminders id that needs to be canceled. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CancelReminder(const int32_t reminderId) override; + + /** + * @brief Get all valid reminder notifications. + * + * @param reminders Identifies the list of all valid notifications. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetValidReminders(std::vector &reminders) override; + + /** + * @brief Cancel all reminder notifications. + * + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode CancelAllReminders() override; + + /** + * @brief Add exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param date exclude date + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AddExcludeDate(const int32_t reminderId, const int64_t date) override; + + /** + * @brief Clear exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode DelExcludeDates(const int32_t reminderId) override; + + /** + * @brief Get exclude date for reminder + * + * @param reminderId Identifies the reminders id. + * @param dates exclude dates + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; +private: + ReminderService(); +private: + static sptr instance_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H diff --git a/services/reminder/include/reminder_service_ability.h b/services/reminder/include/reminder_service_ability.h new file mode 100644 index 000000000..9734960da --- /dev/null +++ b/services/reminder/include/reminder_service_ability.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 BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H +// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H + +// #include "system_ability.h" + +// #include "reminder_service.h" +// #include "reminder_data_manager.h" +// #include "system_ability_definition.h" +// // #include "notification_extension_wrapper.h" + +// namespace OHOS { +// namespace Notification { +// class ReminderServiceAbility final : public SystemAbility { +// public: +// /** +// * @brief The constructor of service ability. +// * +// * @param systemAbilityId Indicates the system ability id. +// * @param runOnCreate Run the system ability on created. +// */ +// ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate); + +// /** +// * @brief The deconstructor. +// */ +// ~ReminderServiceAbility() final; + +// DISALLOW_COPY_AND_MOVE(ReminderServiceAbility); +// DECLARE_SYSTEM_ABILITY(ReminderServiceAbility); + +// private: +// void OnStart() final; +// void OnStop() final; +// void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +// void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; +// // void OnReceiveEvent(const EventFwk::CommonEventData &data); +// int32_t OnExtension(const std::string& extension, MessageParcel& data, MessageParcel& reply) override; + +// private: +// sptr service_; +// std::shared_ptr reminderAgent_; +// }; +// } // namespace Notification +// } // namespace OHOS + +// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H diff --git a/services/reminder/include/reminder_store.h b/services/reminder/include/reminder_store.h new file mode 100644 index 000000000..a71f1bd08 --- /dev/null +++ b/services/reminder/include/reminder_store.h @@ -0,0 +1,109 @@ +/* + * Copyright (c) 2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H + +#include + +#include "notification_bundle_option.h" +#include "reminder_request.h" +#include "rdb_errno.h" +#include "rdb_helper.h" +#include "rdb_open_callback.h" +#include "rdb_store_config.h" + +namespace OHOS { +namespace Notification { +class ReminderStore { +public: + ReminderStore() {}; + virtual ~ReminderStore() {}; + +public: + int32_t Init(); + int32_t Delete(const int32_t reminderId); + int32_t Delete(const std::string& pkg, const int32_t userId, const int32_t uid); + int32_t DeleteUser(const int32_t userId); + int32_t UpdateOrInsert(const sptr& reminder); + int32_t GetMaxId(); + std::vector> GetAllValidReminders(); + +public: + static void GetUInt8Val(const std::shared_ptr& resultSet, + const std::string& name, uint8_t& value); + static void GetUInt16Val(const std::shared_ptr& resultSet, + const std::string& name, uint16_t& value); + static void GetInt32Val(const std::shared_ptr& resultSet, + const std::string& name, int32_t& value); + static void GetInt64Val(const std::shared_ptr& resultSet, + const std::string& name, int64_t& value); + static void GetUInt64Val(const std::shared_ptr& resultSet, + const std::string& name, uint64_t& value); + static void GetStringVal(const std::shared_ptr& resultSet, + const std::string& name, std::string& value); + + static const int32_t STATE_OK; + static const int32_t STATE_FAIL; + + static const std::string REMINDER_DB_DIR; + static const std::string REMINDER_DB_NAME; + static const std::string REMINDER_DB_TABLE; + +private: + /** + * @brief Inits the data in database when system boot on or proxy process reboot on. + * + * 1. Deletes all the reminders which IS_EXPIRED is true. + * 2. Sets all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE + * + * @return int32_t result code. + */ + int32_t InitData(); + int32_t DeleteBase(const std::string& deleteCondition); + int32_t Delete(const std::string& baseCondition, const std::string& assoConditon); + int32_t Insert(const sptr& reminder); + int32_t Update(const sptr& reminder); + + bool IsReminderExist(const sptr& reminder); + std::vector> GetReminders(const std::string& queryCondition); + sptr BuildReminder(const std::shared_ptr& resultBase); + + std::shared_ptr Query(const std::string& tableName, const std::string& colums, + const int32_t reminderId); + std::shared_ptr Query(const std::string& queryCondition) const; + +private: + std::shared_ptr rdbStore_ = nullptr; + +private: +class ReminderStoreDataCallBack : public NativeRdb::RdbOpenCallback { +public: + int32_t OnCreate(NativeRdb::RdbStore& store) override; + int32_t OnUpgrade(NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) override; + int32_t OnDowngrade(NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) override; + +private: + int32_t CreateTable(NativeRdb::RdbStore& store); + int32_t CopyData(NativeRdb::RdbStore& store); + std::vector> GetOldReminders(NativeRdb::RdbStore& store); + void InsertNewReminders(NativeRdb::RdbStore& store, const std::vector>& reminders); + void AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, + const std::string& columnName, const std::string& columnType, const std::string& defValue); +}; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H \ No newline at end of file diff --git a/services/reminder/include/reminder_store_strategy.h b/services/reminder/include/reminder_store_strategy.h new file mode 100644 index 000000000..0d0ccefb6 --- /dev/null +++ b/services/reminder/include/reminder_store_strategy.h @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H + +#include +#include + +#include "reminder_request.h" +#include "rdb_store.h" + +namespace OHOS { +namespace Notification { +class ReminderStrategy { +public: + /** + * @brief Gets the value from rdb result. + * + * @param resultSet the rdb result. + * @param name the column name in rdb. + * @param value the column value in rdb. + */ + template + static void GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value); + +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion = false); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); + +private: + /** + * @brief Recovery time related fields from the database(old version rdb). + */ + static void RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database(old version rdb). + */ + static void RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database(old version rdb). + */ + static void RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Recovery time related fields from the database. + */ + static void RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery id related fields from the database. + */ + static void RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet); + /** + * @brief Recovery context related from the database. + */ + static void RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet); +}; + +class ReminderTimerStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderAlarmStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); +}; + +class ReminderCalendarStrategy { +public: + /** + * @brief Persist the reminder to the database. + */ + static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); + + /** + * @brief Restore the reminder from the database(old version rdb). + */ + static void RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet); + + /** + * @brief Restore the reminder from the database. + */ + static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, + const std::shared_ptr& resultSet); + +private: + static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); +}; + +template +void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, + const std::string& name, T& value) +{ + value = T(); + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + + if constexpr (std::is_same_v) { + resultSet->GetString(columnIndex, value); + } else if constexpr (std::is_same_v) { + resultSet->GetLong(columnIndex, value); + } else if constexpr (std::is_same_v) { + int64_t t = 0; + resultSet->GetLong(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + resultSet->GetInt(columnIndex, value); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } else if constexpr (std::is_same_v) { + int32_t t = 0; + resultSet->GetInt(columnIndex, t); + value = static_cast(t); + } +} +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/services/reminder/include/reminder_table.h b/services/reminder/include/reminder_table.h new file mode 100644 index 000000000..4542000cd --- /dev/null +++ b/services/reminder/include/reminder_table.h @@ -0,0 +1,272 @@ +/* + * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H + +#include +#include + +namespace OHOS { +namespace Notification { +class ReminderBaseTable { +public: + /* + * reminder base table name + */ + static const std::string TABLE_NAME; + + /* + * reminder id + */ + static const std::string REMINDER_ID; + + /* + * package name + */ + static const std::string PACKAGE_NAME; + + /* + * user id + */ + static const std::string USER_ID; + + /* + * uid + */ + static const std::string UID; + + /* + * systerm app flag + */ + static const std::string SYSTEM_APP; + + /* + * reminder type: Timer/Calendar/Alarm + */ + static const std::string REMINDER_TYPE; + + /* + * reminder time + */ + static const std::string REMINDER_TIME; + + /* + * trigger time + */ + static const std::string TRIGGER_TIME; + + /* + * time interval + */ + static const std::string TIME_INTERVAL; + + /* + * snooze times + */ + static const std::string SNOOZE_TIMES; + + /* + * dynamic snooze times + */ + static const std::string DYNAMIC_SNOOZE_TIMES; + + /* + * ring duration + */ + static const std::string RING_DURATION; + + /* + * expired flag + */ + static const std::string IS_EXPIRED; + + /* + * reminder state + */ + static const std::string STATE; + + /* + * action button information + */ + static const std::string ACTION_BUTTON_INFO; + + /* + * custom button uri + */ + static const std::string CUSTOM_BUTTON_URI; + + /* + * slot type + */ + static const std::string SLOT_ID; + + /* + * snoozeslot type + */ + static const std::string SNOOZE_SLOT_ID; + + /* + * notification id + */ + static const std::string NOTIFICATION_ID; + + /* + * notification title + */ + static const std::string TITLE; + + /* + * notification content + */ + static const std::string CONTENT; + + /* + * notification snooze content + */ + static const std::string SNOOZE_CONTENT; + + /* + * notification expired content + */ + static const std::string EXPIRED_CONTENT; + + /* + * want agent information + */ + static const std::string WANT_AGENT; + + /* + * max screen want agent information + */ + static const std::string MAX_SCREEN_WANT_AGENT; + + /* + * tap dismissed flag + */ + static const std::string TAP_DISMISSED; + + /* + * auto deleted time + */ + static const std::string AUTO_DELETED_TIME; + + /* + * group id + */ + static const std::string GROUP_ID; + + /* + * custom ring uri + */ + static const std::string CUSTOM_RING_URI; + + /* + * creator bundle name + */ + static const std::string CREATOR_BUNDLE_NAME; + + /* + * creator uid + */ + static const std::string CREATOR_UID; + +public: + static void InitDbColumns(); + +public: + static std::string ADD_COLUMNS; + static std::string SELECT_COLUMNS; +}; + +class ReminderAlarmTable { +public: + /* + * reminder alarm table name + */ + static const std::string TABLE_NAME; + + /* + * reminder timer table field + */ + static const std::string REMINDER_ID; + static const std::string ALARM_HOUR; + static const std::string ALARM_MINUTE; + static const std::string REPEAT_DAYS_OF_WEEK; + +public: + static void InitDbColumns(); + +public: + static std::string ADD_COLUMNS; + static std::string SELECT_COLUMNS; +}; + +class ReminderCalendarTable { +public: + /* + * reminder calendar table name + */ + static const std::string TABLE_NAME; + + /* + * reminder calendar table field + */ + static const std::string REMINDER_ID; + static const std::string FIRST_DESIGNATE_YEAR; + static const std::string FIRST_DESIGNATE_MONTH; + static const std::string FIRST_DESIGNATE_DAY; + static const std::string CALENDAR_DATE_TIME; + static const std::string CALENDAR_END_DATE_TIME; + static const std::string REPEAT_DAYS; + static const std::string REPEAT_MONTHS; + static const std::string REPEAT_DAYS_OF_WEEK; + static const std::string RRULE_WANT_AGENT; + static const std::string EXCLUDE_DATES; + static const std::string CALENDAR_LAST_DATE_TIME; + +public: + static void InitDbColumns(); + +public: + static std::string ADD_COLUMNS; + static std::string SELECT_COLUMNS; +}; + +class ReminderTimerTable { +public: + /* + * reminder timer table name + */ + static const std::string TABLE_NAME; + + /* + * reminder timer table field + */ + static const std::string REMINDER_ID; + static const std::string TRIGGER_SECOND; + static const std::string START_DATE_TIME; + static const std::string END_DATE_TIME; + +public: + static void InitDbColumns(); + +public: + static std::string ADD_COLUMNS; + static std::string SELECT_COLUMNS; +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H diff --git a/services/reminder/include/reminder_table_old.h b/services/reminder/include/reminder_table_old.h new file mode 100644 index 000000000..172541b49 --- /dev/null +++ b/services/reminder/include/reminder_table_old.h @@ -0,0 +1,239 @@ +/* + * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H + +#include +#include + +namespace OHOS { +namespace Notification { +class ReminderTable { +public: + static void InitDbColumns(); + + static const std::string TABLE_NAME; + + // Reminder Table Basic Columns. + + /* + * reminder id + */ + static const std::string REMINDER_ID; + + /* + * package name + */ + static const std::string PKG_NAME; + + /* + * user id + */ + static const std::string USER_ID; + + /* + * uid + */ + static const std::string UID; + + /* + * systerm app flag + */ + static const std::string SYS_APP; + + /* + * app label + */ + static const std::string APP_LABEL; + + /* + * reminder type: Timer/Calendar/Alarm + */ + static const std::string REMINDER_TYPE; + + /* + * reminder time + */ + static const std::string REMINDER_TIME; + + /* + * trigger time + */ + static const std::string TRIGGER_TIME; + + /* + * RTC trigger time + */ + static const std::string RTC_TRIGGER_TIME; + + /* + * time interval + */ + static const std::string TIME_INTERVAL; + + /* + * snooze times + */ + static const std::string SNOOZE_TIMES; + + /* + * dynamic snooze times + */ + static const std::string DYNAMIC_SNOOZE_TIMES; + + /* + * ring duration + */ + static const std::string RING_DURATION; + + /* + * expired flag + */ + static const std::string IS_EXPIRED; + + /* + * active flag + */ + static const std::string IS_ACTIVE; + + /* + * reminder state + */ + static const std::string STATE; + + /* + * zone id + */ + static const std::string ZONE_ID; + + /* + * scheduled timeout flag + */ + static const std::string HAS_SCHEDULED_TIMEOUT; + + /* + * action button information + */ + static const std::string ACTION_BUTTON_INFO; + + /* + * custom button uri + */ + static const std::string CUSTOM_BUTTON_URI; + + /* + * slot type + */ + static const std::string SLOT_ID; + + /* + * snoozeslot type + */ + static const std::string SNOOZE_SLOT_ID; + + /* + * notification id + */ + static const std::string NOTIFICATION_ID; + + /* + * notification title + */ + static const std::string TITLE; + + /* + * notification content + */ + static const std::string CONTENT; + + /* + * notification snooze content + */ + static const std::string SNOOZE_CONTENT; + + /* + * notification expired content + */ + static const std::string EXPIRED_CONTENT; + + /* + * agent information + */ + static const std::string AGENT; + + /* + * max screen agent information + */ + static const std::string MAX_SCREEN_AGENT; + + /* + * tap dismissed flag + */ + static const std::string TAP_DISMISSED; + + /* + * auto deleted time + */ + static const std::string AUTO_DELETED_TIME; + + /* + * repeat days of week + */ + static const std::string REPEAT_DAYS_OF_WEEK; + + /* + * reminder group id + */ + static const std::string GROUP_ID; + + /* + * reminder ring uri + */ + static const std::string CUSTOM_RING_URI; + + /* + * reminder creator bundle name + */ + static const std::string CREATOR_BUNDLE_NAME; + + // Reminder Table Calendar Columns. + static const std::string REPEAT_DAYS; + static const std::string REPEAT_MONTHS; + static const std::string FIRST_DESIGNATE_YEAR; + static const std::string FIRST_DESIGNATE_MONTH; + static const std::string FIRST_DESIGNATE_DAY; + static const std::string CALENDAR_YEAR; + static const std::string CALENDAR_MONTH; + static const std::string CALENDAR_DAY; + static const std::string CALENDAR_HOUR; + static const std::string CALENDAR_MINUTE; + + // Reminder Table Alarm Columns. + static const std::string ALARM_HOUR; + static const std::string ALARM_MINUTE; + + static std::string ADD_COLUMNS; + static std::string SELECT_COLUMNS; + +private: + static void InitBasicColumns(); + static void InitCalendarColumns(); + static void InitAlarmColumns(); + static void AddColumn(const std::string& name, const std::string& type, bool isEnd = false); +}; +} // namespace Notification +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H diff --git a/services/reminder/include/reminder_timer_info.h b/services/reminder/include/reminder_timer_info.h new file mode 100644 index 000000000..1ac0c35d4 --- /dev/null +++ b/services/reminder/include/reminder_timer_info.h @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H + +#include "reminder_service.h" +#include "itimer_info.h" +#include "notification_request.h" +#include "reminder_request.h" + +namespace OHOS { +namespace Notification { +class ReminderTimerInfo : public MiscServices::ITimerInfo { +public: + ReminderTimerInfo() {}; + virtual ~ReminderTimerInfo() {}; + + ReminderTimerInfo(ReminderTimerInfo &other) = delete; + ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; + + inline void SetAction(const std::string &action) + { + action_ = action; + } + + inline void SetPid(const int32_t pid) + { + pid_ = pid; + } + + inline void SetUid(const int32_t uid) + { + uid_ = uid; + } + + inline void SetBundleName(const std::string &bundleName) + { + bundleName_ = bundleName; + } + + /** + * When timing is up, this function will execute as call back. + */ + void OnTrigger() override; + + /** + * Indicates the timing type. + */ + void SetType(const int32_t &type) override; + + /** + * Indicates the repeat policy. + */ + void SetRepeat(bool repeat) override; + + /** + * Indicates the interval time for repeat timing. + */ + void SetInterval(const uint64_t &interval) override; + + /** + * Indicates the want agent information. + */ + void SetWantAgent(std::shared_ptr wantAgent) override; + +private: + std::string action_; + int32_t pid_ {-1}; + int32_t uid_ {-1}; + std::string bundleName_; +}; +} // namespace OHOS +} // namespace Notification + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/reminder/include/remote_death_recipient.h b/services/reminder/include/remote_death_recipient.h new file mode 100644 index 000000000..da1b9563b --- /dev/null +++ b/services/reminder/include/remote_death_recipient.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H + +#include + +#include "iremote_object.h" +#include "refbase.h" + +namespace OHOS { +namespace Notification { +class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { +public: + /** + * The constructor. + * @param callback Indicates the callback. + */ + explicit RemoteDeathRecipient(std::function &)> callback) + { + callback_ = callback; + } + + /** + * The deconstructor. + */ + ~RemoteDeathRecipient() + { + callback_ = nullptr; + } + + /** + * Obtains the death event. Inherited from IRemoteObject::DeathRecipient. + * @param object Indicates the death object. + */ + void OnRemoteDied(const wptr &object) + { + if (callback_ != nullptr) { + callback_(object); + } + } + +private: + std::function &)> callback_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/reminder/src/reminder_access_token_helper.cpp b/services/reminder/src/reminder_access_token_helper.cpp new file mode 100644 index 000000000..473427b17 --- /dev/null +++ b/services/reminder/src/reminder_access_token_helper.cpp @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2022 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 "reminder_access_token_helper.h" + +#include "ans_log_wrapper.h" +#include "ipc_skeleton.h" +#include "tokenid_kit.h" +#include "reminder_notification_inline.cpp" + +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace Notification { +bool ReminderAccessTokenHelper::IsSystemApp() +{ + AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); + ATokenTypeEnum type = AccessTokenKit::GetTokenTypeFlag(tokenId); + if (type == ATokenTypeEnum::TOKEN_HAP) { + uint64_t fullTokenId = IPCSkeleton::GetCallingFullTokenID(); + if (Security::AccessToken::TokenIdKit::IsSystemAppByFullTokenID(fullTokenId)) { + return true; + } + } + return false; +} + +bool ReminderAccessTokenHelper::VerifyNativeToken(const AccessTokenID &callerToken) +{ + ATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(callerToken); + return (tokenType == ATokenTypeEnum::TOKEN_NATIVE); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_bundle_manager_helper.cpp b/services/reminder/src/reminder_bundle_manager_helper.cpp new file mode 100644 index 000000000..c9cb37023 --- /dev/null +++ b/services/reminder/src/reminder_bundle_manager_helper.cpp @@ -0,0 +1,151 @@ +/* + * Copyright (c) 2021-2023 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 "reminder_bundle_manager_helper.h" + +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "os_account_manager.h" +#include "system_ability_definition.h" + +#include "ans_const_define.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +ReminderBundleManagerHelper::ReminderBundleManagerHelper() +{ + deathRecipient_ = new (std::nothrow) + RemoteDeathRecipient(std::bind(&ReminderBundleManagerHelper::OnRemoteDied, this, std::placeholders::_1)); + if (deathRecipient_ == nullptr) { + ANS_LOGE("Failed to create RemoteDeathRecipient instance"); + } +} + +ReminderBundleManagerHelper::~ReminderBundleManagerHelper() +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +void ReminderBundleManagerHelper::OnRemoteDied(const wptr &object) +{ + std::lock_guard lock(connectionMutex_); + Disconnect(); +} + +void ReminderBundleManagerHelper::Connect() +{ + if (bundleMgr_ != nullptr) { + return; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + return; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (remoteObject == nullptr) { + return; + } + + bundleMgr_ = iface_cast(remoteObject); + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->AddDeathRecipient(deathRecipient_); + } +} + +void ReminderBundleManagerHelper::Disconnect() +{ + if (bundleMgr_ != nullptr) { + bundleMgr_->AsObject()->RemoveDeathRecipient(deathRecipient_); + bundleMgr_ = nullptr; + } +} + +std::string ReminderBundleManagerHelper::GetBundleNameByUid(int32_t uid) +{ + std::string bundle; + + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bundleMgr_->GetNameForUid(uid, bundle); + IPCSkeleton::SetCallingIdentity(identity); + } + + return bundle; +} + +int32_t ReminderBundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +{ + int32_t uid = -1; + + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + std::string identity = IPCSkeleton::ResetCallingIdentity(); + uid = bundleMgr_->GetUidByBundleName(bundle, userId); + if (uid < 0) { + ANS_LOGW("get invalid uid of bundle %{public}s in userId %{public}d", bundle.c_str(), userId); + } + IPCSkeleton::SetCallingIdentity(identity); + } + + return uid; +} + +bool ReminderBundleManagerHelper::GetBundleInfo(const std::string &bundleName, const AppExecFwk::BundleFlag flag, + int32_t userId, AppExecFwk::BundleInfo &bundleInfo) +{ + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ == nullptr) { + return false; + } + int32_t callingUserId; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(userId, callingUserId); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bool ret = bundleMgr_->GetBundleInfo(bundleName, flag, bundleInfo, callingUserId); + IPCSkeleton::SetCallingIdentity(identity); + return ret; +} + +int32_t ReminderBundleManagerHelper::GetAppIndexByUid(const int32_t uid) +{ + int32_t appIndex = 0; + std::lock_guard lock(connectionMutex_); + Connect(); + if (nullptr == bundleMgr_) { + return appIndex; + } + std::string bundleName; + std::string identity = IPCSkeleton::ResetCallingIdentity(); + bundleMgr_->GetNameAndIndexForUid(uid, bundleName, appIndex); + IPCSkeleton::SetCallingIdentity(identity); + return appIndex; +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_config_change_observer.cpp b/services/reminder/src/reminder_config_change_observer.cpp new file mode 100644 index 000000000..e0efc126f --- /dev/null +++ b/services/reminder/src/reminder_config_change_observer.cpp @@ -0,0 +1,41 @@ +/* + * Copyright (c) 2023 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 "reminder_config_change_observer.h" + +#include "ans_log_wrapper.h" +#include "reminder_data_manager.h" + +namespace OHOS { +namespace Notification { + +void ReminderConfigChangeObserver::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) +{ + ANSR_LOGD("OnConfigurationUpdated."); + auto reminderDataMgr = ReminderDataManager::GetInstance(); + if (reminderDataMgr == nullptr) { + ANSR_LOGW("Reminder data manager is nullptr"); + return; + } + std::string newLanguageInfo = configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE); + if (!newLanguageInfo.empty() && newLanguageInfo != languageInfo_) { + ANSR_LOGD("language change: %{public}s -> %{public}s", languageInfo_.c_str(), newLanguageInfo.c_str()); + reminderDataMgr->OnLanguageChanged(); + languageInfo_ = newLanguageInfo; + } +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp new file mode 100644 index 000000000..5a75a336a --- /dev/null +++ b/services/reminder/src/reminder_data_manager.cpp @@ -0,0 +1,2035 @@ +/* + * Copyright (c) 2021-2023 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 "reminder_data_manager.h" + +#include "ability_manager_client.h" +// #include "access_token_helper.h" +#include "ans_log_wrapper.h" +#include "ans_const_define.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "reminder_request_calendar.h" +#include "in_process_call_wrapper.h" +#ifdef DEVICE_STANDBY_ENABLE +#include "standby_service_client.h" +#include "allow_type.h" +#endif +#include "ipc_skeleton.h" +#include "notification_slot.h" +#include "os_account_manager.h" +#include "reminder_os_account_manager_helper.h" +#include "reminder_event_manager.h" +#include "time_service_client.h" +#include "singleton.h" +#include "locale_config.h" +#include "reminder_bundle_manager_helper.h" +#include "datashare_predicates_object.h" +#include "datashare_value_object.h" +#include "datashare_helper.h" +#include "data_share_permission.h" +#include "datashare_errno.h" +#include "datashare_template.h" +#include "system_ability_definition.h" +#include "app_mgr_constants.h" +#include "iservice_registry.h" +#include "config_policy_utils.h" +#include "hitrace_meter_adapter.h" +#ifdef HAS_HISYSEVENT_PART +#include "hisysevent.h" +#endif + +namespace OHOS { +namespace Notification { +namespace { +const std::string ALL_PACKAGES = "allPackages"; +const int32_t MAIN_USER_ID = 100; +#ifdef DEVICE_STANDBY_ENABLE +const int REASON_APP_API = 1; +#endif +const int INDEX_KEY = 0; +const int INDEX_TYPE = 1; +const int INDEX_VALUE = 2; +} + +/** + * Default reminder sound. + */ +const std::string DEFAULT_REMINDER_SOUND_1 = "/system/etc/capture.ogg"; +const std::string DEFAULT_REMINDER_SOUND_2 = "resource/media/audio/alarms/Aegean_Sea.ogg"; + +std::shared_ptr ReminderDataManager::REMINDER_DATA_MANAGER = nullptr; +std::mutex ReminderDataManager::MUTEX; +std::mutex ReminderDataManager::SHOW_MUTEX; +std::mutex ReminderDataManager::ALERT_MUTEX; +std::mutex ReminderDataManager::TIMER_MUTEX; +std::mutex ReminderDataManager::ACTIVE_MUTEX; +constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100; +constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 3; +std::shared_ptr ReminderDataManager::serviceQueue_ = nullptr; +ReminderDataManager::~ReminderDataManager() = default; + +ErrCode ReminderDataManager::PublishReminder(const sptr &reminder, + const int32_t callingUid) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID(); + if (callerTokenId == 0) { + ANSR_LOGE("pushlish failed, callerTokenId is 0"); + return ERR_REMINDER_CALLER_TOKEN_INVALID; + } + + if (!IsActionButtonDataShareValid(reminder, callerTokenId)) { + return ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED; + } + + if (CheckReminderLimitExceededLocked(callingUid, reminder)) { + return ERR_REMINDER_NUMBER_OVERLOAD; + } + UpdateAndSaveReminderLocked(reminder, callingUid); + queue_->submit([this, reminder]() { + StartRecentReminder(); + }); + return ERR_OK; +} + +ErrCode ReminderDataManager::CancelReminder( + const int32_t &reminderId, const int32_t callingUid) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("cancel reminder id: %{public}d", reminderId); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Cancel reminder, not find the reminder"); + return ERR_REMINDER_NOT_EXIST; + } + if (!CheckIsSameApp(reminder, callingUid)) { + ANSR_LOGW("Not find the reminder due to not match"); + return ERR_REMINDER_NOT_EXIST; + } + if (activeReminderId_ == reminderId) { + ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId); + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_->OnStop(); + } + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + if (alertingReminderId_ == reminderId) { + StopSoundAndVibrationLocked(reminder); + StopTimerLocked(TimerType::ALERTING_TIMER); + } + CancelNotification(reminder); + RemoveReminderLocked(reminderId); + StartRecentReminder(); + return ERR_OK; +} + +ErrCode ReminderDataManager::CancelAllReminders(const int32_t userId, const int32_t callingUid) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); + CancelRemindersImplLocked(userId, callingUid); + return ERR_OK; +} + +sptr ReminderDataManager::CheckExcludeDateParam(const int32_t reminderId, + const int32_t callingUid) +{ + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Check reminder failed, not find the reminder"); + return nullptr; + } + if (!CheckIsSameApp(reminder, callingUid)) { + ANSR_LOGW("Check reminder failed, due to not match"); + return nullptr; + } + if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR + || !reminder->IsRepeat()) { + ANSR_LOGW("Check reminder failed, due to type not match or not repeat"); + return nullptr; + } + return reminder; +} + +ErrCode ReminderDataManager::AddExcludeDate(const int32_t reminderId, const int64_t date, + const int32_t callingUid) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + sptr reminder = CheckExcludeDateParam(reminderId, callingUid); + if (reminder == nullptr) { + return ERR_REMINDER_NOT_EXIST; + } + { + std::lock_guard locker(ReminderDataManager::MUTEX); + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->AddExcludeDate(date); + store_->UpdateOrInsert(reminder); + } + return ERR_OK; +} + +ErrCode ReminderDataManager::DelExcludeDates(const int32_t reminderId, + const int32_t callingUid) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + sptr reminder = CheckExcludeDateParam(reminderId, callingUid); + if (reminder == nullptr) { + return ERR_REMINDER_NOT_EXIST; + } + { + std::lock_guard locker(ReminderDataManager::MUTEX); + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + calendar->DelExcludeDates(); + store_->UpdateOrInsert(reminder); + } + return ERR_OK; +} + +ErrCode ReminderDataManager::GetExcludeDates(const int32_t reminderId, + const int32_t callingUid, std::vector& dates) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + sptr reminder = CheckExcludeDateParam(reminderId, callingUid); + if (reminder == nullptr) { + return ERR_REMINDER_NOT_EXIST; + } + { + std::lock_guard locker(ReminderDataManager::MUTEX); + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + dates = calendar->GetExcludeDates(); + } + return ERR_OK; +} + +void ReminderDataManager::GetValidReminders( + const int32_t callingUid, std::vector &reminders) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto& eachReminder : reminderVector_) { + if (eachReminder->IsExpired()) { + continue; + } + + if (CheckIsSameApp(eachReminder, callingUid)) { + reminders.push_back(*eachReminder); + } + } +} + +void ReminderDataManager::CancelAllReminders(const int32_t userId) +{ + ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); + CancelRemindersImplLocked(userId, -1, true); +} + +void ReminderDataManager::CancelRemindersImplLocked(const int32_t userId, + const int32_t uid, bool isCancelAllPackage) +{ + MUTEX.lock(); + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + if (activeReminderId_ != -1 && IsMatched(activeReminder_, userId, uid, isCancelAllPackage)) { + activeReminder_->OnStop(); + StopTimer(TimerType::TRIGGER_TIMER); + ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_.load()); + } + } + for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { + if (IsMatched(*vit, userId, uid, isCancelAllPackage)) { + if ((*vit)->IsAlerting()) { + StopAlertingReminder(*vit); + } + CancelNotification(*vit); + RemoveFromShowedReminders(*vit); + vit = reminderVector_.erase(vit); + totalCount_--; + continue; + } + ++vit; + } + if (isCancelAllPackage) { + store_->DeleteUser(userId); + } else { + // fengyang store_->Delete(packageName, userId, uid); + } + MUTEX.unlock(); + StartRecentReminder(); +} + +bool ReminderDataManager::IsMatchedForGroupIdAndPkgName(const sptr &reminder, + const std::string &packageName, const std::string &groupId) const +{ + std::string packageNameTemp = reminder->GetBundleName(); + if (packageNameTemp.empty()) { + ANSR_LOGW("reminder package name is null"); + return false; + } + if (packageNameTemp == packageName && reminder->GetGroupId() == groupId) { + return true; + } + return false; +} + +bool ReminderDataManager::IsMatched(const sptr &reminder, + const int32_t userId, const int32_t uid, bool isCancelAllPackage) const +{ + if (reminder->GetUserId() != userId) { + return false; + } + if (isCancelAllPackage) { + return true; + } + if (uid != -1 && reminder->GetUid() == uid) { + return true; + } + return false; +} + +void ReminderDataManager::CancelNotification(const sptr &reminder) const +{ + if (!(reminder->IsShowing())) { + ANSR_LOGD("No need to cancel notification"); + return; + } + sptr notification = reminder->GetNotificationRequest(); + if (notification == nullptr) { + ANSR_LOGW("Cancel notification fail"); + return; + } + ANSR_LOGD("Cancel notification"); + // if (advancedNotificationService_ == nullptr) { + // ANSR_LOGE("Cancel notification fail"); + // return; + // } + // sptr bundleOption = reminder->GetNotificationBundleOption(); + // advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), + // ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); +} + +bool ReminderDataManager::CheckReminderLimitExceededLocked(const int32_t callingUid, + const sptr& reminder) const +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { + ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ + and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); + return true; + } + int32_t count = 0; + for (const auto& eachReminder : reminderVector_) { + if (eachReminder->IsExpired()) { + continue; + } + if (CheckIsSameApp(eachReminder, callingUid)) { + count++; + } + } + auto maxReminderNum = reminder->IsSystemApp() ? MAX_NUM_REMINDER_LIMIT_SYS_APP : MAX_NUM_REMINDER_LIMIT_APP; + if (count >= maxReminderNum) { + ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ + reminder can not be published", maxReminderNum); + return true; + } + return false; +} + +void ReminderDataManager::AddToShowedReminders(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { + if (reminder->GetReminderId() == (*it)->GetReminderId()) { + ANSR_LOGD("Showed reminder is already exist"); + return; + } + } + showedReminderVector_.push_back(reminder); +} + +void ReminderDataManager::OnUserRemove(const int32_t& userId) +{ + if (!IsReminderAgentReady()) { + ANSR_LOGW("Give up to remove user id: %{private}d for reminderAgent is not ready", userId); + return; + } + CancelAllReminders(userId); +} + +void ReminderDataManager::OnUserSwitch(const int32_t& userId) +{ + ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); + currentUserId_ = userId; + std::lock_guard lock(ReminderDataManager::MUTEX); + if ((alertingReminderId_ != -1) && IsReminderAgentReady()) { + TerminateAlerting(alertingReminder_, "OnUserSwitch"); + } +} + +void ReminderDataManager::OnProcessDiedLocked(const int32_t callingUid) +{ + ANSR_LOGD("OnProcessDiedLocked, uid=%{public}d", callingUid); + std::lock_guard locker(ReminderDataManager::MUTEX); + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { + if ((*it)->GetUid() != callingUid) { + continue; + } + if ((*it)->IsAlerting()) { + TerminateAlerting((*it), "onProcessDied"); + } else { + CancelNotification(*it); + (*it)->OnClose(false); + showedReminderVector_.erase(it); + --it; + } + store_->UpdateOrInsert((*it)); + } +} + +void ReminderDataManager::InitTimerInfo(std::shared_ptr &sharedTimerInfo, + const sptr &reminderRequest, TimerType reminderType) const +{ + uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); + uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); + sharedTimerInfo->SetRepeat(false); + sharedTimerInfo->SetInterval(0); + + sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); + sharedTimerInfo->SetUid(reminderRequest->GetUid()); + + int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); + sharedTimerInfo->SetType(timerType); +} + +std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type, + const sptr &reminderRequest) const +{ + auto sharedTimerInfo = std::make_shared(); + if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { + ANSR_LOGE("Failed to set timer type."); + return nullptr; + } + InitTimerInfo(sharedTimerInfo, reminderRequest, type); + + int32_t requestCode = 10; + std::vector flags; + flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + + auto want = std::make_shared(); + switch (type) { + case (TimerType::TRIGGER_TIMER): { + want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_); + break; + } + case (TimerType::ALERTING_TIMER): { + if (alertingReminderId_ == -1) { + ANSR_LOGE("Create alerting time out timer Illegal."); + return sharedTimerInfo; + } + want->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); + sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); + want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_); + break; + } + default: + ANSR_LOGE("TimerType not support"); + break; + } + std::vector> wants; + wants.push_back(want); + AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, wants, nullptr); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr wantAgent = + AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); + IPCSkeleton::SetCallingIdentity(identity); + + sharedTimerInfo->SetWantAgent(wantAgent); + return sharedTimerInfo; +} + +sptr ReminderDataManager::FindReminderRequestLocked(const int32_t &reminderId) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if (reminderId == (*it)->GetReminderId()) { + return *it; + } + } + ANSR_LOGD("Not find the reminder"); + return nullptr; +} + +bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) +{ + return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); +} + +void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); + return; + } + std::string packageName = reminder->GetBundleName(); + std::string groupId = reminder->GetGroupId(); + if (!(packageName.empty() || groupId.empty())) { + ANSR_LOGD("this reminder can close by groupId"); + CloseRemindersByGroupId(reminderId, packageName, groupId); + } + CloseReminder(reminder, cancelNotification); + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + StartRecentReminder(); +} + +void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, + const std::string &groupId) +{ + if (packageName == "") { + ANSR_LOGD("packageName is empty"); + return; + } + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto vit = reminderVector_.begin(); vit != reminderVector_.end(); vit++) { + sptr reminder = *vit; + if (reminder == nullptr) { + ANSR_LOGD("reminder is null"); + continue; + } + int32_t reminderId = reminder->GetReminderId(); + if (reminderId == oldReminderId) { + ANSR_LOGD("The old and new reminder are the same"); + continue; + } + if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { + reminder->SetExpired(true); + reminder->SetStateToInActive(); + store_->UpdateOrInsert(reminder); + ResetStates(TimerType::TRIGGER_TIMER); + ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); + } + } +} + +void ReminderDataManager::CloseReminder(const sptr &reminder, bool cancelNotification) +{ + int32_t reminderId = reminder->GetReminderId(); + if (activeReminderId_ == reminderId) { + ANSR_LOGD("Stop active reminder due to CloseReminder"); + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_->OnStop(); + } + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + if (alertingReminderId_ == reminderId) { + StopSoundAndVibrationLocked(reminder); + StopTimerLocked(TimerType::ALERTING_TIMER); + } + reminder->OnClose(true); + RemoveFromShowedReminders(reminder); + store_->UpdateOrInsert(reminder); + if (cancelNotification) { + CancelNotification(reminder); + } +} + +std::shared_ptr ReminderDataManager::GetInstance() +{ + return REMINDER_DATA_MANAGER; +} + +std::shared_ptr ReminderDataManager::InitInstance() +{ + if (REMINDER_DATA_MANAGER == nullptr) { + REMINDER_DATA_MANAGER = std::make_shared(); + ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); + } + return REMINDER_DATA_MANAGER; +} + +// std::shared_ptr ReminderDataManager::InitInstance( +// const sptr &advancedNotificationService) +// { +// if (REMINDER_DATA_MANAGER == nullptr) { +// REMINDER_DATA_MANAGER = std::make_shared(); +// // REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; +// ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); +// } +// return REMINDER_DATA_MANAGER; +// } + +bool ReminderDataManager::CheckUpdateConditions(const sptr &reminder, + const ReminderRequest::ActionButtonType &actionButtonType, + const std::map &actionButtonMap) +{ + if (!reminder->IsSystemApp()) { + ANSR_LOGI("UpdateAppDatabase faild, is not SystemApp"); + return false; + } + if (actionButtonType == ReminderRequest::ActionButtonType::INVALID) { + ANSR_LOGI("actionButtonType is NVALID"); + return false; + } + if (!actionButtonMap.count(actionButtonType)) { + ANSR_LOGI("actionButtonType does not exist"); + return false; + } + if (actionButtonMap.at(actionButtonType).dataShareUpdate == nullptr) { + ANSR_LOGI("dataShareUpdate is null"); + return false; + } + if (actionButtonMap.at(actionButtonType).dataShareUpdate->uri == "" || + actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo == "" || + actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket == "") { + ANSR_LOGI("datashare parameter is invalid"); + return false; + } + return true; +} + +void ReminderDataManager::UpdateAppDatabase(const sptr &reminder, + const ReminderRequest::ActionButtonType &actionButtonType) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + auto actionButtonMap = reminder->GetActionButtons(); + if (!CheckUpdateConditions(reminder, actionButtonType, actionButtonMap)) { + return; + } + // init default dstBundleName + std::string dstBundleName = reminder->GetBundleName(); + GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); + + DataShare::CreateOptions options; + options.enabled_ = true; + auto userID = reminder->GetUserId(); + auto tokenID = IPCSkeleton::GetSelfTokenID(); + std::string uriStr = actionButtonMap.at(actionButtonType).dataShareUpdate->uri + "?user=" + std::to_string(userID) + + "&srcToken=" + std::to_string(tokenID) + "&dstBundleName=" + dstBundleName; + + // create datashareHelper + std::shared_ptr dataShareHelper = DataShare::DataShareHelper::Creator(uriStr, options); + if (dataShareHelper == nullptr) { + ANSR_LOGE("create datashareHelper failed"); + return; + } + // gen uri equalTo valuesBucket + Uri uri(uriStr); + + DataShare::DataSharePredicates predicates; + std::vector equalToVector = ReminderRequest::StringSplit( + actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo, ReminderRequest::SEP_BUTTON_VALUE_TYPE); + GenPredicates(predicates, equalToVector); + + DataShare::DataShareValuesBucket valuesBucket; + std::vector valuesBucketVector = ReminderRequest::StringSplit( + actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket, ReminderRequest::SEP_BUTTON_VALUE_TYPE); + GenValuesBucket(valuesBucket, valuesBucketVector); + + // update app store + int retVal = dataShareHelper->Update(uri, predicates, valuesBucket); + if (retVal > 0) { + // update success + ANSR_LOGI("update app store success retval:%{public}d", retVal); + } +} + +void ReminderDataManager::GenPredicates(DataShare::DataSharePredicates &predicates, + const std::vector &equalToVector) +{ + // predicates + for (auto &it : equalToVector) { + std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); + if (temp.size() <= INDEX_VALUE) { + continue; + } + if (temp[INDEX_TYPE] == "string") { + predicates.EqualTo(temp[INDEX_KEY], temp[INDEX_VALUE]); + } else if (temp[INDEX_TYPE] == "double") { + predicates.EqualTo(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); + } else if (temp[INDEX_TYPE] == "bool") { + bool valueBool = false; + if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true" || temp[INDEX_VALUE] == "True") { + valueBool = true; + } + predicates.EqualTo(temp[INDEX_KEY], valueBool); + } + } +} + +void ReminderDataManager::GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket, + const std::vector &valuesBucketVector) +{ + // valuesBucket + for (auto &it : valuesBucketVector) { + std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); + if (temp.size() <= INDEX_VALUE) { + continue; + } + if (temp[INDEX_TYPE] == "string") { + valuesBucket.Put(temp[INDEX_KEY], temp[INDEX_VALUE]); + } else if (temp[INDEX_TYPE] == "double") { + valuesBucket.Put(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); + } else if (temp[INDEX_TYPE] == "bool") { + bool valueBool = false; + if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true") { + valueBool = true; + } + valuesBucket.Put(temp[INDEX_KEY], valueBool); + } else if (temp[INDEX_TYPE] == "null") { + valuesBucket.Put(temp[INDEX_KEY]); + } else if (temp[INDEX_TYPE] == "vector") { + std::vector arr = ReminderRequest::StringSplit(temp[INDEX_VALUE], + ReminderRequest::SEP_BUTTON_VALUE_BLOB); + std::vector value; + for (auto &num : arr) { + value.emplace_back(static_cast(std::atoi(num.c_str()))); + } + valuesBucket.Put(temp[INDEX_KEY], value); + } + } +} + +void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std::string &uri) const +{ + size_t left = 0; + size_t right = 0; + left = uri.find("/", left); + right = uri.find("/", left + 1); + while (right != std::string::npos && right - left <= 1) { + left = right + 1; + right = uri.find("/", left); + } + if (left == std::string::npos) { + return; + } + if (right != std::string::npos) { + dstBundleName = uri.substr(left, right - left); + } else { + dstBundleName = uri.substr(left); + } +} + +void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) +{ + if (!IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } + std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; + ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); + if (activeReminderId_ != -1) { + ANSR_LOGD("Stop active reminder due to date/time or timeZone change"); + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_->OnStop(); + } + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + std::vector> showImmediately; + std::vector> extensionReminders; + RefreshRemindersLocked(type, showImmediately, extensionReminders); + HandleImmediatelyShow(showImmediately, true); + HandleExtensionReminder(extensionReminders); + StartRecentReminder(); +} + +void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); + return; + } + TerminateAlerting(reminder, "timeOut"); +} + +void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder) +{ + sleep(waitInSecond); + TerminateAlerting(reminder, "waitInMillis"); +} + +void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) +{ + if (reminder == nullptr) { + ANSR_LOGE("TerminateAlerting illegal."); + return; + } + ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", + reminder->Dump().c_str(), reason.c_str()); + StopAlertingReminder(reminder); + + if (!reminder->OnTerminate()) { + return; + } + int32_t reminderId = reminder->GetReminderId(); + int32_t uid = reminder->GetUid(); + sptr notificationRequest = reminder->GetNotificationRequest(); + ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); + UpdateNotification(reminder, false); + // if (advancedNotificationService_ == nullptr) { + // ANSR_LOGE("Ans instance is null."); + // return; + // } + // // Set the notification SoundEnabled and VibrationEnabled by soltType + // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); + // advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + store_->UpdateOrInsert(reminder); +} + +void ReminderDataManager::UpdateAndSaveReminderLocked( + const sptr& reminder, const int32_t callingUid) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + reminder->InitReminderId(); + int32_t userId = -1; + ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(callingUid, userId); + reminder->InitUserId(userId); + reminder->InitUid(callingUid); + // reminder->InitBundleName(bundleOption->GetBundleName()); + + if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) { + ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); + reminder->SetExpired(true); + } + // reminder->SetNotificationBundleOption(bundleOption); + reminderVector_.push_back(reminder); + totalCount_++; + store_->UpdateOrInsert(reminder); +} + +// void ReminderDataManager::SetService(sptr &advancedNotificationService) +// { +// advancedNotificationService_ = advancedNotificationService; +// } + +bool ReminderDataManager::ShouldAlert(const sptr &reminder) const +{ + if (reminder == nullptr) { + return false; + } + int32_t reminderId = reminder->GetReminderId(); + // sptr bundleOption = reminder->GetNotificationBundleOption(); + // if (bundleOption == nullptr) { + // ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); + // return false; + // } + int32_t userId = -1; + ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(reminder->GetUid(), userId); + if (currentUserId_ != userId) { + ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ + "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); + return false; + } + + sptr date; + // ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); + // if (errCode != ERR_OK) { + // ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); + // return true; + // } + if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { + return true; + } + std::vector> slots; + // errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); + // if (errCode != ERR_OK) { + // ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); + // return false; + // } + for (auto slot : slots) { + if (slot->GetType() != reminder->GetSlotType()) { + continue; + } + if (slot->IsEnableBypassDnd()) { + ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId); + return true; + } + } + ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId); + return false; +} + +void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId); + if (reminderId == activeReminderId_) { + ResetStates(TimerType::TRIGGER_TIMER); + } + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); + return; + } + if (HandleSysTimeChange(reminder)) { + return; + } + ShowActiveReminderExtendLocked(reminder); + StartRecentReminder(); +} + +bool ReminderDataManager::HandleSysTimeChange(const sptr reminder) const +{ + if (reminder->CanShow()) { + return false; + } else { + ANSR_LOGI("handleSystimeChange, no need to show reminder again."); + return true; + } +} + +void ReminderDataManager::SetActiveReminder(const sptr &reminder) +{ + if (reminder == nullptr) { + // activeReminder_ should not be set with null as it point to actual object. + activeReminderId_ = -1; + } else { + activeReminderId_ = reminder->GetReminderId(); + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_ = reminder; + } + ANSR_LOGD("Set activeReminderId=%{public}d", activeReminderId_.load()); +} + +void ReminderDataManager::SetAlertingReminder(const sptr &reminder) +{ + if (reminder == nullptr) { + // alertingReminder_ should not be set with null as it point to actual object. + alertingReminderId_ = -1; + } else { + alertingReminderId_ = reminder->GetReminderId(); + alertingReminder_ = reminder; + } + ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); +} + +void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); + bool isAlerting = false; + sptr playSoundReminder = nullptr; + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired()) { + continue; + } + uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli(); + if (tempTriggerTime < triggerTime) { + ANSR_LOGE("this reminder triggerTime is less than target triggerTime."); + continue; + } + if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { + continue; + } + if (!(*it)->IsNeedNotification()) { + continue; + } + ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); + if ((*it)->CheckExcludeDate()) { + ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); + continue; + } + if (((*it)->GetRingDuration() > 0) && !isAlerting) { + playSoundReminder = (*it); + isAlerting = true; + } else { + ShowReminder((*it), false, false, false, false); + } + } + if (playSoundReminder != nullptr) { + ShowReminder(playSoundReminder, true, false, false, true); + } +} + +bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) +{ + ANSR_LOGD("StartExtensionAbility"); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + std::shared_ptr wantInfo = calendar->GetRRuleWantAgentInfo(); + if (wantInfo != nullptr && wantInfo->pkgName.size() != 0 && wantInfo->abilityName.size() != 0) { + AAFwk::Want want; + want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); + want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); + int32_t result = IN_PROCESS_CALL( + AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); + if (result != ERR_OK) { + ANSR_LOGE("StartExtensionAbility failed[%{public}d]", result); + return false; + } + } + } + return true; +} + +void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) +{ + auto manager = ReminderDataManager::GetInstance(); + if (manager == nullptr) { + ANSR_LOGW("ReminderDataManager is nullptr."); + return; + } + if (!manager->IsSystemReady()) { + ANSR_LOGW("bundle service or ability service not ready."); + return; + } + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Start extension ability failed, is not system app"); + return; + } + times--; + bool ret = ReminderDataManager::StartExtensionAbility(reminder); + if (!ret && times > 0 && serviceQueue_ != nullptr) { + ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); + ffrt::task_attr taskAttr; + taskAttr.delay(CONNECT_EXTENSION_INTERVAL); + auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; + serviceQueue_->submit(callback, taskAttr); + } +} + +void ReminderDataManager::ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, + const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout) +{ + ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", + static_cast(isNeedToPlaySound), reminder->Dump().c_str()); + int32_t reminderId = reminder->GetReminderId(); + sptr notificationRequest = reminder->GetNotificationRequest(); + // if (advancedNotificationService_ == nullptr) { + // ANSR_LOGE("ShowReminder fail"); + // reminder->OnShow(false, isSysTimeChanged, false); + // store_->UpdateOrInsert(reminder, bundleOption); + // return; + // } + if (!IsAllowedNotify(reminder)) { + ANSR_LOGE("Not allow to notify."); + reminder->OnShow(false, isSysTimeChanged, false); + store_->UpdateOrInsert(reminder); + return; + } + ReportSysEvent(reminder); + bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; + reminder->OnShow(toPlaySound, isSysTimeChanged, true); + AddToShowedReminders(reminder); + UpdateNotification(reminder, false); // this should be called after OnShow + + if (alertingReminderId_ != -1) { + TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); + } + // Set the notification SoundEnabled and VibrationEnabled by soltType + // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); + // ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + // if (errCode != ERR_OK) { + // reminder->OnShowFail(); + // RemoveFromShowedReminders(reminder); + // } else { + // if (toPlaySound) { + // PlaySoundAndVibration(reminder); // play sound and vibration + // if (needScheduleTimeout) { + // StartTimer(reminder, TimerType::ALERTING_TIMER); + // } else { + // TerminateAlerting(1, reminder); + // } + // } + // HandleSameNotificationIdShowing(reminder); + // } + store_->UpdateOrInsert(reminder); + + if (isNeedToStartNext) { + StartRecentReminder(); + } +} + +void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) +{ + if (isSnooze) { + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); + } else { + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); + } + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); + reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); +} + +void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); + return; + } + SnoozeReminderImpl(reminder); + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::SNOOZE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::SNOOZE); +} + +void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) +{ + ANSR_LOGI("Snooze the reminder request, %{public}s", reminder->Dump().c_str()); + int32_t reminderId = reminder->GetReminderId(); + if (activeReminderId_ == reminderId) { + ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_.load()); + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_->OnStop(); + } + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + + // 1) Snooze the reminder by manual + if (alertingReminderId_ == reminder->GetReminderId()) { + StopSoundAndVibrationLocked(reminder); + StopTimerLocked(TimerType::ALERTING_TIMER); + } + reminder->OnSnooze(); + store_->UpdateOrInsert(reminder); + + // 2) Show the notification dialog in the systemUI + sptr notificationRequest = reminder->GetNotificationRequest(); + ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); + UpdateNotification(reminder, true); + // if (advancedNotificationService_ == nullptr) { + // ANSR_LOGE("Ans instance is null"); + // return; + // } + // // Set the notification SoundEnabled and VibrationEnabled by soltType + // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); + // advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + StartRecentReminder(); +} + +void ReminderDataManager::StartRecentReminder() +{ + sptr reminder = GetRecentReminderLocked(); + if (reminder == nullptr) { + ANSR_LOGI("No reminder need to start"); + SetActiveReminder(reminder); + return; + } + if (activeReminderId_ == reminder->GetReminderId()) { + ANSR_LOGI("Recent reminder has already run, no need to start again."); + return; + } + if (activeReminderId_ != -1) { + { + std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); + activeReminder_->OnStop(); + store_->UpdateOrInsert(activeReminder_); + } + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + ANSR_LOGI("Start recent reminder"); + StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); + reminder->OnStart(); + store_->UpdateOrInsert(reminder); +} + +void ReminderDataManager::StopAlertingReminder(const sptr &reminder) +{ + if (reminder == nullptr) { + ANSR_LOGE("StopAlertingReminder illegal."); + return; + } + if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { + ANSR_LOGE("StopAlertingReminder is illegal."); + return; + } + StopSoundAndVibration(alertingReminder_); + StopTimer(TimerType::ALERTING_TIMER); +} + +std::string ReminderDataManager::Dump() const +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + std::map>> bundleNameMap; + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired()) { + continue; + } + std::string bundleName = (*it)->GetBundleName(); + auto val = bundleNameMap.find(bundleName); + if (val == bundleNameMap.end()) { + std::vector> reminders; + reminders.push_back(*it); + bundleNameMap.insert(std::pair>>(bundleName, reminders)); + } else { + val->second.push_back(*it); + } + } + + std::string allReminders = ""; + for (auto it = bundleNameMap.begin(); it != bundleNameMap.end(); ++it) { + std::string bundleName = it->first; + std::vector> reminders = it->second; + sort(reminders.begin(), reminders.end(), cmp); + std::string oneBundleReminders = bundleName + ":{\n"; + oneBundleReminders += " totalCount:" + std::to_string(reminders.size()) + ",\n"; + oneBundleReminders += " reminders:{\n"; + for (auto vit = reminders.begin(); vit != reminders.end(); ++vit) { + oneBundleReminders += " [\n"; + std::string reminderInfo = (*vit)->Dump(); + oneBundleReminders += " " + reminderInfo + "\n"; + oneBundleReminders += " ],\n"; + } + oneBundleReminders += " },\n"; + oneBundleReminders += "},\n"; + allReminders += oneBundleReminders; + } + + return "ReminderDataManager{ totalCount:" + std::to_string(totalCount_) + ",\n" + + "timerId:" + std::to_string(timerId_) + ",\n" + + "activeReminderId:" + std::to_string(activeReminderId_) + ",\n" + + allReminders + "}"; +} + +sptr ReminderDataManager::GetRecentReminderLocked() +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + sort(reminderVector_.begin(), reminderVector_.end(), cmp); + for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { + if (!(*it)->IsExpired()) { + ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); + time_t now; + (void)time(&now); // unit is seconds. + if (now < 0 + || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) { + ANSR_LOGE("Get recent reminder while the trigger time is overdue."); + it++; + continue; + } + return *it; + } + if (!(*it)->CanRemove()) { + ANSR_LOGD("Reminder has been expired: %{public}s", (*it)->Dump().c_str()); + it++; + continue; + } + int32_t reminderId = (*it)->GetReminderId(); + ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + it = reminderVector_.erase(it); + totalCount_--; + store_->Delete(reminderId); + } + return nullptr; +} + +void ReminderDataManager::HandleImmediatelyShow( + std::vector> &showImmediately, bool isSysTimeChanged) +{ + bool isAlerting = false; + for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { + if ((*it)->IsShowing()) { + continue; + } + if (((*it)->GetRingDuration() > 0) && !isAlerting) { + std::lock_guard lock(ReminderDataManager::MUTEX); + ShowReminder((*it), true, false, isSysTimeChanged, true); + isAlerting = true; + } else { + std::lock_guard lock(ReminderDataManager::MUTEX); + ShowReminder((*it), false, false, isSysTimeChanged, false); + } + } +} + +void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) +{ + for (auto& reminder : extensionReminders) { + ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); + } +} + +sptr ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr &reminder) +{ + reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE); + uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli(); + bool needShowImmediately = false; + if (type == TIME_ZONE_CHANGE) { + needShowImmediately = reminder->OnTimeZoneChange(); + } + if (type == DATE_TIME_CHANGE) { + needShowImmediately = reminder->OnDateTimeChange(); + } + if (!needShowImmediately) { + uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli(); + if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { + CloseReminder(reminder, true); + } + store_->UpdateOrInsert(reminder); + return nullptr; + } + store_->UpdateOrInsert(reminder); + return reminder; +} + +void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) +{ + // not add ReminderDataManager::MUTEX, as ShowActiveReminderExtendLocked has locked + int32_t notificationId = reminder->GetNotificationId(); + ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); + int32_t curReminderId = reminder->GetReminderId(); + + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + int32_t tmpId = (*it)->GetReminderId(); + if (tmpId == curReminderId) { + continue; + } + if (!(*it)->IsShowing()) { + continue; + } + if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp((*it)->GetUid(), reminder->GetUid())) { + if ((*it)->IsAlerting()) { + StopAlertingReminder(*it); + } + (*it)->OnSameNotificationIdCovered(); + RemoveFromShowedReminders(*it); + store_->UpdateOrInsert((*it)); + } + } +} + +void ReminderDataManager::Init(bool isFromBootComplete) +{ + ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete); + if (isFromBootComplete) { + std::vector> immediatelyReminders; + std::vector> extensionReminders; + CheckReminderTime(immediatelyReminders, extensionReminders); + HandleImmediatelyShow(immediatelyReminders, false); + HandleExtensionReminder(extensionReminders); + StartRecentReminder(); + } + if (IsReminderAgentReady()) { + return; + } + // Register config observer for language change + if (!RegisterConfigurationObserver()) { + ANSR_LOGW("Register configuration observer failed."); + return; + } + if (queue_ == nullptr) { + queue_ = std::make_shared("ReminderDataManager"); + if (queue_ == nullptr) { + ANSR_LOGE("create ffrt queue failed!"); + return; + } + } + if (store_ == nullptr) { + store_ = std::make_shared(); + } + if (store_->Init() != ReminderStore::STATE_OK) { + ANSR_LOGW("Db init fail."); + return; + } + InitServiceHandler(); + LoadReminderFromDb(); + InitUserId(); + isReminderAgentReady_ = true; + ANSR_LOGD("ReminderAgent is ready."); +} + +void ReminderDataManager::InitServiceHandler() +{ + ANSR_LOGD("InitServiceHandler started"); + if (serviceQueue_ != nullptr) { + ANSR_LOGD("InitServiceHandler already init."); + return; + } + serviceQueue_ = std::make_shared("ReminderService"); + + ANSR_LOGD("InitServiceHandler suceeded."); +} + +void ReminderDataManager::CheckReminderTime(std::vector>& immediatelyReminders, + std::vector>& extensionReminders) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto reminder : reminderVector_) { + if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR) { + continue; + } + + if (reminder->IsPullUpService()) { + extensionReminders.push_back(reminder); + } + + if (reminder->OnDateTimeChange()) { + immediatelyReminders.push_back(reminder); + } + } +} + +void ReminderDataManager::InitUserId() +{ + currentUserId_ = MAIN_USER_ID; + ReminderOsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); +} + +bool ReminderDataManager::RegisterConfigurationObserver() +{ + if (configChangeObserver_ != nullptr) { + return true; + } + + auto appMgrClient = std::make_shared(); + configChangeObserver_ = sptr( + new (std::nothrow) ReminderConfigChangeObserver()); + if (appMgrClient->RegisterConfigurationObserver(configChangeObserver_) != ERR_OK) { + ANSR_LOGE("Register configuration observer failed."); + return false; + } + return true; +} + +void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector> &reminders) const +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto reminderSptr : reminderVector_) { + if (!(reminderSptr->ShouldShowImmediately())) { + break; + } + if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) { + reminderSptr->SetSnoozeTimesDynamic(0); + } + reminders.push_back(reminderSptr); + } +} + +bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) const +{ + if (reminder == nullptr) { + return false; + } + // auto option = reminder->GetNotificationBundleOption(); + // if (option == nullptr) { + // ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); + // return false; + // } + bool isAllowed = false; + // ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); + // if (errCode != ERR_OK) { + // ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); + // return false; + // } + return isAllowed; +} + +bool ReminderDataManager::IsReminderAgentReady() const +{ + return isReminderAgentReady_; +} + +bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, + const int32_t callingUid) const +{ + std::string bundleName = reminder->GetCreatorBundleName(); + int32_t uid = reminder->GetCreatorUid(); + if (uid == -1) { + uid = ReminderBundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); + } + return uid == callingUid; +} + +bool ReminderDataManager::IsBelongToSameApp(const int32_t uidSrc, + const int32_t uidTar) const +{ + bool result = uidSrc == uidTar; + int32_t userIdSrc = -1; + ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); + int32_t userIdTar = -1; + ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); + result = result && (userIdSrc == userIdTar); + return result; +} + +void ReminderDataManager::LoadReminderFromDb() +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + std::vector> existReminders = store_->GetAllValidReminders(); + reminderVector_ = existReminders; + ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); + // for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + // // sptr bundleOption = new (std::nothrow) NotificationBundleOption(); + // // if (bundleOption == nullptr) { + // // ANS_LOGE("Failed to create bundle option due to low memory."); + // // return; + // // } + // // bundleOption->SetBundleName((*it)->GetBundleName()); + // // bundleOption->SetUid((*it)->GetUid()); + // // (*it)->SetNotificationBundleOption(bundleOption); + // } + totalCount_ = static_cast(reminderVector_.size()); + ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; +} + +void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); + PlaySoundAndVibration(reminder); +} + +std::string ReminderDataManager::GetCustomRingUri(const sptr &reminder) +{ + if (reminder == nullptr) { + return ""; + } + return reminder->GetCustomRingUri(); +} + +std::string ReminderDataManager::GetFullPath(const std::string& oriPath) +{ + char buf[MAX_PATH_LEN] = {0}; + char* path = GetOneCfgFile(oriPath.c_str(), buf, MAX_PATH_LEN); + if (path == nullptr || *path == '\0') { + ANSR_LOGE("GetOneCfgFile failed"); + return ""; + } + std::string filePath = path; + return filePath; +} + +void ReminderDataManager::PlaySoundAndVibration(const sptr &reminder) +{ + if (reminder == nullptr) { + ANSR_LOGE("Play sound and vibration failed as reminder is null."); + return; + } + if (alertingReminderId_ != -1) { + TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); + } + ANSR_LOGD("Play sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); +#ifdef PLAYER_FRAMEWORK_ENABLE + if (soundPlayer_ == nullptr) { + soundPlayer_ = Media::PlayerFactory::CreatePlayer(); + if (soundPlayer_ == nullptr) { + ANSR_LOGE("Fail to creat player."); + return; + } + } + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + // use default ring + std::string defaultPath; + if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { + defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; + } else { + defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); + } + Uri defaultSound(defaultPath); + soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); + ANSR_LOGI("Play default sound."); + } else { + Global::Resource::ResourceManager::RawFileDescriptor desc; + if (GetCustomRingFileDesc(reminder, desc)) { + soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); + } + ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); + } + soundPlayer_->SetLooping(true); + soundPlayer_->PrepareAsync(); + soundPlayer_->Play(); +#endif + SetAlertingReminder(reminder); +} + +std::string ReminderDataManager::GetSoundUri(const sptr &reminder) +{ + Uri uri = DEFAULT_NOTIFICATION_SOUND; + // if (advancedNotificationService_ == nullptr) { + // ANSR_LOGE("Ans instance is null."); + // return uri.GetSchemeSpecificPart(); + // } + // sptr bundle = reminder->GetNotificationBundleOption(); + std::vector> slots; + // ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); + // if (errCode != ERR_OK) { + // ANSR_LOGW("Get sound uri fail, use default sound instead."); + // return uri.GetSchemeSpecificPart(); + // } + for (auto it = slots.begin(); it != slots.end(); ++it) { + if ((*it)->GetType() == reminder->GetSlotType()) { + uri = (*it)->GetSound(); + break; + } + } + return uri.GetSchemeSpecificPart(); +} + +void ReminderDataManager::StopSoundAndVibrationLocked(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); + StopSoundAndVibration(reminder); +} + +void ReminderDataManager::StopSoundAndVibration(const sptr &reminder) +{ + if (reminder == nullptr) { + ANSR_LOGE("Stop sound and vibration failed as reminder is null."); + return; + } + if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { + ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \ + "%{public}d, tarReminderId=%{public}d", alertingReminderId_.load(), reminder->GetReminderId()); + return; + } + ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); +#ifdef PLAYER_FRAMEWORK_ENABLE + if (soundPlayer_ == nullptr) { + ANSR_LOGW("Sound player is null"); + } else { + std::string customRingUri = reminder->GetCustomRingUri(); + if (customRingUri.empty()) { + ANSR_LOGI("Stop default sound."); + } else { + CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); + } + soundPlayer_->Stop(); + soundPlayer_->Release(); + soundPlayer_ = nullptr; + } +#endif + sptr nullReminder = nullptr; + SetAlertingReminder(nullReminder); +} + +void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { + if ((*it)->GetReminderId() == reminder->GetReminderId()) { + ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); + showedReminderVector_.erase(it); + break; + } + } +} + +void ReminderDataManager::RefreshRemindersLocked(uint8_t type, + std::vector>& immediatelyReminders, std::vector>& extensionReminders) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsPullUpService()) { + extensionReminders.push_back((*it)); + } + + sptr reminder = HandleRefreshReminder(type, (*it)); + if (reminder != nullptr) { + immediatelyReminders.push_back(reminder); + } + } +} + +void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { + if (reminderId == (*it)->GetReminderId()) { + ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + it = reminderVector_.erase(it); + totalCount_--; + store_->Delete(reminderId); + break; + } else { + ++it; + } + } +} + +void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) +{ + std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); + StartTimer(reminderRequest, type); +} + +void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); + return; + } + time_t now; + (void)time(&now); // unit is seconds. + if (now < 0) { + ANSR_LOGE("Get now time error"); + return; + } + uint64_t triggerTime = 0; + switch (type) { + case TimerType::TRIGGER_TIMER: { + if (timerId_ != 0) { + ANSR_LOGE("Trigger timer has already started."); + break; + } + triggerTime = HandleTriggerTimeInner(reminderRequest, type, timer); + break; + } + case TimerType::ALERTING_TIMER: { + if (timerIdAlerting_ != 0) { + ANSR_LOGE("Alerting time out timer has already started."); + break; + } + triggerTime = HandleAlertingTimeInner(reminderRequest, type, timer, now); + break; + } + default: { + ANSR_LOGE("TimerType not support"); + break; + } + } + if (triggerTime == 0) { + ANSR_LOGW("Start timer fail"); + } else { + ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")", + ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime); + } +} + +uint64_t ReminderDataManager::HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, + const sptr &timer) +{ + uint64_t triggerTime = 0; + SetActiveReminder(reminderRequest); + timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); + triggerTime = reminderRequest->GetTriggerTimeInMilli(); + timer->StartTimer(timerId_, triggerTime); + ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_); + return triggerTime; +} + +uint64_t ReminderDataManager::HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, + const sptr &timer, time_t now) +{ + uint64_t triggerTime = 0; + triggerTime = ReminderRequest::GetDurationSinceEpochInMilli(now) + + static_cast(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS); + timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); + timer->StartTimer(timerIdAlerting_, triggerTime); + ANSR_LOGD("Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_.load()); + return triggerTime; +} + +void ReminderDataManager::StopTimerLocked(TimerType type) +{ + std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); + StopTimer(type); +} + +void ReminderDataManager::StopTimer(TimerType type) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null."); + return; + } + uint64_t timerId = 0; + switch (type) { + case TimerType::TRIGGER_TIMER: { + timerId = timerId_; + ANSR_LOGD("Stop timing (next triggerTime)"); + break; + } + case TimerType::ALERTING_TIMER: { + timerId = timerIdAlerting_; + ANSR_LOGD("Stop timing (alerting time out)"); + break; + } + default: { + ANSR_LOGE("TimerType not support"); + break; + } + } + if (timerId == 0) { + ANSR_LOGD("Timer is not running"); + return; + } + ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId); + timer->StopTimer(timerId); + ResetStates(type); +} + +void ReminderDataManager::ResetStates(TimerType type) +{ + uint64_t timerId = 0; + switch (type) { + case TimerType::TRIGGER_TIMER: { + ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); + timerId = timerId_; + timerId_ = 0; + activeReminderId_ = -1; + break; + } + case TimerType::ALERTING_TIMER: { + ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); + timerId = timerIdAlerting_; + timerIdAlerting_ = 0; + alertingReminderId_ = -1; + break; + } + default: { + ANSR_LOGE("TimerType not support"); + break; + } + } + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + if (timer == nullptr) { + ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); + return; + } + if (timerId != 0) { + timer->DestroyTimer(timerId); + } +} + +void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); + return; + } + if (!reminder->IsSystemApp()) { + ANSR_LOGI("Custom button click, is not system app"); + return; + } + CloseReminder(reminder, false); + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); + std::string buttonPkgName = want.GetStringParam("PkgName"); + std::string buttonAbilityName = want.GetStringParam("AbilityName"); + + AAFwk::Want abilityWant; + abilityWant.SetElementName(buttonPkgName, buttonAbilityName); + abilityWant.SetUri(reminder->GetCustomButtonUri()); + auto client = AppExecFwk::AbilityManagerClient::GetInstance(); + if (client == nullptr) { + return; + } + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); + if (result != 0) { + ANSR_LOGE("Start ability failed, result = %{public}d", result); + return; + } +} + +void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) +{ + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); + ANSR_LOGI("click reminder[%{public}d] start", reminderId); + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); + return; + } + CloseReminder(reminder, true); + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + StartRecentReminder(); + + auto wantInfo = reminder->GetWantAgentInfo(); + if (wantInfo == nullptr || (wantInfo->pkgName.empty() && wantInfo->abilityName.empty())) { + ANSR_LOGW("want info is nullptr or no pkg name"); + return; + } + AAFwk::Want abilityWant; + AppExecFwk::ElementName element("", wantInfo->pkgName, wantInfo->abilityName); + abilityWant.SetElement(element); + abilityWant.SetUri(wantInfo->uri); + abilityWant.SetParams(wantInfo->parameters); + int32_t appIndex = ReminderBundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); + abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); + + auto client = AppExecFwk::AbilityManagerClient::GetInstance(); + if (client == nullptr) { + ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); + return; + } + uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); + int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); + if (result != 0) { + ANSR_LOGE("Start ability failed, result = %{public}d", result); + } +} + +std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, + const int32_t uid) +{ + AppExecFwk::BundleInfo bundleInfo; + if (!ReminderBundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, + AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { + ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); + return nullptr; + } + // obtains the resource manager + std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); + if (!resourceManager) { + ANSR_LOGE("CreateResourceManager fail."); + return nullptr; + } + // obtains the resource path. + for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { + std::string moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; + if (moduleResPath.empty()) { + continue; + } + if (!resourceManager->AddResource(moduleResPath.c_str())) { + ANSR_LOGW("AddResource fail."); + } + } + // obtains the current system language. + std::unique_ptr resConfig(Global::Resource::CreateResConfig()); + UErrorCode status = U_ZERO_ERROR; + icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); + resConfig->SetLocaleInfo(locale); + resourceManager->UpdateResConfig(*resConfig); + return resourceManager; +} + +void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, + const std::vector>& reminders) +{ + // obtains the bundle info by bundle name + if (reminders.empty()) { + return; + } + + std::string bundleName = reminders[0]->GetBundleName(); + // obtains the resource manager + auto resourceMgr = GetResourceMgr(bundleName, uid); + if (resourceMgr == nullptr) { + ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", + uid, bundleName.c_str()); + return; + } + // update action button title + for (auto reminder : reminders) { + std::lock_guard lock(ReminderDataManager::MUTEX); + reminder->OnLanguageChange(resourceMgr); + } +} + +void ReminderDataManager::OnLanguageChanged() +{ + ANSR_LOGI("System language config changed start."); + std::unordered_map>> reminders; + { + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + reminders[(*it)->GetUid()].push_back((*it)); + } + } + for (auto& each : reminders) { + UpdateReminderLanguageLocked(each.first, each.second); + } + std::vector> showedReminder; + { + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + showedReminder = showedReminderVector_; + } + for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { + std::lock_guard lock(ReminderDataManager::MUTEX); + ShowReminder((*it), false, false, false, false); + } + ANSR_LOGI("System language config changed end."); +} + +void ReminderDataManager::OnRemoveAppMgr() +{ + std::lock_guard lock(appMgrMutex_); + appMgrProxy_ = nullptr; +} + +bool ReminderDataManager::ConnectAppMgr() +{ + if (appMgrProxy_ != nullptr) { + return true; + } + + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemAbilityManager == nullptr) { + ANSR_LOGE("get SystemAbilityManager failed"); + return false; + } + + sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); + if (remoteObject == nullptr) { + ANSR_LOGE("get app manager service failed"); + return false; + } + + appMgrProxy_ = iface_cast(remoteObject); + if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { + ANSR_LOGE("get app mgr proxy failed!"); + return false; + } + return true; +} + +void ReminderDataManager::CheckNeedNotifyStatus(const sptr &reminder, + const ReminderRequest::ActionButtonType buttonType) +{ + const std::string bundleName = reminder->GetBundleName(); + if (bundleName.empty()) { + return; + } + bool isRunning = false; + { + std::lock_guard lock(appMgrMutex_); + if (!ConnectAppMgr()) { + return; + } + isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); + } + if (!isRunning) { + return; + } + + EventFwk::Want want; + // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string + want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); + EventFwk::CommonEventData eventData(want); + + std::string data; + data.append(std::to_string(static_cast(buttonType))).append(","); + data.append(std::to_string(reminder->GetReminderId())); + eventData.SetData(data); + + EventFwk::CommonEventPublishInfo info; + info.SetBundleName(bundleName); + if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { + ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); + } +} +} +} diff --git a/services/reminder/src/reminder_data_manager_inner.cpp b/services/reminder/src/reminder_data_manager_inner.cpp new file mode 100644 index 000000000..261f4d745 --- /dev/null +++ b/services/reminder/src/reminder_data_manager_inner.cpp @@ -0,0 +1,166 @@ +/* + * Copyright (c) 2024-2024 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 "reminder_data_manager.h" + +#include "ability_manager_client.h" +#include "ans_log_wrapper.h" +#include "ans_const_define.h" +#include "common_event_support.h" +#include "common_event_manager.h" +#include "reminder_request_calendar.h" +#include "in_process_call_wrapper.h" +#ifdef DEVICE_STANDBY_ENABLE +#include "standby_service_client.h" +#include "allow_type.h" +#endif +#include "ipc_skeleton.h" +#include "notification_slot.h" +#include "os_account_manager.h" +#include "reminder_event_manager.h" +#include "time_service_client.h" +#include "singleton.h" +#include "locale_config.h" +#include "datashare_predicates_object.h" +#include "datashare_value_object.h" +#include "datashare_helper.h" +#include "data_share_permission.h" +#include "datashare_errno.h" +#include "datashare_template.h" +#include "system_ability_definition.h" +#include "app_mgr_constants.h" +#include "iservice_registry.h" +#include "config_policy_utils.h" +#include "hitrace_meter_adapter.h" +#ifdef HAS_HISYSEVENT_PART +#include "hisysevent.h" +#endif + +namespace OHOS { +namespace Notification { +namespace { +constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. +} + +bool ReminderDataManager::IsSystemReady() +{ + return saReadyFlag_ >= ALL_SA_READY_FLAG; +} + +bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, + const uint32_t callerTokenId) +{ + auto actionButtonMap = reminder->GetActionButtons(); + for (auto it = actionButtonMap.begin(); it != actionButtonMap.end(); ++it) { + ReminderRequest::ActionButtonInfo& buttonInfo = it->second; + if (buttonInfo.dataShareUpdate->uri.empty()) { + continue; + } + Uri uri(buttonInfo.dataShareUpdate->uri); + auto ret = DataShare::DataSharePermission::VerifyPermission(callerTokenId, uri, false); + if (ret != DataShare::E_OK) { + ANSR_LOGE("publish failed, DataSharePermission::VerifyPermission return error[%{public}d],", + static_cast(ret)); + return false; + } + } + return true; +} + +void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, + const int64_t autoDeletedTime) +{ + ANSR_LOGI("auto delete reminder start"); + std::vector> showedReminder; + { + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + showedReminder = showedReminderVector_; + } + for (auto reminder : showedReminder) { + if (reminder == nullptr) { + continue; + } + + if (reminder->GetUid() != uid || notificationId != reminder->GetNotificationId() || + reminder->GetAutoDeletedTime() != autoDeletedTime) { + continue; + } + CloseReminder(reminder, true); + UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); + CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); + } + StartRecentReminder(); +} + +void ReminderDataManager::OnBundleMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + +void ReminderDataManager::OnAbilityMgrServiceStart() +{ + saReadyFlag_.fetch_add(1); +} + +bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, + Global::Resource::ResourceManager::RawFileDescriptor& desc) +{ + // obtains the resource manager + std::lock_guard locker(resourceMutex_); + soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); + if (soundResource_ == nullptr) { + ANSR_LOGE("GetResourceMgr fail."); + return false; + } + auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); + return false; + } + return true; +} + +void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) +{ + std::lock_guard locker(resourceMutex_); + if (soundResource_ == nullptr) { + ANSR_LOGW("ResourceManager is nullptr."); + return; + } + auto result = soundResource_->CloseRawFileDescriptor(customRingUri); + if (result != Global::Resource::SUCCESS) { + ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); + } + ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); + soundResource_ = nullptr; +} + +void ReminderDataManager::ReportSysEvent(const sptr& reminder) +{ +#ifdef HAS_HISYSEVENT_PART + std::string event = "ALARM_TRIGGER"; + std::string bundleName = reminder->GetBundleName(); + int32_t uid = reminder->GetUid(); + int32_t type = static_cast(reminder->GetReminderType()); + int32_t repeat = static_cast(reminder->IsRepeat()); + uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); + int32_t ringTime = static_cast(reminder->GetRingDuration()); + HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, + "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, + "RING_TIME", ringTime); +#endif +} +} +} diff --git a/services/reminder/src/reminder_event_manager.cpp b/services/reminder/src/reminder_event_manager.cpp new file mode 100644 index 000000000..f6fe7f5d6 --- /dev/null +++ b/services/reminder/src/reminder_event_manager.cpp @@ -0,0 +1,352 @@ +/* + * Copyright (c) 2021-2022 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 "reminder_event_manager.h" + +#include "ans_log_wrapper.h" +#include "bundle_constants.h" +#include "bundle_mgr_interface.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "reminder_bundle_manager_helper.h" +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "notification_helper.h" +#include "string_ex.h" + +using namespace OHOS::EventFwk; +namespace OHOS { +namespace Notification { +static const std::string NOTIFICATION_LABEL = "REMINDER_AGENT"; +std::shared_ptr ReminderEventManager::subscriber_ + = nullptr; + +ReminderEventManager::ReminderEventManager(std::shared_ptr &reminderDataManager) +{ + init(reminderDataManager); +} + +void ReminderEventManager::init(std::shared_ptr &reminderDataManager) const +{ + MatchingSkills customMatchingSkills; + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT); + customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLICK_ALERT); + CommonEventSubscribeInfo customSubscriberInfo(customMatchingSkills); + customSubscriberInfo.SetPermission("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); + customSubscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + auto customSubscriber = std::make_shared(customSubscriberInfo, reminderDataManager); + + MatchingSkills matchingSkills; + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIME_CHANGED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); + matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + subscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); + auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); + if (CommonEventManager::SubscribeCommonEvent(subscriber) && + CommonEventManager::SubscribeCommonEvent(customSubscriber)) { + ANSR_LOGD("SubscribeCommonEvent ok"); + } else { + ANSR_LOGD("SubscribeCommonEvent fail"); + } + IPCSkeleton::SetCallingIdentity(identity); + + subscriber_ = std::make_shared(reminderDataManager); + if (NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { + ANSR_LOGD("SubscribeNotification failed"); + } + + SubscribeSystemAbility(reminderDataManager); +} + +void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const +{ + sptr statusChangeListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (statusChangeListener == nullptr) { + ANSR_LOGE("Failed to create statusChangeListener due to no memory."); + return; + } + // app mgr + sptr appMgrStatusChangeListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (appMgrStatusChangeListener == nullptr) { + ANSR_LOGE("Failed to create appMgrStatusChangeListener due to no memory."); + return; + } + // ability mgr + sptr abilityMgrStatusListener + = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); + if (abilityMgrStatusListener == nullptr) { + ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); + return; + } + + sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ANSR_LOGD("samgrProxy is null"); + return; + } + int32_t ret = samgrProxy->SubscribeSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, statusChangeListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + } + ret = samgrProxy->SubscribeSystemAbility(APP_MGR_SERVICE_ID, appMgrStatusChangeListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", APP_MGR_SERVICE_ID); + } + ret = samgrProxy->SubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); + if (ret != ERR_OK) { + ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); + } +} + +ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( + const CommonEventSubscribeInfo &subscriberInfo, + std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) +{ + reminderDataManager_ = reminderDataManager; +} + +ReminderEventManager::ReminderEventCustomSubscriber::ReminderEventCustomSubscriber( + const CommonEventSubscribeInfo &subscriberInfo, + std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) +{ + reminderDataManager_ = reminderDataManager; +} + +void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + Want want = data.GetWant(); + std::string action = want.GetAction(); + ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); + if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { + reminderDataManager_->ShowActiveReminder(want); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT) { + reminderDataManager_->TerminateAlerting(want); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_CLOSE_ALERT) { + reminderDataManager_->CloseReminder(want, true); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT) { + reminderDataManager_->SnoozeReminder(want); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT) { + reminderDataManager_->HandleCustomButtonClick(want); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { + reminderDataManager_->CloseReminder(want, false); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { + reminderDataManager_->ClickReminder(want); + return; + } +} + +void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) +{ + Want want = data.GetWant(); + std::string action = want.GetAction(); + ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); + if (action == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) { + reminderDataManager_->Init(true); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + HandlePackageRemove(want); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { + HandlePackageRemove(want); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { + HandleProcessDied(want); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { + reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::TIME_ZONE_CHANGE); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_TIME_CHANGED) { + reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::DATE_TIME_CHANGE); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { + reminderDataManager_->OnUserSwitch(data.GetCode()); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { + reminderDataManager_->OnUserRemove(data.GetCode()); + return; + } +} + +void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const +{ + OHOS::AppExecFwk::ElementName ele = want.GetElement(); + int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); + int32_t uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); + reminderDataManager_->CancelAllReminders(userId, uid); +} + +void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const +{ + int32_t uid = GetUid(want); + reminderDataManager_->OnProcessDiedLocked(uid); +} + +int32_t ReminderEventManager::ReminderEventSubscriber::GetUid( + const OHOS::EventFwk::Want &want) const +{ + OHOS::AppExecFwk::ElementName ele = want.GetElement(); + std::string bundleName = ele.GetBundleName(); + int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); + int32_t uid = ReminderBundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); + ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); + return uid; +} + +ReminderEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener( + std::shared_ptr &reminderDataManager) +{ + reminderDataManager_ = reminderDataManager; +} + +void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + ANSR_LOGD("OnAddSystemAbilityInner"); + switch (systemAbilityId) { + case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: + ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); + reminderDataManager_->OnBundleMgrServiceStart(); + break; + case APP_MGR_SERVICE_ID: + ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); + break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + reminderDataManager_->OnAbilityMgrServiceStart(); + break; + default: + break; + } +} + +void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( + int32_t systemAbilityId, const std::string& deviceId) +{ + ANSR_LOGD("OnRemoveSystemAbilityInner"); + switch (systemAbilityId) { + case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: + ANSR_LOGD("OnRemoveSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); + break; + case APP_MGR_SERVICE_ID: + ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); + reminderDataManager_->OnRemoveAppMgr(); + break; + case ABILITY_MGR_SERVICE_ID: + ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); + break; + default: + break; + } +} + +ReminderEventManager::ReminderNotificationSubscriber::ReminderNotificationSubscriber( + std::shared_ptr &reminderDataManager) +{ + reminderDataManager_ = reminderDataManager; +} + +ReminderEventManager::ReminderNotificationSubscriber::~ReminderNotificationSubscriber() {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnConnected() {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnDisconnected() {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( + const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap, int deleteReason) +{ + // Note: Don't modify param notification + if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { + return; + } + if (notification == nullptr) { + return; + } + NotificationRequest request = notification->GetNotificationRequest(); + std::string label = request.GetLabel(); + int64_t autoDeletedTime = request.GetAutoDeletedTime(); + if (autoDeletedTime <= 0 || label != NOTIFICATION_LABEL) { + return; + } + + if (reminderDataManager_ == nullptr) { + return; + } + int32_t notificationId = request.GetNotificationId(); + int32_t uid = request.GetOwnerUid() == 0 ? request.GetCreatorUid() : request.GetOwnerUid(); + reminderDataManager_->HandleAutoDeleteReminder(notificationId, uid, autoDeletedTime); +} + +void ReminderEventManager::ReminderNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, + const std::shared_ptr &sortingMap) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnUpdate( + const std::shared_ptr &sortingMap) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnDied() {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnDoNotDisturbDateChange( + const std::shared_ptr &date) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeChanged( + const std::shared_ptr &badgeData) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeEnabledChanged( + const sptr &callbackData) {} + +void ReminderEventManager::ReminderNotificationSubscriber::OnBatchCanceled( + const std::vector> &requestList, + const std::shared_ptr &sortingMap, int32_t deleteReason) {} +} // namespace OHOS +} // namespace Notification diff --git a/services/reminder/src/reminder_notification_inline.cpp b/services/reminder/src/reminder_notification_inline.cpp new file mode 100644 index 000000000..b6093427c --- /dev/null +++ b/services/reminder/src/reminder_notification_inline.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2021-2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "reminder_access_token_helper.h" +#include "ans_permission_def.h" +#include "reminder_bundle_manager_helper.h" +#include "errors.h" +#include "ipc_skeleton.h" +#include "notification_constant.h" + +namespace OHOS { +namespace Notification { +inline std::string GetClientBundleNameByUid(int32_t callingUid) +{ + std::string bundle; + + std::shared_ptr bundleManager = ReminderBundleManagerHelper::GetInstance(); + if (bundleManager != nullptr) { + bundle = bundleManager->GetBundleNameByUid(callingUid); + } + + return bundle; +} + +inline std::string GetClientBundleName() +{ + return GetClientBundleNameByUid(IPCSkeleton::GetCallingUid()); +} + +inline int64_t ResetSeconds(int64_t date) +{ + auto milliseconds = std::chrono::milliseconds(date); + auto tp = std::chrono::time_point(milliseconds); + auto tp_minutes = std::chrono::time_point_cast(tp); + auto duration = std::chrono::duration_cast(tp_minutes.time_since_epoch()); + return duration.count(); +} + +inline int64_t GetCurrentTime() +{ + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + return duration.count(); +} + +inline tm GetLocalTime(time_t time) +{ + struct tm ret = {0}; + localtime_r(&time, &ret); + return ret; +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_os_account_manager_helper.cpp b/services/reminder/src/reminder_os_account_manager_helper.cpp new file mode 100644 index 000000000..a7a46f38e --- /dev/null +++ b/services/reminder/src/reminder_os_account_manager_helper.cpp @@ -0,0 +1,49 @@ +/* + * Copyright (c) 2022 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 "reminder_os_account_manager_helper.h" +#include "ans_log_wrapper.h" +#include "ans_inner_errors.h" +#include "errors.h" +#include "ipc_skeleton.h" + +#include "os_account_constants.h" +#include "os_account_info.h" +#include "os_account_manager.h" +#include + +namespace OHOS { +namespace Notification { +ErrCode ReminderOsAccountManagerHelper::GetOsAccountLocalIdFromUid(const int32_t uid, int32_t &userId) +{ + int32_t ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + if (ret != ERR_OK) { + ANS_LOGE("Get userId failed, uid = <%{public}d>, code is %{public}d", uid, ret); + return ret; + } + ANS_LOGD("Get userId Success, uid = <%{public}d> userId = <%{public}d>", uid, userId); + return ret; +} + +ErrCode ReminderOsAccountManagerHelper::GetCurrentActiveUserId(int32_t &id) +{ + int32_t ret = OHOS::AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(id); + if (ret != ERR_OK) { + ANS_LOGE("Failed to call OsAccountManager::GetForegroundOsAccountLocalId, code is %{public}d", ret); + } + return ret; +} +} +} diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp new file mode 100644 index 000000000..d37c81378 --- /dev/null +++ b/services/reminder/src/reminder_service.cpp @@ -0,0 +1,325 @@ +/* + * Copyright (c) 2021-2023 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 "reminder_service.h" + +#include "reminder_request_timer.h" +#include "reminder_request_calendar.h" +#include "reminder_request_alarm.h" +#include "reminder_bundle_manager_helper.h" +#include "reminder_access_token_helper.h" +#include "reminder_notification_inline.cpp" + + +#include +#include +#include + +#include "accesstoken_kit.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "errors.h" + +#include "ipc_skeleton.h" +#include "notification_constant.h" +#include "notification_request.h" +#include "os_account_manager.h" +#include "hitrace_meter_adapter.h" +#include "reminder_data_manager.h" +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +#include "distributed_notification_manager.h" +#include "distributed_preferences.h" +#include "distributed_screen_status_manager.h" +#endif + +namespace OHOS { +namespace Notification { +inline bool ReminderService::CheckReminderPermission() +{ + Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); + ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken( + callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER"); + return result == Security::AccessToken::PermissionState::PERMISSION_GRANTED; +} + +ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_t& reminderId) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Publish reminder"); + sptr tarReminder = nullptr; + switch (reminder.GetReminderType()) { + case (ReminderRequest::ReminderType::TIMER): { + ANSR_LOGI("Publish timer"); + ReminderRequestTimer &timer = (ReminderRequestTimer &)reminder; + tarReminder = new (std::nothrow) ReminderRequestTimer(timer); + break; + } + case (ReminderRequest::ReminderType::ALARM): { + ANSR_LOGI("Publish alarm"); + ReminderRequestAlarm &alarm = (ReminderRequestAlarm &)reminder; + tarReminder = new (std::nothrow) ReminderRequestAlarm(alarm); + break; + } + case (ReminderRequest::ReminderType::CALENDAR): { + ANSR_LOGI("Publish calendar"); + ReminderRequestCalendar &calendar = (ReminderRequestCalendar &)reminder; + tarReminder = new (std::nothrow) ReminderRequestCalendar(calendar); + break; + } + default: { + ANSR_LOGW("PublishReminder fail."); + return ERR_ANS_INVALID_PARAM; + } + } + if (!tarReminder) { + ANSR_LOGE("ReminderRequest object is nullptr"); + return ERR_ANS_INVALID_PARAM; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::string bundle = GetClientBundleName(); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + // if (!AllowUseReminder(bundle)) { + // ANSR_LOGW("The number of reminders exceeds the limit[0]."); + // return ERR_REMINDER_NUMBER_OVERLOAD; + // } + ANSR_LOGD("is system app: %{public}d", ReminderAccessTokenHelper::IsSystemApp()); + tarReminder->SetSystemApp(ReminderAccessTokenHelper::IsSystemApp()); + sptr notificationRequest = reminder.GetNotificationRequest(); + tarReminder->InitCreatorBundleName(bundle); + tarReminder->InitCreatorUid(callingUid); + if (tarReminder->GetWantAgentInfo() == nullptr || tarReminder->GetMaxScreenWantAgentInfo() == nullptr) { + ANSR_LOGE("wantagent info is nullptr"); + return ERR_ANS_INVALID_PARAM; + } + std::string wantAgentName = tarReminder->GetWantAgentInfo()->pkgName; + std::string msWantAgentName = tarReminder->GetMaxScreenWantAgentInfo()->pkgName; + if (wantAgentName != msWantAgentName && wantAgentName != "" && msWantAgentName != "") { + ANSR_LOGE("wantAgentName is not same to msWantAgentName, wantAgentName:%{public}s, msWantAgentName:%{public}s", + wantAgentName.c_str(), msWantAgentName.c_str()); + return ERR_ANS_INVALID_PARAM; + } + if (wantAgentName != bundle && wantAgentName != "") { + ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(), + wantAgentName.c_str()); + // SetAgentNotification(notificationRequest, wantAgentName); + } else if (msWantAgentName != bundle && msWantAgentName != "") { + ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(), + msWantAgentName.c_str()); + // SetAgentNotification(notificationRequest, msWantAgentName); + } + // ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); + // if (result != ERR_OK) { + // ANSR_LOGW("PrepareNotificationInfo fail"); + // return result; + // } + // bool allowedNotify = false; + // result = IsAllowedNotifySelf(bundleOption, allowedNotify); + // if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { + // ANSR_LOGW("The application does not request enable notification"); + // return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; + // } + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + int32_t ret = rdm->PublishReminder(tarReminder, callingUid); + if (ret == ERR_OK) { + reminderId = tarReminder->GetReminderId(); + } + return ret; +} + +ErrCode ReminderService::CancelReminder(const int32_t reminderId) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Cancel Reminder"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + return rdm->CancelReminder(reminderId, callingUid); +} + +ErrCode ReminderService::CancelAllReminders() +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Cancel all reminders"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + int32_t userId = -1; + AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + return rdm->CancelAllReminders(userId, callingUid); +} + + +ErrCode ReminderService::GetValidReminders(std::vector &reminders) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("GetValidReminders"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + + reminders.clear(); + int32_t callingUid = IPCSkeleton::GetCallingUid(); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + rdm->GetValidReminders(callingUid, reminders); + ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); + return ERR_OK; +} + +ErrCode ReminderService::AddExcludeDate(const int32_t reminderId, const int64_t date) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Add Exclude Date"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + ANSR_LOGW("Reminder data manager not init!"); + return ERR_NO_INIT; + } + return rdm->AddExcludeDate(reminderId, date, callingUid); +} + +ErrCode ReminderService::DelExcludeDates(const int32_t reminderId) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Del Exclude Dates"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + + int32_t callingUid = IPCSkeleton::GetCallingUid(); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + ANSR_LOGW("Reminder data manager not init!"); + return ERR_NO_INIT; + } + return rdm->DelExcludeDates(reminderId, callingUid); +} + +ErrCode ReminderService::GetExcludeDates(const int32_t reminderId, std::vector& dates) +{ + HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); + ANSR_LOGI("Get Exclude Dates"); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + ANSR_LOGW("Reminder data manager not init!"); + return ERR_NO_INIT; + } + return rdm->GetExcludeDates(reminderId, callingUid, dates); +} + +// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +// NotificationConstant::RemindType ReminderService::GetRemindType() +// { +// bool remind = localScreenOn_; +// if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DEFAULT) { +// bool remoteUsing = false; +// ErrCode result = DistributedScreenStatusManager::GetInstance()->CheckRemoteDevicesIsUsing(remoteUsing); +// if (result != ERR_OK) { +// remind = true; +// } +// if (!localScreenOn_ && !remoteUsing) { +// remind = true; +// } +// } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::ALWAYS_REMIND) { +// remind = true; +// } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DO_NOT_REMIND) { +// remind = false; +// } + +// if (localScreenOn_) { +// if (remind) { +// return NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; +// } else { +// return NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND; +// } +// } else { +// if (remind) { +// return NotificationConstant::RemindType::DEVICE_IDLE_REMIND; +// } else { +// return NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND; +// } +// } +// } +// #endif + +// ErrCode ReminderService::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +// { +// ANS_LOGD("%{public}s", __FUNCTION__); + +// bool isSubsystem = ReminderAccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); +// if (!isSubsystem && !ReminderAccessTokenHelper::IsSystemApp()) { +// return ERR_ANS_NON_SYSTEM_APP; +// } + +// if (!ReminderAccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { +// return ERR_ANS_PERMISSION_DENIED; +// } + +// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +// if (notificationSvrQueue_ == nullptr) { +// ANS_LOGE("Serial queue is invalid."); +// return ERR_ANS_INVALID_PARAM; +// } +// ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { remindType = GetRemindType(); })); +// notificationSvrQueue_->wait(handler); +// return ERR_OK; +// #else +// return ERR_INVALID_OPERATION; +// #endif +// } + +// ErrCode ReminderService::SetNotificationRemindType(sptr notification, bool isLocal) +// { +// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +// notification->SetRemindType(GetRemindType()); +// #else +// notification->SetRemindType(NotificationConstant::RemindType::NONE); +// #endif +// return ERR_OK; +// } +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp new file mode 100644 index 000000000..a91662f04 --- /dev/null +++ b/services/reminder/src/reminder_service_ability.cpp @@ -0,0 +1,136 @@ +// /* +// * 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 "reminder_service_ability.h" +// // #include "system_event_observer.h" +// // #include "common_event_manager.h" + +// namespace OHOS { +// namespace Notification { +// namespace { +// REGISTER_SYSTEM_ABILITY_BY_ID(ReminderServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); +// } + +// const std::string EXTENSION_BACKUP = "backup"; +// const std::string EXTENSION_RESTORE = "restore"; + +// ReminderServiceAbility::ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate) +// : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) +// {} + +// ReminderServiceAbility::~ReminderServiceAbility() +// {} + +// void ReminderServiceAbility::OnStart() +// { +// if (service_ != nullptr) { +// return; +// } + +// service_ = ReminderService::GetInstance(); +// if (!Publish(service_)) { +// return; +// } +// // service_->CreateDialogManager(); +// // service_->InitPublishProcess(); +// reminderAgent_ = ReminderDataManager::InitInstance(service_); + +// // #ifdef ENABLE_ANS_EXT_WRAPPER +// // EXTENTION_WRAPPER->InitExtentionWrapper(); +// // AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); +// // AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); +// // #else +// ANS_LOGI("Not enabled ans_ext"); +// #endif + +// // #ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER +// // TEL_EXTENTION_WRAPPER->InitTelExtentionWrapper(); +// // #endif +// } + +// void ReminderServiceAbility::OnStop() +// { +// service_ = nullptr; +// reminderAgent_ = nullptr; +// } + +// void ReminderServiceAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) +// { +// ANS_LOGD("SubSystemAbilityListener::OnAddSystemAbility enter !"); +// if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { +// if (AdvancedDatashareObserver::GetInstance().CheckIfSettingsDataReady()) { +// if (isDatashaReready_) { +// return; +// } +// EXTENTION_WRAPPER->CheckIfSetlocalSwitch(); +// isDatashaReready_ = true; +// } +// } else if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { +// if (isDatashaReready_) { +// return; +// } +// EventFwk::MatchingSkills matchingSkills; +// matchingSkills.AddEvent("usual.event.DATA_SHARE_READY"); +// EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); +// subscriber_ = std::make_shared( +// subscribeInfo, std::bind(&ReminderServiceAbility::OnReceiveEvent, this, std::placeholders::_1)); +// if (subscriber_ == nullptr) { +// ANS_LOGD("subscriber_ is nullptr"); +// return; +// } +// EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); +// } +// } + +// // void ReminderServiceAbility::OnReceiveEvent(const EventFwk::CommonEventData &data) +// // { +// // ANS_LOGI("CheckIfSettingsDataReady() ok!"); +// // if (isDatashaReready_) { +// // return; +// // } +// // auto const &want = data.GetWant(); +// // std::string action = want.GetAction(); +// // if (action == "usual.event.DATA_SHARE_READY") { +// // isDatashaReready_ = true; +// // ANS_LOGI("COMMON_EVENT_SERVICE_ID OnReceiveEvent ok!"); +// // EXTENTION_WRAPPER->CheckIfSetlocalSwitch(); +// // } +// // } + +// void ReminderServiceAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) +// { +// if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { +// return; +// } +// } + +// int32_t ReminderServiceAbility::OnExtension(const std::string& extension, +// MessageParcel& data, MessageParcel& reply) +// { +// ANS_LOGI("extension is %{public}s.", extension.c_str()); +// auto notificationService = ReminderService::GetInstance(); +// if (notificationService == nullptr) { +// ANS_LOGW("notification service is not initial."); +// return ERR_OK; +// } +// if (extension == EXTENSION_BACKUP) { +// return notificationService->OnBackup(data, reply); +// } else if (extension == EXTENSION_RESTORE) { +// return notificationService->OnRestore(data, reply); +// } +// return ERR_OK; +// } +// } // namespace Notification +// } // namespace OHOS diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp new file mode 100644 index 000000000..7bedc5055 --- /dev/null +++ b/services/reminder/src/reminder_store.cpp @@ -0,0 +1,809 @@ +/* + * Copyright (c) 2022 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 "reminder_store.h" + +#include +#include +#include +#include + +#include "fa_ability_context.h" +#include "ans_log_wrapper.h" +#include "reminder_table.h" +#include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" +#include "reminder_request_calendar.h" +#include "reminder_store_strategy.h" + +namespace OHOS { +namespace Notification { +namespace { +const int32_t REMINDER_RDB_VERSION_V1 = 1; +const int32_t REMINDER_RDB_VERSION_V2 = 2; +const int32_t REMINDER_RDB_VERSION_V3 = 3; +const int32_t REMINDER_RDB_VERSION_V4 = 4; +const int32_t REMINDER_RDB_VERSION_V5 = 5; +const int32_t REMINDER_RDB_VERSION_V6 = 6; +const int32_t REMINDER_RDB_VERSION = 7; +} + +const int32_t ReminderStore::STATE_OK = 0; +const int32_t ReminderStore::STATE_FAIL = -1; +const std::string ReminderStore::REMINDER_DB_DIR = "/data/service/el1/public/notification/"; +const std::string ReminderStore::REMINDER_DB_NAME = "notification.db"; + +int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore& store) +{ + ANSR_LOGI("Create table"); + return CreateTable(store); +} + +int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade( + NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) +{ + ANSR_LOGI("OnUpgrade oldVersion is %{public}d, newVersion is %{public}d", oldVersion, newVersion); + if (oldVersion < newVersion && newVersion == REMINDER_RDB_VERSION) { + switch (oldVersion) { + case REMINDER_RDB_VERSION_V1: + AddRdbColum(store, ReminderTable::TABLE_NAME, "groupId", "TEXT", "''"); + [[fallthrough]]; + case REMINDER_RDB_VERSION_V2: + AddRdbColum(store, ReminderTable::TABLE_NAME, "custom_ring_uri", "TEXT", "''"); + AddRdbColum(store, ReminderTable::TABLE_NAME, "snooze_slot_id", "INT", "3"); + [[fallthrough]]; + case REMINDER_RDB_VERSION_V3: + AddRdbColum(store, ReminderTable::TABLE_NAME, "creator_bundle_name", "TEXT", "''"); + [[fallthrough]]; + case REMINDER_RDB_VERSION_V4: + CreateTable(store); + CopyData(store); + [[fallthrough]]; + case REMINDER_RDB_VERSION_V5: + AddRdbColum(store, ReminderBaseTable::TABLE_NAME, ReminderBaseTable::CREATOR_UID, "INT", "-1"); + [[fallthrough]]; + case REMINDER_RDB_VERSION_V6: + AddRdbColum(store, ReminderCalendarTable::TABLE_NAME, + ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, "BIGINT", "0"); + [[fallthrough]]; + default: + break; + } + } + store.SetVersion(newVersion); + return NativeRdb::E_OK; +} + +int32_t ReminderStore::ReminderStoreDataCallBack::OnDowngrade( + NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) +{ + ANSR_LOGI("OnDowngrade currentVersion is %{public}d, targetVersion is %{public}d", currentVersion, targetVersion); + if (currentVersion > targetVersion && targetVersion <= REMINDER_RDB_VERSION_V4) { + std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTable::TABLE_NAME + " (" + + ReminderTable::ADD_COLUMNS + ")"; + int32_t ret = store.ExecuteSql(createSql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Create reminder table failed:%{public}d", ret); + } + return ret; + } + store.SetVersion(targetVersion); + return NativeRdb::E_OK; +} + +int32_t ReminderStore::ReminderStoreDataCallBack::CreateTable(NativeRdb::RdbStore& store) +{ + std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderBaseTable::TABLE_NAME + " (" + + ReminderBaseTable::ADD_COLUMNS + ")"; + int32_t ret = store.ExecuteSql(createSql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Create reminder_base table failed:%{public}d", ret); + return ret; + } + + createSql = "CREATE TABLE IF NOT EXISTS " + ReminderAlarmTable::TABLE_NAME + " (" + + ReminderAlarmTable::ADD_COLUMNS + ")"; + ret = store.ExecuteSql(createSql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Create reminder_alarm table failed:%{public}d", ret); + return ret; + } + + createSql = "CREATE TABLE IF NOT EXISTS " + ReminderCalendarTable::TABLE_NAME + " (" + + ReminderCalendarTable::ADD_COLUMNS + ")"; + ret = store.ExecuteSql(createSql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Create reminder_calendar table failed:%{public}d", ret); + return ret; + } + + createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTimerTable::TABLE_NAME + " (" + + ReminderTimerTable::ADD_COLUMNS + ")"; + ret = store.ExecuteSql(createSql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Create reminder_timer table failed:%{public}d", ret); + return ret; + } + return ret; +} + +int32_t ReminderStore::ReminderStoreDataCallBack::CopyData(NativeRdb::RdbStore& store) +{ + // select old data + auto reminders = GetOldReminders(store); + // insert new data + if (!reminders.empty()) { + InsertNewReminders(store, reminders); + } + // delete old table + std::string sql = "DELETE FROM " + ReminderTable::TABLE_NAME; + store.ExecuteSql(sql); + return NativeRdb::E_OK; +} + +std::vector> ReminderStore::ReminderStoreDataCallBack::GetOldReminders(NativeRdb::RdbStore& store) +{ + std::string sql = "SELECT " + ReminderTable::SELECT_COLUMNS + " FROM " + + ReminderTable::TABLE_NAME; + std::vector> reminders; + std::vector whereArgs; + auto queryResult = store.QuerySql(sql, whereArgs); + if (queryResult == nullptr) { + return reminders; + } + + bool isLastRow = false; + queryResult->IsAtLastRow(isLastRow); + while (!isLastRow) { + queryResult->GoToNextRow(); + int32_t reminderId; + int32_t reminderType; + GetInt32Val(queryResult, ReminderTable::REMINDER_ID, reminderId); + GetInt32Val(queryResult, ReminderTable::REMINDER_TYPE, reminderType); + + sptr reminderReq = nullptr; + switch (reminderType) { + case (static_cast(ReminderRequest::ReminderType::TIMER)): { + reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); + ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); + break; + } + case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { + reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); + ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); + break; + } + case (static_cast(ReminderRequest::ReminderType::ALARM)): { + reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); + ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); + break; + } + default: { + break; + } + } + if (reminderReq != nullptr) { + reminders.push_back(reminderReq); + } + queryResult->IsAtLastRow(isLastRow); + } + return reminders; +} + +void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::RdbStore& store, + const std::vector>& reminders) +{ + for (auto reminder : reminders) { + int64_t rowId = STATE_FAIL; + NativeRdb::ValuesBucket baseValues; + ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); + + store.BeginTransaction(); + // insert reminder_base + int32_t ret = store.Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + store.RollBack(); + continue; + } + + // insert reminder_alarm or reminder_calendar + NativeRdb::ValuesBucket values; + rowId = STATE_FAIL; + switch (reminder->GetReminderType()) { + case ReminderRequest::ReminderType::CALENDAR: + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); + ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); + break; + case ReminderRequest::ReminderType::ALARM: + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); + ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); + break; + case ReminderRequest::ReminderType::TIMER: + ReminderTimerStrategy::AppendValuesBucket(reminder, values); + ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); + break; + default: + ANSR_LOGE("Insert reminder_base operation failed, unkown type."); + ret = STATE_FAIL; + break; + } + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + store.RollBack(); + continue; + } + store.Commit(); + ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); + } +} + +void ReminderStore::ReminderStoreDataCallBack::AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, + const std::string& columnName, const std::string& columnType, const std::string& defValue) +{ + std::string sqlStr = ""; + sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType + " DEFAULT " + defValue + ";"; + ANSR_LOGD("AddRdbColum sqlStr = %{public}s", sqlStr.c_str()); + int errorCode = store.ExecuteSql(sqlStr); + if (errorCode != NativeRdb::E_OK) { + ANSR_LOGE("AddRdbColum error,errorCode is = %{public}d", errorCode); + } +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Init() +{ + ANSR_LOGD("Reminder store init."); + if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) { + int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU); + if (createDir != 0) { + ANSR_LOGE("Failed to create directory %{private}s", REMINDER_DB_DIR.c_str()); + return STATE_FAIL; + } + } + + ReminderTable::InitDbColumns(); + ReminderBaseTable::InitDbColumns(); + ReminderTimerTable::InitDbColumns(); + ReminderAlarmTable::InitDbColumns(); + ReminderCalendarTable::InitDbColumns(); + + std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME; + NativeRdb::RdbStoreConfig config(dbConfig); + config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); + + ReminderStoreDataCallBack rdbDataCallBack; + int32_t errCode = STATE_FAIL; + rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, REMINDER_RDB_VERSION, rdbDataCallBack, errCode); + if (rdbStore_ == nullptr) { + ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode); + return STATE_FAIL; + } + return InitData(); +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const int32_t reminderId) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + std::string condition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); + rdbStore_->BeginTransaction(); + int32_t delRows = STATE_FAIL; + std::vector whereArgs; + int32_t ret = rdbStore_->Delete(delRows, ReminderBaseTable::TABLE_NAME, condition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", + ReminderBaseTable::TABLE_NAME.c_str(), reminderId); + rdbStore_->RollBack(); + return STATE_FAIL; + } + delRows = STATE_FAIL; + ret = rdbStore_->Delete(delRows, ReminderAlarmTable::TABLE_NAME, condition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", + ReminderAlarmTable::TABLE_NAME.c_str(), reminderId); + rdbStore_->RollBack(); + return STATE_FAIL; + } + delRows = STATE_FAIL; + ret = rdbStore_->Delete(delRows, ReminderCalendarTable::TABLE_NAME, condition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", + ReminderCalendarTable::TABLE_NAME.c_str(), reminderId); + rdbStore_->RollBack(); + return STATE_FAIL; + } + delRows = STATE_FAIL; + ret = rdbStore_->Delete(delRows, ReminderTimerTable::TABLE_NAME, condition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", + ReminderTimerTable::TABLE_NAME.c_str(), reminderId); + rdbStore_->RollBack(); + return STATE_FAIL; + } + rdbStore_->Commit(); + return STATE_OK; +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& pkg, const int32_t userId, + const int32_t uid) +{ + std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME + + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + + std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " + + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + + if (uid != -1) { + assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID + + " = " + std::to_string(uid); + baseCondtion += " AND " + ReminderBaseTable::UID + " = " + std::to_string(uid); + } + assoConditon += ")"; + return Delete(baseCondtion, assoConditon); +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteUser(const int32_t userId) +{ + std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME + + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + + std::to_string(userId) + ")"; + + std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + return Delete(baseCondtion, assoConditon); +} + +int32_t ReminderStore::UpdateOrInsert( + const sptr& reminder) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + if (IsReminderExist(reminder)) { + return Update(reminder); + } else { + return Insert(reminder); + } +} + +int32_t ReminderStore::GetMaxId() +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + std::string queryCondition = "SELECT " + ReminderBaseTable::REMINDER_ID + + " FROM " + ReminderBaseTable::TABLE_NAME + " ORDER BY " + + ReminderBaseTable::REMINDER_ID + " DESC"; + auto queryResultSet = Query(queryCondition); + if (queryResultSet == nullptr) { + ANSR_LOGE("QueryResultSet is null."); + return STATE_FAIL; + } + int32_t resultNum = 0; + queryResultSet->GetRowCount(resultNum); + if (resultNum == 0) { + ANSR_LOGI("QueryResultSet is zero."); + return STATE_FAIL; + } + queryResultSet->GoToNextRow(); + int32_t maxId = STATE_FAIL; + int32_t result = queryResultSet->GetInt(0, maxId); + if (result != NativeRdb::E_OK) { + ANSR_LOGE("Query operation failed, result %{public}d.", result); + } + ANSR_LOGD("MaxId: %{public}d.", maxId); + return maxId; +} + +__attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() +{ + std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " + + ReminderBaseTable::TABLE_NAME + " WHERE " + + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " + + ReminderBaseTable::TRIGGER_TIME + " ASC"; + ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); + return GetReminders(sql); +} + +void ReminderStore::GetUInt8Val(const std::shared_ptr& resultSet, + const std::string& name, uint8_t& value) +{ + int32_t val; + GetInt32Val(resultSet, name, val); + value = static_cast(val); +} + +void ReminderStore::GetUInt16Val(const std::shared_ptr& resultSet, + const std::string& name, uint16_t& value) +{ + int32_t val; + GetInt32Val(resultSet, name, val); + value = static_cast(val); +} + +void ReminderStore::GetInt32Val(const std::shared_ptr& resultSet, + const std::string& name, int32_t& value) +{ + value = 0; + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + resultSet->GetInt(columnIndex, value); +} + +void ReminderStore::GetInt64Val(const std::shared_ptr& resultSet, + const std::string& name, int64_t& value) +{ + value = 0; + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + resultSet->GetLong(columnIndex, value); +} + +void ReminderStore::GetUInt64Val(const std::shared_ptr& resultSet, + const std::string& name, uint64_t& value) +{ + int64_t val; + GetInt64Val(resultSet, name, val); + value = static_cast(val); +} + +void ReminderStore::GetStringVal(const std::shared_ptr& resultSet, + const std::string& name, std::string& value) +{ + int32_t columnIndex = -1; + resultSet->GetColumnIndex(name, columnIndex); + if (columnIndex == -1) { + ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); + return; + } + resultSet->GetString(columnIndex, value); +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::InitData() +{ + ANSR_LOGD("Reminder data init."); + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + // delete all the reminders which IS_EXPIRED is true. + std::string deleteCondition = ReminderBaseTable::IS_EXPIRED + " is true"; + DeleteBase(deleteCondition); + + // set all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE + NativeRdb::ValuesBucket statusValues; + statusValues.PutInt(ReminderBaseTable::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE); + int32_t statusChangedRows = STATE_FAIL; + int32_t ret = rdbStore_->Update(statusChangedRows, ReminderBaseTable::TABLE_NAME, statusValues); + ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Init data failed."); + return STATE_FAIL; + } + return STATE_OK; +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteBase(const std::string& deleteCondition) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int32_t deletedRows = STATE_FAIL; + std::vector whereArgs; + int32_t ret = rdbStore_->Delete(deletedRows, ReminderBaseTable::TABLE_NAME, deleteCondition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \ + "result: %{public}d.", deleteCondition.c_str(), ret); + } + ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \ + "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows); + return deletedRows; +} + +__attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& baseCondition, + const std::string& assoConditon) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + rdbStore_->BeginTransaction(); + // delete reminder_calendar + std::string sql = "DELETE FROM " + ReminderCalendarTable::TABLE_NAME + " WHERE " + + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::REMINDER_ID + + " IN " + assoConditon; + int32_t ret = rdbStore_->ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + + // delete reminder_alarm + sql = "DELETE FROM " + ReminderAlarmTable::TABLE_NAME + " WHERE " + + ReminderAlarmTable::TABLE_NAME + "." + ReminderAlarmTable::REMINDER_ID + + " IN " + assoConditon; + ret = rdbStore_->ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + + // delete reminder_timer + sql = "DELETE FROM " + ReminderTimerTable::TABLE_NAME + " WHERE " + + ReminderTimerTable::TABLE_NAME + "." + ReminderTimerTable::REMINDER_ID + + " IN " + assoConditon; + ret = rdbStore_->ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed", ReminderTimerTable::TABLE_NAME.c_str()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + + // delete reminder_base + sql = "DELETE FROM " + ReminderBaseTable::TABLE_NAME + " WHERE " + baseCondition; + ret = rdbStore_->ExecuteSql(sql); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + rdbStore_->Commit(); + return STATE_OK; +} + +int32_t ReminderStore::Insert(const sptr& reminder) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int64_t rowId = STATE_FAIL; + NativeRdb::ValuesBucket baseValues; + ReminderStrategy::AppendValuesBucket(reminder, baseValues); + + rdbStore_->BeginTransaction(); + // insert reminder_base + int32_t ret = rdbStore_->Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + + // insert reminder_alarm or reminder_calendar + NativeRdb::ValuesBucket values; + rowId = STATE_FAIL; + switch (reminder->GetReminderType()) { + case ReminderRequest::ReminderType::CALENDAR: { + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); + break; + } + case ReminderRequest::ReminderType::ALARM: { + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); + break; + } + case ReminderRequest::ReminderType::TIMER: { + ReminderTimerStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); + break; + } + default: { + ANSR_LOGE("Insert reminder_base operation failed, unkown type."); + ret = STATE_FAIL; + break; + } + } + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + rdbStore_->Commit(); + ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); + return STATE_OK; +} + +int32_t ReminderStore::Update( + const sptr& reminder) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return STATE_FAIL; + } + int32_t rowId = STATE_FAIL; + NativeRdb::ValuesBucket baseValues; + ReminderStrategy::AppendValuesBucket(reminder, baseValues); + + std::string updateCondition = ReminderBaseTable::REMINDER_ID + + " = " + std::to_string(reminder->GetReminderId()); + + rdbStore_->BeginTransaction(); + // update reminder_base + std::vector whereArgs; + int32_t ret = rdbStore_->Update(rowId, ReminderBaseTable::TABLE_NAME, baseValues, updateCondition, whereArgs); + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Update reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + + // update reminder_alarm or reminder_calendar + NativeRdb::ValuesBucket values; + rowId = STATE_FAIL; + switch (reminder->GetReminderType()) { + case ReminderRequest::ReminderType::CALENDAR: + ReminderCalendarStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); + break; + case ReminderRequest::ReminderType::ALARM: + ReminderAlarmStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); + break; + case ReminderRequest::ReminderType::TIMER: + ReminderTimerStrategy::AppendValuesBucket(reminder, values); + ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); + break; + default: + ANSR_LOGE("Insert reminder_base operation failed, unkown type."); + ret = STATE_FAIL; + break; + } + if (ret != NativeRdb::E_OK) { + ANSR_LOGE("Update operation failed, result: %{public}d, reminderId=%{public}d.", + ret, reminder->GetReminderId()); + rdbStore_->RollBack(); + return STATE_FAIL; + } + rdbStore_->Commit(); + ANSR_LOGD("Update successfully, reminderId=%{public}d.", reminder->GetReminderId()); + return STATE_OK; +} + +bool ReminderStore::IsReminderExist(const sptr& reminder) +{ + NativeRdb::AbsRdbPredicates absRdbPredicates(ReminderBaseTable::TABLE_NAME); + absRdbPredicates.EqualTo(ReminderBaseTable::REMINDER_ID, std::to_string(reminder->GetReminderId())); + auto queryResultSet = rdbStore_->Query(absRdbPredicates, std::vector()); + if (queryResultSet == nullptr) { + ANSR_LOGE("QueryResultSet is null."); + return false; + } + int32_t resultNum; + queryResultSet->GetRowCount(resultNum); + return resultNum != 0; +} + +std::vector> ReminderStore::GetReminders(const std::string& queryCondition) +{ + std::vector> reminders; + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return reminders; + } + auto queryResultSet = Query(queryCondition); + if (queryResultSet == nullptr) { + return reminders; + } + bool isAtLastRow = false; + queryResultSet->IsAtLastRow(isAtLastRow); + while (!isAtLastRow) { + queryResultSet->GoToNextRow(); + sptr reminder = BuildReminder(queryResultSet); + if (reminder != nullptr) { + reminders.push_back(reminder); + } + queryResultSet->IsAtLastRow(isAtLastRow); + } + ANSR_LOGD("Size=%{public}zu", reminders.size()); + return reminders; +} + +sptr ReminderStore::BuildReminder(const std::shared_ptr& resultBase) +{ + int32_t reminderId; + int32_t reminderType; + GetInt32Val(resultBase, ReminderBaseTable::REMINDER_ID, reminderId); + GetInt32Val(resultBase, ReminderBaseTable::REMINDER_TYPE, reminderType); + + sptr reminder = nullptr; + std::shared_ptr resultSet; + switch (reminderType) { + case (static_cast(ReminderRequest::ReminderType::TIMER)): { + reminder = new (std::nothrow) ReminderRequestTimer(reminderId); + resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); + ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); + break; + } + case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { + reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); + resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); + ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); + break; + } + case (static_cast(ReminderRequest::ReminderType::ALARM)): { + reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); + resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); + ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); + break; + } + default: { + ANSR_LOGE("ReminderType from database is error, reminderType %{public}d.", reminderType); + break; + } + } + if (reminder != nullptr) { + ANSR_LOGI("BuildReminder success."); + } else { + ANSR_LOGW("BuildReminder fail."); + } + return reminder; +} + +std::shared_ptr ReminderStore::Query(const std::string& tableName, const std::string& colums, + const int32_t reminderId) +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return nullptr; + } + std::string queryCondition = "SELECT " + colums + " FROM " + tableName + + " WHERE " + ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); + auto queryResultSet = Query(queryCondition); + if (queryResultSet == nullptr) { + return nullptr; + } + int32_t resultNum = 0; + queryResultSet->GetRowCount(resultNum); + if (resultNum == 0) { + return nullptr; + } + queryResultSet->GoToNextRow(); + return queryResultSet; +} + +std::shared_ptr ReminderStore::Query(const std::string& queryCondition) const +{ + if (rdbStore_ == nullptr) { + ANSR_LOGE("Rdb store is not initialized."); + return nullptr; + } + std::vector whereArgs; + return rdbStore_->QuerySql(queryCondition, whereArgs); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/src/reminder_store_strategy.cpp b/services/reminder/src/reminder_store_strategy.cpp new file mode 100644 index 000000000..814d85d3b --- /dev/null +++ b/services/reminder/src/reminder_store_strategy.cpp @@ -0,0 +1,649 @@ +/* + * Copyright (c) 2024 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 "reminder_store_strategy.h" + +#include "ans_log_wrapper.h" +#include "reminder_store.h" +#include "reminder_table.h" +#include "reminder_table_old.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" +#include "reminder_request_calendar.h" + +namespace OHOS { +namespace Notification { +void ReminderStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket &values, const bool oldVersion) +{ + values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); + values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); + values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); + values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); + values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); + values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); + values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); + values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); + values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); + values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); + values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); + values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); + values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); + values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); + values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->SerializeButtonInfo()); + values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); + values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); + values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); + values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); + values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); + values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); + values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); + values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); + + if (oldVersion) { + values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); + } else { + std::string wantInfoStr; + std::string maxWantInfoStr; + reminder->SerializeWantAgent(wantInfoStr, maxWantInfoStr); + values.PutString(ReminderBaseTable::WANT_AGENT, wantInfoStr); + values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantInfoStr); + } + + values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); + values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); + values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); + values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); + values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); + values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); +} + +void ReminderStrategy::RecoverTimeFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); +} + +void ReminderStrategy::RecoverContextFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::PKG_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + + ReminderStrategy::RecoverTimeFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverIdFromOldVersion(reminder, resultSet); + ReminderStrategy::RecoverContextFromOldVersion(reminder, resultSet); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SYS_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::STATE, state); + reminder->SetState(state); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + reminder->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AGENT, wantAgent); + reminder->SetWantAgentStr(wantAgent); + + std::string maxScreenWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); + reminder->SetMaxWantAgentStr(maxScreenWantAgent); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderStrategy::RecoverTimeFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + uint64_t reminderTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTime); + reminder->SetReminderTimeInMilli(reminderTime); + + uint64_t triggerTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTime); + reminder->SetTriggerTimeInMilli(triggerTime); + + uint64_t timeInterval = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TIME_INTERVAL, timeInterval); + reminder->SetTimeInterval(timeInterval); + + uint8_t snoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes); + reminder->SetSnoozeTimes(snoozeTimes); + + uint8_t dynamicSnoozeTimes = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); + reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); + + uint64_t ringDuration = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::RING_DURATION, ringDuration); + reminder->SetRingDuration(ringDuration); + + int64_t autoDeletedTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime); + reminder->SetAutoDeletedTime(autoDeletedTime); +} + +void ReminderStrategy::RecoverIdFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + int32_t reminderId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_ID, reminderId); + reminder->SetReminderId(reminderId); + + int32_t userId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::USER_ID, userId); + reminder->InitUserId(userId); + + int32_t uid = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::UID, uid); + reminder->InitUid(uid); + + int32_t reminderType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); + reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); + + int32_t slotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SLOT_ID, slotType); + reminder->SetSlotType(NotificationConstant::SlotType(slotType)); + + int32_t snoozeSlotType = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); + reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); + + int32_t notificationId = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId); + reminder->SetNotificationId(notificationId); + + std::string groupId; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::GROUP_ID, groupId); + reminder->SetGroupId(groupId); + + int32_t creatorUid; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid); + reminder->InitCreatorUid(creatorUid); +} + +void ReminderStrategy::RecoverContextFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + std::string bundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName); + reminder->InitBundleName(bundleName); + + std::string customButtonUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri); + reminder->SetCustomButtonUri(customButtonUri); + + std::string title; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TITLE, title); + reminder->SetTitle(title); + + std::string content; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CONTENT, content); + reminder->SetContent(content); + + std::string snoozeContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent); + reminder->SetSnoozeContent(snoozeContent); + + std::string expiredContent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent); + reminder->SetExpiredContent(expiredContent); + + std::string customRingUri; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri); + reminder->SetCustomRingUri(customRingUri); + + std::string creatorBundleName; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName); + reminder->InitCreatorBundleName(creatorBundleName); +} + +void ReminderStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder == nullptr || resultSet == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverTimeFromDb(reminder, resultSet); + ReminderStrategy::RecoverIdFromDb(reminder, resultSet); + ReminderStrategy::RecoverContextFromDb(reminder, resultSet); + + uint8_t state = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::STATE, state); + reminder->SetState(state); + + std::string isSystemApp; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SYSTEM_APP, isSystemApp); + reminder->SetSystemApp(isSystemApp == "true" ? true : false); + + std::string isExpired; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); + reminder->SetExpired(isExpired == "true" ? true : false); + + std::string actionButtons; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); + reminder->DeserializeButtonInfo(actionButtons); + + reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent + std::string wantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); + reminder->DeserializeWantAgent(wantAgent, 0); + + std::string maxWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantAgent); + reminder->DeserializeWantAgent(maxWantAgent, 1); + + std::string tapDismissed; + ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); + reminder->SetTapDismissed(tapDismissed == "true" ? true : false); +} + +void ReminderTimerStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint64_t seconds = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + seconds = timer->GetInitInfo(); + } + values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); + values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); + values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); + values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); +} + +void ReminderTimerStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); +} + +void ReminderTimerStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { + ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); + uint64_t seconds; + ReminderStrategy::GetRdbValue(resultSet, ReminderTimerTable::TRIGGER_SECOND, seconds); + timer->SetInitInfo(seconds); + } +} + +void ReminderAlarmStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint8_t hour = 0; + uint8_t minute = 0; + uint8_t repeatDaysOfWeek = 0; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + hour = alarm->GetHour(); + minute = alarm->GetMinute(); + repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); + } + values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); + values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); + values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); +} + +void ReminderAlarmStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + } +} + +void ReminderAlarmStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { + ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_HOUR, hour); + alarm->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute); + alarm->SetMinute(minute); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + alarm->SetRepeatDaysOfWeek(repeatDaysOfWeek); + } +} + +void ReminderCalendarStrategy::AppendValuesBucket(const sptr& reminder, + NativeRdb::ValuesBucket& values) +{ + uint16_t firstDesignateYear = 0; + uint8_t firstDesignateMonth = 0; + uint8_t firstDesignateDay = 0; + uint64_t dateTime = 0; + uint32_t repeatDay = 0; + uint16_t repeatMonth = 0; + uint8_t repeatDaysOfWeek = 0; + uint64_t endDateTime = 0; + uint64_t lastStartDateTime = 0; + std::string rruleWantAgent; + std::string excludeDates; + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + if (calendar != nullptr) { + repeatDay = calendar->GetRepeatDay(); + repeatMonth = calendar->GetRepeatMonth(); + firstDesignateYear = calendar->GetFirstDesignateYear(); + firstDesignateMonth = calendar->GetFirstDesignageMonth(); + firstDesignateDay = calendar->GetFirstDesignateDay(); + dateTime = calendar->GetDateTime(); + repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); + endDateTime = calendar->GetEndDateTime(); + lastStartDateTime = calendar->GetLastStartDateTime(); + rruleWantAgent = calendar->SerializationRRule(); + excludeDates = calendar->SerializationExcludeDates(); + } + } + values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); + values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); +} + +void ReminderCalendarStrategy::RecoverFromOldVersion(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint16_t year = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_YEAR, year); + calendar->SetYear(year); + + uint8_t month = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MONTH, month); + calendar->SetMonth(month); + + uint8_t day = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_DAY, day); + calendar->SetDay(day); + + uint8_t hour = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_HOUR, hour); + calendar->SetHour(hour); + + uint8_t minute = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MINUTE, minute); + calendar->SetMinute(minute); + } +} + +void ReminderCalendarStrategy::RecoverTime(sptr& reminder, + const std::shared_ptr& resultSet) +{ + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint16_t firstDesignateYear = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, + firstDesignateYear); + calendar->SetFirstDesignateYear(firstDesignateYear); + + uint8_t firstDesignateMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, + firstDesignateMonth); + calendar->SetFirstDesignageMonth(firstDesignateMonth); + + uint8_t firstDesignateDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, + firstDesignateDay); + calendar->SetFirstDesignateDay(firstDesignateDay); + + uint64_t dateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); + calendar->SetDateTime(dateTime); + + uint64_t endDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); + if (endDateTime != 0 && endDateTime >= dateTime) { + calendar->SetEndDateTime(endDateTime); + } else { + calendar->SetEndDateTime(dateTime); + } + + uint64_t lastStartDateTime = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, + lastStartDateTime); + if (lastStartDateTime == 0) { + calendar->SetLastStartDateTime(dateTime); + } else { + calendar->SetLastStartDateTime(lastStartDateTime); + } + } +} + +void ReminderCalendarStrategy::RecoverFromDb(sptr& reminder, + const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) +{ + if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { + ANSR_LOGE("ResultSet is null or reminder is null"); + return; + } + ReminderStrategy::RecoverFromDb(reminder, baseResult); + ReminderCalendarStrategy::RecoverTime(reminder, resultSet); + if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); + + uint32_t repeatDay = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); + calendar->SetRepeatDay(repeatDay); + + uint16_t repeatMonth = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); + calendar->SetRepeatMonth(repeatMonth); + + uint8_t repeatDaysOfWeek = 0; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); + calendar->SetRepeatDaysOfWeek(repeatDaysOfWeek); + + std::string rruleWantAgent; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); + calendar->DeserializationRRule(rruleWantAgent); + + std::string excludeDates; + ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); + calendar->DeserializationExcludeDates(excludeDates); + } +} +} +} \ No newline at end of file diff --git a/services/reminder/src/reminder_table.cpp b/services/reminder/src/reminder_table.cpp new file mode 100644 index 000000000..5e85b7289 --- /dev/null +++ b/services/reminder/src/reminder_table.cpp @@ -0,0 +1,178 @@ +/* + * Copyright (c) 2023 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 "reminder_table.h" + +namespace OHOS { +namespace Notification { +// reminder base table +const std::string ReminderBaseTable::TABLE_NAME = "reminder_base"; +const std::string ReminderBaseTable::REMINDER_ID = "reminder_id"; +const std::string ReminderBaseTable::PACKAGE_NAME = "package_name"; +const std::string ReminderBaseTable::USER_ID = "user_id"; +const std::string ReminderBaseTable::UID = "uid"; +const std::string ReminderBaseTable::SYSTEM_APP = "system_app"; +const std::string ReminderBaseTable::REMINDER_TYPE = "reminder_type"; +const std::string ReminderBaseTable::REMINDER_TIME = "reminder_time"; +const std::string ReminderBaseTable::TRIGGER_TIME = "trigger_time"; +const std::string ReminderBaseTable::TIME_INTERVAL = "time_interval"; +const std::string ReminderBaseTable::SNOOZE_TIMES = "snooze_times"; +const std::string ReminderBaseTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; +const std::string ReminderBaseTable::RING_DURATION = "ring_duration"; +const std::string ReminderBaseTable::IS_EXPIRED = "is_expired"; +const std::string ReminderBaseTable::STATE = "state"; +const std::string ReminderBaseTable::ACTION_BUTTON_INFO = "button_info"; +const std::string ReminderBaseTable::CUSTOM_BUTTON_URI = "custom_button_uri"; +const std::string ReminderBaseTable::SLOT_ID = "slot_id"; +const std::string ReminderBaseTable::SNOOZE_SLOT_ID = "snooze_slot_id"; +const std::string ReminderBaseTable::NOTIFICATION_ID = "notification_id"; +const std::string ReminderBaseTable::TITLE = "title"; +const std::string ReminderBaseTable::CONTENT = "content"; +const std::string ReminderBaseTable::SNOOZE_CONTENT = "snooze_content"; +const std::string ReminderBaseTable::EXPIRED_CONTENT = "expired_content"; +const std::string ReminderBaseTable::WANT_AGENT = "want_agent"; +const std::string ReminderBaseTable::MAX_SCREEN_WANT_AGENT = "max_screen_want_agent"; +const std::string ReminderBaseTable::TAP_DISMISSED = "tap_dismissed"; +const std::string ReminderBaseTable::AUTO_DELETED_TIME = "auto_deleted_time"; +const std::string ReminderBaseTable::GROUP_ID = "group_id"; +const std::string ReminderBaseTable::CUSTOM_RING_URI = "custom_ring_uri"; +const std::string ReminderBaseTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; +const std::string ReminderBaseTable::CREATOR_UID = "creator_uid"; + +// reminder alarm table +const std::string ReminderAlarmTable::TABLE_NAME = "reminder_alarm"; +const std::string ReminderAlarmTable::REMINDER_ID = "reminder_id"; +const std::string ReminderAlarmTable::ALARM_HOUR = "alarm_hour"; +const std::string ReminderAlarmTable::ALARM_MINUTE = "alarm_minute"; +const std::string ReminderAlarmTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; + +// reminder calendar table +const std::string ReminderCalendarTable::TABLE_NAME = "reminder_calendar"; +const std::string ReminderCalendarTable::REMINDER_ID = "reminder_id"; +const std::string ReminderCalendarTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; +const std::string ReminderCalendarTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; +const std::string ReminderCalendarTable::FIRST_DESIGNATE_DAY = "first_designate_day"; +const std::string ReminderCalendarTable::CALENDAR_DATE_TIME = "calendar_date_time"; +const std::string ReminderCalendarTable::CALENDAR_END_DATE_TIME = "calendar_end_date_time"; +const std::string ReminderCalendarTable::REPEAT_DAYS = "repeat_days"; +const std::string ReminderCalendarTable::REPEAT_MONTHS = "repeat_months"; +const std::string ReminderCalendarTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +const std::string ReminderCalendarTable::RRULE_WANT_AGENT = "rrule_want_agent"; +const std::string ReminderCalendarTable::EXCLUDE_DATES = "exclude_dates"; +const std::string ReminderCalendarTable::CALENDAR_LAST_DATE_TIME = "calendar_last_date_time"; + +// reminder timer table +const std::string ReminderTimerTable::TABLE_NAME = "reminder_timer"; +const std::string ReminderTimerTable::REMINDER_ID = "reminder_id"; +const std::string ReminderTimerTable::TRIGGER_SECOND = "trigger_second"; +const std::string ReminderTimerTable::START_DATE_TIME = "start_date_time"; +const std::string ReminderTimerTable::END_DATE_TIME = "end_date_time"; + +std::string ReminderBaseTable::ADD_COLUMNS = ""; +std::string ReminderBaseTable::SELECT_COLUMNS = ""; + +std::string ReminderAlarmTable::ADD_COLUMNS = ""; +std::string ReminderAlarmTable::SELECT_COLUMNS = ""; + +std::string ReminderCalendarTable::ADD_COLUMNS = ""; +std::string ReminderCalendarTable::SELECT_COLUMNS = ""; + +std::string ReminderTimerTable::ADD_COLUMNS = ""; +std::string ReminderTimerTable::SELECT_COLUMNS = ""; + +static inline void AddColumn(const std::string& name, const std::string& type, std::string& sqlOfColumns, + std::string& columns) +{ + columns.append(name).append(","); + sqlOfColumns.append(name).append(" "); + sqlOfColumns.append(type).append(", "); +} + +static inline void AddColumnEnd(const std::string& name, const std::string& type, std::string& sqlOfColumns, + std::string& columns) +{ + columns.append(name); + sqlOfColumns.append(name).append(" "); + sqlOfColumns.append(type); +} + +void ReminderBaseTable::InitDbColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(PACKAGE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(USER_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(SYSTEM_APP, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(REMINDER_TYPE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(REMINDER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(RING_DURATION, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(IS_EXPIRED, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(STATE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(ACTION_BUTTON_INFO, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CUSTOM_BUTTON_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(SNOOZE_SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(NOTIFICATION_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(TITLE, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(SNOOZE_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(EXPIRED_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(MAX_SCREEN_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(TAP_DISMISSED, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(AUTO_DELETED_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(GROUP_ID, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CUSTOM_RING_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CREATOR_BUNDLE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumnEnd(CREATOR_UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +} + +void ReminderAlarmTable::InitDbColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(ALARM_HOUR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(ALARM_MINUTE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumnEnd(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); +} + +void ReminderCalendarTable::InitDbColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(FIRST_DESIGNATE_YEAR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(FIRST_DESIGNATE_MONTH, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(FIRST_DESIGNATE_DAY, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CALENDAR_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(CALENDAR_END_DATE_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(REPEAT_DAYS, "INT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(REPEAT_MONTHS, "INT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(RRULE_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(EXCLUDE_DATES, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); + AddColumnEnd(CALENDAR_LAST_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +} + +void ReminderTimerTable::InitDbColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(TRIGGER_SECOND, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumn(START_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); + AddColumnEnd(END_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); +} +} +} diff --git a/services/reminder/src/reminder_table_old.cpp b/services/reminder/src/reminder_table_old.cpp new file mode 100644 index 000000000..1def1b8bc --- /dev/null +++ b/services/reminder/src/reminder_table_old.cpp @@ -0,0 +1,157 @@ +/* + * Copyright (c) 2024 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 "reminder_table_old.h" + +namespace OHOS { +namespace Notification { +// Reminder Table Basic Columns. +const std::string ReminderTable::TABLE_NAME = "reminder"; +const std::string ReminderTable::REMINDER_ID = "reminder_id"; +const std::string ReminderTable::PKG_NAME = "package_name"; +const std::string ReminderTable::USER_ID = "user_id"; +const std::string ReminderTable::UID = "uid"; +const std::string ReminderTable::SYS_APP = "system_app"; +const std::string ReminderTable::APP_LABEL = "app_label"; +const std::string ReminderTable::REMINDER_TYPE = "reminder_type"; +const std::string ReminderTable::REMINDER_TIME = "reminder_time"; +const std::string ReminderTable::TRIGGER_TIME = "trigger_time"; +const std::string ReminderTable::RTC_TRIGGER_TIME = "rtc_trigger_time"; +const std::string ReminderTable::TIME_INTERVAL = "time_interval"; +const std::string ReminderTable::SNOOZE_TIMES = "snooze_times"; +const std::string ReminderTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; +const std::string ReminderTable::RING_DURATION = "ring_duration"; +const std::string ReminderTable::IS_EXPIRED = "is_expired"; +const std::string ReminderTable::IS_ACTIVE = "is_active"; +const std::string ReminderTable::STATE = "state"; +const std::string ReminderTable::ZONE_ID = "zone_id"; +const std::string ReminderTable::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout"; +const std::string ReminderTable::ACTION_BUTTON_INFO = "button_info"; +const std::string ReminderTable::CUSTOM_BUTTON_URI = "custom_button_uri"; +const std::string ReminderTable::SLOT_ID = "slot_id"; +const std::string ReminderTable::SNOOZE_SLOT_ID = "snooze_slot_id"; +const std::string ReminderTable::NOTIFICATION_ID = "notification_id"; +const std::string ReminderTable::TITLE = "title"; +const std::string ReminderTable::CONTENT = "content"; +const std::string ReminderTable::SNOOZE_CONTENT = "snooze_content"; +const std::string ReminderTable::EXPIRED_CONTENT = "expired_content"; +const std::string ReminderTable::AGENT = "agent"; +const std::string ReminderTable::MAX_SCREEN_AGENT = "maxScreen_agent"; +const std::string ReminderTable::TAP_DISMISSED = "tapDismissed"; +const std::string ReminderTable::AUTO_DELETED_TIME = "autoDeletedTime"; +const std::string ReminderTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; +const std::string ReminderTable::GROUP_ID = "groupId"; +const std::string ReminderTable::CUSTOM_RING_URI = "custom_ring_uri"; +const std::string ReminderTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; + +// Reminder Table Calendar Columns. +const std::string ReminderTable::REPEAT_DAYS = "repeat_days"; +const std::string ReminderTable::REPEAT_MONTHS = "repeat_months"; +const std::string ReminderTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; +const std::string ReminderTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; +const std::string ReminderTable::FIRST_DESIGNATE_DAY = "first_designate_day"; +const std::string ReminderTable::CALENDAR_YEAR = "calendar_year"; +const std::string ReminderTable::CALENDAR_MONTH = "calendar_month"; +const std::string ReminderTable::CALENDAR_DAY = "calendar_day"; +const std::string ReminderTable::CALENDAR_HOUR = "calendar_hour"; +const std::string ReminderTable::CALENDAR_MINUTE = "calendar_minute"; + +// Reminder Table Alarm Columns. +const std::string ReminderTable::ALARM_HOUR = "alarm_hour"; +const std::string ReminderTable::ALARM_MINUTE = "alarm_minute"; + +std::string ReminderTable::ADD_COLUMNS = ""; +std::string ReminderTable::SELECT_COLUMNS = ""; + +void ReminderTable::InitDbColumns() +{ + InitBasicColumns(); + InitCalendarColumns(); + InitAlarmColumns(); +} + +void ReminderTable::InitBasicColumns() +{ + AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY"); + AddColumn(PKG_NAME, "TEXT NOT NULL"); + AddColumn(USER_ID, "INT NOT NULL"); + AddColumn(UID, "INT NOT NULL"); + AddColumn(SYS_APP, "TEXT NOT NULL"); + AddColumn(APP_LABEL, "TEXT"); + AddColumn(REMINDER_TYPE, "INT NOT NULL"); + AddColumn(REMINDER_TIME, "BIGINT NOT NULL"); + AddColumn(TRIGGER_TIME, "BIGINT NOT NULL"); + AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL"); + AddColumn(TIME_INTERVAL, "BIGINT NOT NULL"); + AddColumn(SNOOZE_TIMES, "INT NOT NULL"); + AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL"); + AddColumn(RING_DURATION, "BIGINT NOT NULL"); + AddColumn(IS_EXPIRED, "TEXT NOT NULL"); + AddColumn(IS_ACTIVE, "TEXT NOT NULL"); + AddColumn(STATE, "INT NOT NULL"); + AddColumn(ZONE_ID, "TEXT"); + AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT"); + AddColumn(ACTION_BUTTON_INFO, "TEXT"); + AddColumn(CUSTOM_BUTTON_URI, "TEXT"); + AddColumn(SLOT_ID, "INT"); + AddColumn(SNOOZE_SLOT_ID, "INT"); + AddColumn(NOTIFICATION_ID, "INT NOT NULL"); + AddColumn(TITLE, "TEXT"); + AddColumn(CONTENT, "TEXT"); + AddColumn(SNOOZE_CONTENT, "TEXT"); + AddColumn(EXPIRED_CONTENT, "TEXT"); + AddColumn(AGENT, "TEXT"); + AddColumn(MAX_SCREEN_AGENT, "TEXT"); + AddColumn(TAP_DISMISSED, "TEXT"); + AddColumn(AUTO_DELETED_TIME, "BIGINT"); + AddColumn(REPEAT_DAYS_OF_WEEK, "INT"); + AddColumn(GROUP_ID, "TEXT"); + AddColumn(CUSTOM_RING_URI, "TEXT"); + AddColumn(CREATOR_BUNDLE_NAME, "TEXT", false); +} + +void ReminderTable::InitCalendarColumns() +{ + AddColumn(REPEAT_DAYS, "INT"); + AddColumn(REPEAT_MONTHS, "INT"); + AddColumn(FIRST_DESIGNATE_YEAR, "INT"); + AddColumn(FIRST_DESIGNATE_MONTH, "INT"); + AddColumn(FIRST_DESIGNATE_DAY, "INT"); + AddColumn(CALENDAR_YEAR, "INT"); + AddColumn(CALENDAR_MONTH, "INT"); + AddColumn(CALENDAR_DAY, "INT"); + AddColumn(CALENDAR_HOUR, "INT"); + AddColumn(CALENDAR_MINUTE, "INT"); +} + +void ReminderTable::InitAlarmColumns() +{ + AddColumn(ALARM_HOUR, "INT"); + AddColumn(ALARM_MINUTE, "INT", true); +} + +void ReminderTable ::AddColumn( + const std::string& name, const std::string& type, bool isEnd) +{ + if (!isEnd) { + SELECT_COLUMNS.append(name).append(","); + ADD_COLUMNS += name + " " + type + ", "; + } else { + SELECT_COLUMNS.append(name); + ADD_COLUMNS += name + " " + type; + } +} +} +} diff --git a/services/reminder/src/reminder_timer_info.cpp b/services/reminder/src/reminder_timer_info.cpp new file mode 100644 index 000000000..d11fa91f5 --- /dev/null +++ b/services/reminder/src/reminder_timer_info.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021-2022 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 "reminder_timer_info.h" + +#include "ans_log_wrapper.h" +#include "common_event_manager.h" +#include "reminder_request.h" + +using namespace OHOS::EventFwk; +using namespace OHOS::HiviewDFX; +namespace OHOS { +namespace Notification { +void ReminderTimerInfo::SetType(const int &_type) +{ + type = _type; +} + +void ReminderTimerInfo::SetRepeat(bool _repeat) +{ + repeat = _repeat; +} + +void ReminderTimerInfo::SetInterval(const uint64_t &_interval) +{ + interval = _interval; +} + +void ReminderTimerInfo::SetWantAgent(std::shared_ptr _wantAgent) +{ + wantAgent = _wantAgent; +} + +void ReminderTimerInfo::OnTrigger() +{ + ANSR_LOGI("Timing is arrivelled."); +} +} +} diff --git a/tools/dump/BUILD.gn b/tools/dump/BUILD.gn index c9bd4bc7d..a703f391e 100644 --- a/tools/dump/BUILD.gn +++ b/tools/dump/BUILD.gn @@ -46,7 +46,10 @@ ohos_executable("anm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + ] configs = [ "${frameworks_module_ans_path}:ans_innerkits_public_config" ] -- Gitee From 04fa4c3f8d066d81d8c63264ec9bdc6038445715 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 15 Nov 2024 16:55:42 +0800 Subject: [PATCH 02/29] push Signed-off-by: fengyang --- frameworks/reminder/idl-gen:Zone.Identifier | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 frameworks/reminder/idl-gen:Zone.Identifier diff --git a/frameworks/reminder/idl-gen:Zone.Identifier b/frameworks/reminder/idl-gen:Zone.Identifier deleted file mode 100644 index e69de29bb..000000000 -- Gitee From 3fcb30b5ad480c534e5fa5287ae0ef5286cd8ae8 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 15 Nov 2024 16:57:32 +0800 Subject: [PATCH 03/29] push Signed-off-by: fengyang --- .../core/include/ans_manager_interface.h | 57 ----------------- frameworks/core/include/ans_manager_proxy.h | 57 ----------------- frameworks/core/include/ans_manager_stub.h | 64 ------------------- 3 files changed, 178 deletions(-) diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index e503d8d65..f31277450 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -652,63 +652,6 @@ public: */ virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) = 0; - // /** - // * @brief Publishes a reminder notification. - // * - // * @param reminder Identifies the reminder notification request that needs to be published. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode PublishReminder(sptr &reminder) = 0; - - // /** - // * @brief Cancel a reminder notifications. - // * - // * @param reminderId Identifies the reminders id that needs to be canceled. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode CancelReminder(const int32_t reminderId) = 0; - - // /** - // * @brief Get all valid reminder notifications. - // * - // * @param reminders Identifies the list of all valid notifications. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode GetValidReminders(std::vector> &reminders) = 0; - - // /** - // * @brief Cancel all reminder notifications. - // * - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode CancelAllReminders() = 0; - - // /** - // * @brief Add exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param date exclude date - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) = 0; - - // /** - // * @brief Clear exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode DelExcludeDates(const int32_t reminderId) = 0; - - // /** - // * @brief Get exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param dates exclude dates - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) = 0; - /** * @brief Checks whether this device is support template. * diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index db8df7d94..87c134236 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -649,63 +649,6 @@ public: */ ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; - // /** - // * @brief Publishes a reminder notification. - // * - // * @param reminder Identifies the reminder notification request that needs to be published. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode PublishReminder(sptr &reminder) override; - - // /** - // * @brief Cancel a reminder notifications. - // * - // * @param reminderId Identifies the reminders id that needs to be canceled. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode CancelReminder(const int32_t reminderId) override; - - // /** - // * @brief Get all valid reminder notifications. - // * - // * @param reminders Identifies the list of all valid notifications. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode GetValidReminders(std::vector> &reminders) override; - - // /** - // * @brief Cancel all reminder notifications. - // * - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode CancelAllReminders() override; - - // /** - // * @brief Add exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param date exclude date - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - // /** - // * @brief Clear exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode DelExcludeDates(const int32_t reminderId) override; - - // /** - // * @brief Get exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param dates exclude dates - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; - /** * @brief Checks Whether the specified users is allowed to publish notifications. * diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 51650a776..cbf994c58 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -642,63 +642,6 @@ public: */ virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; - // /** - // * @brief Publishes a reminder notification. - // * - // * @param reminder Identifies the reminder notification request that needs to be published. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode PublishReminder(sptr &reminder) override; - - // /** - // * @brief Cancel a reminder notifications. - // * - // * @param reminderId Identifies the reminders id that needs to be canceled. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode CancelReminder(const int32_t reminderId) override; - - // /** - // * @brief Get all valid reminder notifications. - // * - // * @param reminders Identifies the list of all valid notifications. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode GetValidReminders(std::vector> &reminders) override; - - // /** - // * @brief Cancel all reminder notifications. - // * - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode CancelAllReminders() override; - - // /** - // * @brief Add exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param date exclude date - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - // /** - // * @brief Clear exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode DelExcludeDates(const int32_t reminderId) override; - - // /** - // * @brief Get exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param dates exclude dates - // * @return Returns ERR_OK on success, others on failure. - // */ - // virtual ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; - /** * @brief Checks whether this device is support template. * @@ -1012,13 +955,6 @@ private: ErrCode HandleGetDeviceRemindType(MessageParcel &data, MessageParcel &reply); ErrCode HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); ErrCode HandleCancelContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); - // ErrCode HandlePublishReminder(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleCancelReminder(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleGetValidReminders(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply); - // ErrCode HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialUserAllowedNotifyByUser(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetNotificationsEnabledByUser(MessageParcel &data, MessageParcel &reply); -- Gitee From 8dba66f4e968201f5d2d33a8543f959f944ee6f1 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 15 Nov 2024 17:28:24 +0800 Subject: [PATCH 04/29] push Signed-off-by: fengyang --- frameworks/cj/ffi/BUILD.gn | 5 +- frameworks/core/include/ans_notification.h | 1 - .../core/src/manager/ans_manager_stub.cpp | 197 -- .../src/manager/ans_manager_stub_invalid.cpp | 42 - frameworks/js/napi/src/subscribe/BUILD.gn | 5 +- .../include/advanced_notification_service.h | 57 - .../advanced_notification_service_ability.h | 1 - .../include/reminder_config_change_observer.h | 42 - services/ans/include/reminder_data_manager.h | 763 ------ services/ans/include/reminder_event_manager.h | 100 - services/ans/include/reminder_store.h | 109 - services/ans/include/reminder_timer_info.h | 88 - .../advanced_notification_service_ability.cpp | 1 - .../src/reminder_config_change_observer.cpp | 41 - services/ans/src/reminder_data_manager.cpp | 2073 ----------------- .../ans/src/reminder_data_manager_inner.cpp | 168 -- services/ans/src/reminder_event_manager.cpp | 361 --- services/ans/src/reminder_store.cpp | 817 ------- services/ans/src/reminder_table.cpp | 178 -- services/ans/src/reminder_table_old.cpp | 157 -- services/ans/src/reminder_timer_info.cpp | 51 - 21 files changed, 2 insertions(+), 5255 deletions(-) delete mode 100644 services/ans/include/reminder_config_change_observer.h delete mode 100644 services/ans/include/reminder_data_manager.h delete mode 100644 services/ans/include/reminder_event_manager.h delete mode 100644 services/ans/include/reminder_store.h delete mode 100644 services/ans/include/reminder_timer_info.h delete mode 100644 services/ans/src/reminder_config_change_observer.cpp delete mode 100644 services/ans/src/reminder_data_manager.cpp delete mode 100644 services/ans/src/reminder_data_manager_inner.cpp delete mode 100644 services/ans/src/reminder_event_manager.cpp delete mode 100644 services/ans/src/reminder_store.cpp delete mode 100644 services/ans/src/reminder_table.cpp delete mode 100644 services/ans/src/reminder_table_old.cpp delete mode 100644 services/ans/src/reminder_timer_info.cpp diff --git a/frameworks/cj/ffi/BUILD.gn b/frameworks/cj/ffi/BUILD.gn index 9447c9c9c..ee353be72 100644 --- a/frameworks/cj/ffi/BUILD.gn +++ b/frameworks/cj/ffi/BUILD.gn @@ -38,10 +38,7 @@ ohos_shared_library("cj_notification_manager_ffi") { use_exceptions = true if (product_name != "ohos-sdk") { - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${frameworks_module_reminder_path}:reminder_innerkits", - ] + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] external_deps = [ "ability_base:want", "ability_base:zuri", diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index cb70a6da4..8d7971e03 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -876,7 +876,6 @@ public: * @brief try to reconnect ans SA when SA manager OnAddSystemAbility called. */ void Reconnect(); - /** * @brief Checks whether this application has permission to publish notifications under the user. * diff --git a/frameworks/core/src/manager/ans_manager_stub.cpp b/frameworks/core/src/manager/ans_manager_stub.cpp index 58bca12ed..ed3e9038a 100644 --- a/frameworks/core/src/manager/ans_manager_stub.cpp +++ b/frameworks/core/src/manager/ans_manager_stub.cpp @@ -287,22 +287,6 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleCancelContinuousTaskNotification(data, reply); break; } - // case static_cast(NotificationInterfaceCode::PUBLISH_REMINDER): { - // result = HandlePublishReminder(data, reply); - // break; - // } - // case static_cast(NotificationInterfaceCode::CANCEL_REMINDER): { - // result = HandleCancelReminder(data, reply); - // break; - // } - // case static_cast(NotificationInterfaceCode::CANCEL_ALL_REMINDERS): { - // result = HandleCancelAllReminders(data, reply); - // break; - // } - // case static_cast(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS): { - // result = HandleGetValidReminders(data, reply); - // break; - // } case static_cast(NotificationInterfaceCode::IS_SUPPORT_TEMPLATE): { result = HandleIsSupportTemplate(data, reply); break; @@ -433,18 +417,6 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess break; } #endif - // case static_cast(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER): { - // result = HandleAddExcludeDate(data, reply); - // break; - // } - // case static_cast(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER): { - // result = HandleDelExcludeDates(data, reply); - // break; - // } - // case static_cast(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER): { - // result = HandleGetExcludeDates(data, reply); - // break; - // } case static_cast(NotificationInterfaceCode::GET_DONOTDISTURB_PROFILE): { result = HandleGetDoNotDisturbProfile(data, reply); break; @@ -1861,175 +1833,6 @@ ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &repl return ERR_OK; } -// ErrCode AnsManagerStub::HandlePublishReminder(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandlePublishReminder"); -// uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); -// if (!data.ReadUint8(typeInfo)) { -// ANSR_LOGE("Failed to read reminder type"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// ReminderRequest::ReminderType reminderType = static_cast(typeInfo); -// sptr reminder; -// if (ReminderRequest::ReminderType::ALARM == reminderType) { -// ANSR_LOGD("Publish alarm"); -// reminder = data.ReadParcelable(); -// } else if (ReminderRequest::ReminderType::TIMER == reminderType) { -// ANSR_LOGD("Publish timer"); -// reminder = data.ReadParcelable(); -// } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { -// ANSR_LOGD("Publish calendar"); -// reminder = data.ReadParcelable(); -// } else { -// ANSR_LOGE("Reminder type invalid"); -// return ERR_ANS_INVALID_PARAM; -// } -// if (!reminder) { -// ANSR_LOGE("Reminder ReadParcelable failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// ErrCode result = PublishReminder(reminder); - -// if (!reply.WriteInt32(reminder->GetReminderId())) { -// ANSR_LOGE("Write back reminderId failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleCancelReminder(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandleCancelReminder"); -// int32_t reminderId = -1; -// if (!data.ReadInt32(reminderId)) { -// ANSR_LOGE("Read reminder id failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// ErrCode result = CancelReminder(reminderId); -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply) -// { -// ErrCode result = CancelAllReminders(); -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandleGetValidReminders"); -// std::vector> validReminders; -// ErrCode result = GetValidReminders(validReminders); - -// ANSR_LOGD("Write back size=%{public}zu", validReminders.size()); -// if (!reply.WriteUint8(static_cast(validReminders.size()))) { -// ANSR_LOGE("Write back reminder count failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// for (auto it = validReminders.begin(); it != validReminders.end(); ++it) { -// sptr reminder = (*it); -// uint8_t reminderType = static_cast(reminder->GetReminderType()); -// ANSR_LOGD("ReminderType=%{public}d", reminderType); -// if (!reply.WriteUint8(reminderType)) { -// ANSR_LOGW("Write reminder type failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!reply.WriteParcelable(reminder)) { -// ANSR_LOGW("Write reminder parcelable failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// } -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleAddExcludeDate(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandleAddExcludeDate"); -// int32_t reminderId = -1; -// if (!data.ReadInt32(reminderId)) { -// ANSR_LOGE("Read reminder id failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// uint64_t date = 0; -// if (!data.ReadUint64(date)) { -// ANSR_LOGE("Read exclude date failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// ErrCode result = AddExcludeDate(reminderId, date); -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleDelExcludeDates(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandleDelExcludeDates"); -// int32_t reminderId = -1; -// if (!data.ReadInt32(reminderId)) { -// ANSR_LOGE("Read reminder id failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// ErrCode result = DelExcludeDates(reminderId); -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerStub::HandleGetExcludeDates(MessageParcel &data, MessageParcel &reply) -// { -// ANSR_LOGI("HandleGetExcludeDates"); -// int32_t reminderId = -1; -// if (!data.ReadInt32(reminderId)) { -// ANSR_LOGE("Read reminder id failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// std::vector dates; -// ErrCode result = GetExcludeDates(reminderId, dates); -// ANSR_LOGD("Write back size=%{public}zu", dates.size()); -// if (!reply.WriteUint8(static_cast(dates.size()))) { -// ANSR_LOGE("Write back exclude date count failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// for (const auto date : dates) { -// if (!reply.WriteUint64(date)) { -// ANSR_LOGW("Write exclude date failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// } -// if (!reply.WriteInt32(result)) { -// ANSR_LOGE("Write back result failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - ErrCode AnsManagerStub::HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply) { std::string templateName; diff --git a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp index 62d5cea3d..b679a1f1a 100644 --- a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp @@ -454,48 +454,6 @@ ErrCode AnsManagerStub::CancelContinuousTaskNotification(const std::string &labe return ERR_INVALID_OPERATION; } -// ErrCode AnsManagerStub::PublishReminder(sptr &reminder) -// { -// ANS_LOGE("AnsManagerStub::PublishReminder called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::CancelReminder(const int32_t reminderId) -// { -// ANS_LOGE("AnsManagerStub::CancelReminder called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::GetValidReminders(std::vector> &reminders) -// { -// ANS_LOGE("AnsManagerStub::getValidReminders called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::CancelAllReminders() -// { -// ANS_LOGE("AnsManagerStub::cancelAllReminders called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::AddExcludeDate(const int32_t reminderId, const uint64_t date) -// { -// ANS_LOGE("AnsManagerStub::AddExcludeDate called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::DelExcludeDates(const int32_t reminderId) -// { -// ANS_LOGE("AnsManagerStub::DelExcludeDates called!"); -// return ERR_INVALID_OPERATION; -// } - -// ErrCode AnsManagerStub::GetExcludeDates(const int32_t reminderId, std::vector& dates) -// { -// ANS_LOGE("AnsManagerStub::GetExcludeDates called!"); -// return ERR_INVALID_OPERATION; -// } - ErrCode AnsManagerStub::IsSupportTemplate(const std::string &templateName, bool &support) { ANS_LOGE("AnsManagerStub::IsSupportTemplate called!"); diff --git a/frameworks/js/napi/src/subscribe/BUILD.gn b/frameworks/js/napi/src/subscribe/BUILD.gn index 300bffd59..8b3e32f8c 100644 --- a/frameworks/js/napi/src/subscribe/BUILD.gn +++ b/frameworks/js/napi/src/subscribe/BUILD.gn @@ -73,10 +73,7 @@ ohos_shared_library("notificationsubscribe") { "napi_subscribe.cpp", ] - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${frameworks_module_reminder_path}:reminder_innerkits", - ] + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] external_deps = [ "ability_base:want", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 41d1c0be5..20115ded6 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -702,63 +702,6 @@ public: */ bool CheckReminderPermission(); - // /** - // * @brief Publishes a reminder notification. - // * - // * @param reminder Identifies the reminder notification request that needs to be published. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode PublishReminder(sptr &reminder) override; - - // /** - // * @brief Cancel a reminder notifications. - // * - // * @param reminderId Identifies the reminders id that needs to be canceled. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode CancelReminder(const int32_t reminderId) override; - - // /** - // * @brief Get all valid reminder notifications. - // * - // * @param reminders Identifies the list of all valid notifications. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode GetValidReminders(std::vector> &reminders) override; - - // /** - // * @brief Cancel all reminder notifications. - // * - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode CancelAllReminders() override; - - // /** - // * @brief Add exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param date exclude date - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override; - - // /** - // * @brief Clear exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode DelExcludeDates(const int32_t reminderId) override; - - // /** - // * @brief Get exclude date for reminder - // * - // * @param reminderId Identifies the reminders id. - // * @param dates exclude dates - // * @return Returns ERR_OK on success, others on failure. - // */ - // ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; - /** * @brief Checks whether this device is support template. * diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 5cbc4f61f..6caf7f477 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -55,7 +55,6 @@ private: private: std::atomic isDatashaReready_ {false}; sptr service_; - // std::shared_ptr reminderAgent_; std::shared_ptr subscriber_ = nullptr; }; } // namespace Notification diff --git a/services/ans/include/reminder_config_change_observer.h b/services/ans/include/reminder_config_change_observer.h deleted file mode 100644 index 342eb9748..000000000 --- a/services/ans/include/reminder_config_change_observer.h +++ /dev/null @@ -1,42 +0,0 @@ -// /* -// * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H - -// #include "configuration_observer_stub.h" - -// namespace OHOS { -// namespace Notification { - -// /** -// * @brief Listening system language change, when the system language changes, -// * notify ReminderDataManager. -// */ -// class ReminderConfigChangeObserver final : public AppExecFwk::ConfigurationObserverStub { -// public: -// ReminderConfigChangeObserver() = default; -// ~ReminderConfigChangeObserver() = default; - -// public: -// void OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) override; - -// private: -// std::string languageInfo_; -// }; -// } // namespace Notification -// } // namespace OHOS - -// #endif \ No newline at end of file diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h deleted file mode 100644 index 2e0cbbc70..000000000 --- a/services/ans/include/reminder_data_manager.h +++ /dev/null @@ -1,763 +0,0 @@ -// /* -// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H - -// #include -// #include - -// #include "advanced_notification_service.h" -// #include "ans_inner_errors.h" -// #ifdef PLAYER_FRAMEWORK_ENABLE -// #include "player.h" -// #endif -// #include "ffrt.h" -// #include "app_mgr_client.h" -// #include "reminder_request.h" -// #include "reminder_store.h" -// #include "reminder_timer_info.h" -// #include "reminder_config_change_observer.h" -// #include "datashare_predicates.h" -// #include "datashare_values_bucket.h" -// #include "app_mgr_interface.h" -// #include "time_service_client.h" - -// namespace OHOS { -// namespace Notification { -// class ReminderDataManager final { -// public: -// ReminderDataManager() -// { -// Init(false); -// }; -// ~ReminderDataManager(); - -// ReminderDataManager(ReminderDataManager &other) = delete; -// ReminderDataManager& operator = (const ReminderDataManager &other) = delete; - -// /** -// * @brief Cancels all the reminders relative to the bundle option. -// * -// * @param packageName Indicates the package name. -// * @param userId Indicates the user id which the bundle belong to. -// * @param uid Indicates the uid which the bundle belong to. -// * @return ERR_OK if success, else not. -// */ -// ErrCode CancelAllReminders(const std::string& packageName, const int32_t userId, -// const int32_t uid); - -// /** -// * @brief Cancels the target reminder relative to the reminder id and bundle option. -// * -// * @param reminderId Indicates the reminder id. -// * @param bundleOption Indicates the bundle option. -// * @return ERR_OK if success, else not. -// */ -// ErrCode CancelReminder(const int32_t &reminderId, const sptr &bundleOption); - -// sptr CheckExcludeDateParam(const int32_t reminderId, -// const sptr &bundleOption); - -// /** -// * @brief Add exclude date for reminder -// * -// * @param reminderId Identifies the reminders id. -// * @param date exclude date -// * @return Returns ERR_OK on success, others on failure. -// */ -// ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date, -// const sptr &bundleOption); - -// /** -// * @brief Clear exclude date for reminder -// * -// * @param reminderId Identifies the reminders id. -// * @return Returns ERR_OK on success, others on failure. -// */ -// ErrCode DelExcludeDates(const int32_t reminderId, const sptr &bundleOption); - -// /** -// * @brief Get exclude date for reminder -// * -// * @param reminderId Identifies the reminders id. -// * @param dates exclude dates -// * @return Returns ERR_OK on success, others on failure. -// */ -// ErrCode GetExcludeDates(const int32_t reminderId, const sptr &bundleOption, -// std::vector& dates); - -// /** -// * @brief Close the target reminder which is showing on panel. -// * This is manul operation by user: 1.Click close button of the reminder, 2.remove reminder notification. -// * -// * @param want Want information that transferred when the event trigger by user. -// * @param cancelNotification Indicates whether need to cancel notification or not. -// */ -// void CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification); - -// /** -// * Dump all the reminders information. -// * -// * @return reminders informations. -// */ -// std::string Dump() const; - -// /** -// * Obtains the single instance. -// * -// * @return Single instance of ReminderDataManager. -// */ -// static std::shared_ptr GetInstance(); -// static std::shared_ptr InitInstance( -// const sptr &advancedNotificationService); - -// /** -// * Obtains all the valid reminders (which are not expired) relative to the bundle option. -// * -// * @param bundleOption Indicates the bundle option. -// * @param[out] reminders return the valid reminders. -// */ -// void GetValidReminders( -// const sptr &bundleOption, std::vector> &reminders); - -// /** -// * @brief Inits and recovery data from database. -// * -// * @param isFromBootComplete Indicates the init is called when boot completed. -// */ -// void Init(bool isFromBootComplete); - -// void InitUserId(); - -// /** -// * @brief Check all reminders, Whether an immediate reminder is needed; -// * whether a pull up service extension is required. -// * Use when powering on and changing the system time. -// */ -// void CheckReminderTime(std::vector>& immediatelyReminders, -// std::vector>& extensionReminders); - -// /** -// * @brief Register configuration observer, the listening system language is changed. -// */ -// bool RegisterConfigurationObserver(); - -// void OnUserRemove(const int32_t& userId); - -// /** -// * @brief Bundle manager service start. -// */ -// void OnBundleMgrServiceStart(); - -// /** -// * @brief Ability manager service start. -// */ -// void OnAbilityMgrServiceStart(); - -// void OnUserSwitch(const int32_t& userId); - -// /** -// * @brief Triggered when third party application died. -// * -// * @param bundleOption Indicates the bundleOption of third party application. -// */ -// void OnProcessDiedLocked(const sptr &bundleOption); - -// /** -// * Publishs a scheduled reminder. -// * -// * @param reminder Indicates the reminder. -// * @param bundleOption Indicates bundle option the reminder belongs to. -// * @return ERR_OK if success, else not. -// */ -// ErrCode PublishReminder(const sptr &reminder, -// const sptr &bundleOption); - -// /** -// * @brief Refresh all reminders when date/time or timeZone of device changed by user. -// * -// * @param type Indicates it is triggered by dateTime change or timeZone change. -// */ -// void RefreshRemindersDueToSysTimeChange(uint8_t type); - -// /** -// * @brief Indicates the single instance of ans that used to execute operations in service. -// * -// * @param Indicates the single instance of ans notification service. -// */ -// void SetService(sptr &advancedNotificationService); - -// bool ShouldAlert(const sptr &reminder) const; - -// /** -// * @brief Show the reminder. -// * -// * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. -// * @param want Which contains the given reminder. -// */ -// void ShowActiveReminder(const EventFwk::Want &want); - -// /** -// * @brief Snooze the reminder by manual. -// * 1) Snooze the trigger time to the next. -// * 2) Update the notification(Update notification lable/content...; Stop audio player and vibrator) -// * 3) Show the notification dialog in the SystemUI -// * 4) Start a new reminder, which is recent one now. -// * -// * @param want Which contains the given reminder. -// */ -// void SnoozeReminder(const OHOS::EventFwk::Want &want); - -// /** -// * Starts the recent reminder timing. -// */ -// void StartRecentReminder(); - -// /** -// * Handle custom button click event. -// */ -// void HandleCustomButtonClick(const OHOS::EventFwk::Want &want); - -// /** -// * Handle click notification, no button. -// */ -// void ClickReminder(const OHOS::EventFwk::Want &want); - -// /** -// * Handle auto delete time -// */ -// void HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, const int64_t autoDeletedTime); - -// /** -// * @brief Terminate the alerting reminder. -// * -// * 1. Stop sound and vibrate. -// * 2. Stop the alerting timer. -// * 3. Update the reminder state. -// * 4. Update the display content of the notification. -// * -// * @param want Which contains the given reminder. -// */ -// void TerminateAlerting(const OHOS::EventFwk::Want &want); - -// /** -// * @brief Update reminders based on the system language. -// * -// * Update action button title. -// */ -// void UpdateReminderLanguageLocked(const int32_t uid, const std::vector>& reminders); - -// /** -// * @brief System language change -// */ -// void OnLanguageChanged(); - -// /** -// * @brief When OnRemoveSystemAbility occurs. -// */ -// void OnRemoveAppMgr(); - -// /** -// * @brief Whether the device is ready or not. -// */ -// bool IsSystemReady(); - -// static constexpr uint8_t TIME_ZONE_CHANGE = 0; -// static constexpr uint8_t DATE_TIME_CHANGE = 1; - -// private: -// enum class TimerType : uint8_t { -// TRIGGER_TIMER, -// ALERTING_TIMER -// }; - -// static std::shared_ptr serviceQueue_; -// /** -// * Add default slot to the reminder if no slot set by user. -// * -// * @param reminder Indicates the reminder. -// */ -// void AddDefaultSlotIfNeeded(sptr &reminder); - -// /** -// * Add reminder to showed reminder vector. -// * -// * @param reminder Indicates the showed reminder. -// */ -// void AddToShowedReminders(const sptr &reminder); - -// void CancelAllReminders(const int32_t userId); - -// /** -// * @brief Check the update conditions. -// * -// * @param reminder Indicates the showed reminder. -// * @param actionButtonType Button type of the button. -// * @param actionButtonMap Button map. -// * @return True if check successful. -// */ -// bool CheckUpdateConditions(const sptr &reminder, -// const ReminderRequest::ActionButtonType &actionButtonType, -// const std::map &actionButtonMap); - -// /** -// * @brief update app database. -// * -// * @param reminder Indicates the showed reminder. -// * @param actionButtonType Button type of the button. -// */ -// void UpdateAppDatabase(const sptr &reminder, -// const ReminderRequest::ActionButtonType &actionButtonType); - -// /** -// * @brief generate Predicates for dataShare. -// * -// * @param predicates find fields from database. -// * @param equalToVector Split from dataShareUpdate->equaleTo. -// */ -// void GenPredicates(DataShare::DataSharePredicates &predicates, const std::vector &equalToVector); - -// /** -// * @brief generate ValuesBucket for dataShare. -// * -// * @param valuesBucket update fields at database. -// * @param valuesBucketVector Split from dataShareUpdate->valuesBucket. -// */ -// void GenValuesBucket(DataShare::DataShareValuesBucket &valuesBucket, -// const std::vector &valuesBucketVector); - -// /** -// * @brief get bundleName from uri. -// * -// * @param dstBundleName The package name required to update the database. -// * @param uri Database address. -// */ -// void GenDstBundleName(std::string &dstBundleName, const std::string &uri) const; - -// /** -// * @brief get custom ring uri. -// * -// * @param reminder Indicates the reminder. -// * @return Returns the uri of ring tone. -// */ -// std::string GetCustomRingUri(const sptr &reminder); - -// /** -// * @brief Cancels all the reminders of the target bundle or user. -// * -// * @param packageName Indicates the packageName need to cancel. -// * @param userId Indicates the userId to cancel. -// */ -// void CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, const int32_t uid); - -// /** -// * @brief Close reminders with the same group id. -// * -// * @param oldReminderId Indicates the reminderId that are currently bing showed. -// * @param packageName Indicates the packageName need to cancel. -// * @param groupId Indicates the group id to cancel. -// */ -// void CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, -// const std::string &groupId); - -// /** -// * Cancels the notification relative to the reminder. -// * -// * @param reminder Indicates the reminder. -// */ -// void CancelNotification(const sptr &reminder) const; - -// /** -// * Check whether the number limit of reminders if exceeded. -// * -// * @param bundleName Indicates the target bundle. -// * @return true if number limit is exceeded. -// */ -// bool CheckReminderLimitExceededLocked(const sptr &bundleOption, -// const sptr &reminder) const; -// void CloseReminder(const sptr &reminder, bool cancelNotification); - -// /** -// * Create a information for timer, such as timer type, repeat policy, interval and want agent. -// * -// * @param type Indicates the timer type. -// * @param reminderRequest Indicates the reminder request. -// * @return pointer of ReminderTimerInfo. -// */ -// std::shared_ptr CreateTimerInfo(TimerType type, -// const sptr &reminderRequest) const; -// void InitTimerInfo(std::shared_ptr &timerInfo, -// const sptr &reminderRequest, TimerType reminderType) const; - -// void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; - -// std::string GetSoundUri(const sptr &reminder); - -// /** -// * Find the reminder from reminderVector_ by reminder id. -// * -// * @param reminderId Indicates the reminder id. -// * @return pointer of reminder request or nullptr. -// */ -// sptr FindReminderRequestLocked(const int32_t &reminderId); - -// /** -// * Find the reminder from {@link reminderVector_} and -// * {@link notificationBundleOptionMap_} by reminder id and pkgName. -// * -// * @param reminderId Indicates the reminder id. -// * @param pkgName Indicates the package name. -// * @return pointer of reminder request or nullptr. -// */ -// sptr FindReminderRequestLocked(const int32_t &reminderId, const std::string &pkgName); - -// /** -// * Obtains the recent reminder which is not expired from reminder vector. -// * -// * The expired reminders will be removed from reminderVector_ and notificationBundleOptionMap_. -// * -// * @return pointer of reminder object. -// */ -// sptr GetRecentReminderLocked(); - -// void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); -// void HandleExtensionReminder(std::vector> &extensionReminders); - -// /** -// * @brief Refresh the reminder due to date/time or timeZone change by user. -// * -// * @param type Indicates it is date/time change or timeZone change. -// * @param reminder Indicates the target reminder. -// * @return sptr Returns the target reminder if it is need to show immediately, otherwise nullptr. -// */ -// sptr HandleRefreshReminder(const uint8_t &type, sptr &reminder); - -// /** -// * @brief Handles all the reminders that have the same notification id and belong to same application -// * with the current reminder. Unset the state of "showing". -// * -// * @param reminder Indicates the current reminder. -// */ -// void HandleSameNotificationIdShowing(const sptr reminder); - -// bool HandleSysTimeChange(const sptr reminder) const; - -// /** -// * @brief Judge the two reminders is belong to the same application or not. -// * -// * @param bundleOption Indicates the bundleOption of first reminder. -// * @param other Indicates the bundleOption of second reminder. -// * @return true if the two reminders belong to the same application. -// */ -// bool IsBelongToSameApp(const sptr &bundleOption, -// const sptr &other) const; -// bool CheckIsSameApp(const sptr &reminder, const sptr &other) const; - -// /** -// * @brief Judges whether the reminder is matched with the bundleOption or userId. -// * -// * @param reminder Indicates the target reminder. -// * @param packageName Indicates the package name. -// * @param userId Indicates the user id. -// * @param uid Indicates the uid. -// * @return true If the reminder is matched with the bundleOption or userId. -// */ -// bool IsMatched(const sptr &reminder, const std::string &packageName, -// const int32_t userId, const int32_t uid) const; - -// /** -// * @brief Judges whether the reminder is matched with the packageName or groupId. -// * -// * @param reminder Indicates the target reminder. -// * @param packageName Indicates the package name. -// * @param groupId Indicates the group id. -// * @return true If the reminder is matched with the packageName and groupId. -// */ -// bool IsMatchedForGroupIdAndPkgName(const sptr &reminder, const std::string &packageName, -// const std::string &groupId) const; - -// bool IsAllowedNotify(const sptr &reminder) const; - -// bool IsReminderAgentReady() const; - -// void LoadReminderFromDb(); - -// void PlaySoundAndVibrationLocked(const sptr &reminder); -// void PlaySoundAndVibration(const sptr &reminder); -// void StopSoundAndVibrationLocked(const sptr &reminder); -// void StopSoundAndVibration(const sptr &reminder); - -// /** -// * Remove from showed reminder vector. -// * -// * @param reminder Indicates the reminder need to remove. -// */ -// void RemoveFromShowedReminders(const sptr &reminder); - -// /** -// * @brief Refresh the all reminders due to date/time or timeZone change by user. -// * -// * @param type Indicates it is date/time change or timeZone change. -// * @return reminders that need to show immediately. -// */ -// void RefreshRemindersLocked(uint8_t type, std::vector>& immediatelyReminders, -// std::vector>& extensionReminders); - -// /** -// * Removes the reminder. -// * 1. removes the reminder from reminderVector_ and notificationBundleOptionMap_. -// * 2. cancels the notification. -// * -// * @param reminderId Indicates the reminder id. -// */ -// void RemoveReminderLocked(const int32_t &reminderId); - -// /** -// * Resets timer status. -// * 1. Sets timerId_ or timerIdAlerting_ with 0. -// * 2. Sets activeReminderId_ or alertingReminderId with -1. -// * -// * @param type Indicates the timer type. -// */ -// void ResetStates(TimerType type); - -// void SetActiveReminder(const sptr &reminder); -// void SetAlertingReminder(const sptr &reminder); -// void ShowActiveReminderExtendLocked(sptr &reminder); -// static bool StartExtensionAbility(const sptr &reminder); -// static void AsyncStartExtensionAbility(const sptr &reminder, int32_t times); -// void InitServiceHandler(); -// /** -// * @brief Show the reminder on SystemUI. -// * -// * @param reminder Indicates the reminder to show. -// * @param isNeedToPlaySound Indicates whether need to play sound. -// * @param isNeedToStartNext Indicates whether need to start next reminder. -// * @param isSysTimeChanged Indicates whether it is triggerred as system time changed by user. -// * @param needScheduleTimeout Indicates whether need to control the ring duration. -// */ -// void ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, -// const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout); - -// void SnoozeReminderImpl(sptr &reminder); - -// /** -// * Starts timing actually. -// * -// * @param reminderRequest Indicates the reminder. -// * @param type Indicates the timer type. -// */ -// void StartTimerLocked(const sptr &reminderRequest, TimerType type); -// void StartTimer(const sptr &reminderRequest, TimerType type); - -// uint64_t HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, -// const sptr &timer); - -// uint64_t HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, -// const sptr &timer, time_t now); - -// /** -// * @brief Stop the alerting timer and update reminder information. -// * -// * 1. Stop sound and vibrate. -// * 2. Stop the alerting timer. -// * -// * @param reminder Indicates the target reminder. -// */ -// void StopAlertingReminder(const sptr &reminder); - -// /** -// * Stops timing. -// * -// * @param type Indicates the timer type. -// */ -// void StopTimer(TimerType type); -// void StopTimerLocked(TimerType type); - -// /** -// * @brief Terminate the alerting reminder. -// * -// * 1. Stop sound and vibrate. -// * 2. Stop the alerting timer. -// * 3. Update the reminder state. -// * 4. Update the display content of the notification. -// * -// * @param reminder Indicates the reminder. -// * @param reason Indicates the description information. -// */ -// void TerminateAlerting(const sptr &reminder, const std::string &reason); -// void TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder); - -// /** -// * @brief Assign unique reminder id and save reminder in memory. -// * -// * @param reminder Indicates a reminder. -// * @param bundleOption Indicates bundle option relative to the reminder. -// */ -// void UpdateAndSaveReminderLocked( -// const sptr &reminder, const sptr &bundleOption); - -// void UpdateNotification(const sptr &reminder, bool isSnooze); - -// static bool cmp(sptr &reminderRequest, sptr &other); - -// /** -// * @brief Connect App Manager to get the current foreground application. -// */ -// bool ConnectAppMgr(); - -// /** -// * @brief Check need to notify the application, if the current foreground application -// * is the creator of the reminder, notify the application of the reminder status -// * change; otherwise, do not noitfy. -// * -// * @param reminder Indicates a reminder. -// * @param buttonType The type of button clicked by the user. -// */ -// void CheckNeedNotifyStatus(const sptr &reminder, -// const ReminderRequest::ActionButtonType buttonType); - -// std::string GetFullPath(const std::string& path); - -// /** -// * @brief Check action button data share permission -// */ -// bool IsActionButtonDataShareValid(const sptr& reminder, -// const uint32_t callerTokenId); - -// /** -// * @brief Get resource manager by bundlename and uid. -// */ -// std::shared_ptr GetResourceMgr(const std::string& bundleName, -// const int32_t uid); - -// /** -// * @brief Get custom ring file desc. -// * lock by resourceMutex_ in function -// */ -// bool GetCustomRingFileDesc(const sptr& reminder, -// Global::Resource::ResourceManager::RawFileDescriptor& desc); - -// /** -// * @brief Close custom ring file desc. -// * lock by resourceMutex_ in function -// */ -// void CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri); - -// /** -// * @brief report event to dfx -// */ -// void ReportSysEvent(const sptr& reminder); - -// /** -// * Single instance. -// */ -// static std::shared_ptr REMINDER_DATA_MANAGER; - -// /** -// * Used for multi-thread synchronise. -// */ -// static std::mutex MUTEX; -// static std::mutex SHOW_MUTEX; -// static std::mutex ALERT_MUTEX; -// static std::mutex TIMER_MUTEX; -// static std::mutex ACTIVE_MUTEX; - -// /** -// * Max number of reminders limit for the whole system. -// */ -// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYSTEM = 12000; - -// /** -// * Max number of reminders limit for one system application. -// */ -// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_SYS_APP = 10000; - -// /** -// * Max number of reminders limit for one application. -// */ -// static constexpr int16_t MAX_NUM_REMINDER_LIMIT_APP = 30; - -// bool isReminderAgentReady_ = false; - -// /** -// * Vector used to record all the reminders in system. -// */ -// std::vector> reminderVector_; - -// /** -// * Vector used to record all the reminders which has been shown on panel. -// */ -// std::vector> showedReminderVector_; - -// /** -// * This timer is used to control the triggerTime of next reminder. -// */ -// uint64_t timerId_ {0}; - -// /** -// * This timer is used to control the ringDuration of the alerting reminder. -// */ -// std::atomic timerIdAlerting_ {0}; - -// /** -// * Indicates the active reminder that timing is taking effect. -// */ -// std::atomic activeReminderId_ = -1; -// sptr activeReminder_ = nullptr; - -// /** -// * Indicates the reminder which is playing sound or vibration. -// */ -// std::atomic alertingReminderId_ = -1; -// sptr alertingReminder_ = nullptr; -// #ifdef PLAYER_FRAMEWORK_ENABLE -// std::shared_ptr soundPlayer_ = nullptr; -// std::mutex resourceMutex_; // for soundResource_ -// std::shared_ptr soundResource_ = nullptr; -// #endif -// /** -// * Indicates the total count of reminders in system. -// */ -// int16_t totalCount_ {0}; -// int currentUserId_ {0}; -// sptr advancedNotificationService_ = nullptr; -// std::shared_ptr store_ = nullptr; - -// /** -// * Indicates config change observer for language -// */ -// sptr configChangeObserver_ = nullptr; - -// /** -// * Indicates app mananger for get foreground application -// */ -// std::mutex appMgrMutex_; -// sptr appMgrProxy_ = nullptr; - -// /** -// * async queue -// */ -// std::shared_ptr queue_ = nullptr; - -// /** -// * Sa ready flag -// */ -// std::atomic saReadyFlag_{ 0 }; -// }; -// } // namespace OHOS -// } // namespace Notification -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h deleted file mode 100644 index ab3e4856a..000000000 --- a/services/ans/include/reminder_event_manager.h +++ /dev/null @@ -1,100 +0,0 @@ -// /* -// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H - -// #include "common_event_subscriber.h" -// #include "reminder_data_manager.h" -// #include "system_ability_status_change_stub.h" -// #include "notification_subscriber.h" - -// #include - -// namespace OHOS { -// namespace Notification { -// class ReminderEventManager { -// public: -// explicit ReminderEventManager(std::shared_ptr &reminderDataManager); -// virtual ~ReminderEventManager() {}; -// ReminderEventManager(ReminderEventManager &other) = delete; -// ReminderEventManager& operator = (const ReminderEventManager &other) = delete; - -// private: -// void init(std::shared_ptr &reminderDataManager) const; -// void SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const; - -// class ReminderEventSubscriber : public EventFwk::CommonEventSubscriber { -// public: -// ReminderEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, -// std::shared_ptr &reminderDataManager); -// virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); - -// private: -// sptr GetBundleOption(const OHOS::EventFwk::Want &want) const; -// void HandlePackageRemove(const EventFwk::Want &want) const; -// void HandleProcessDied(const EventFwk::Want &want) const; -// std::shared_ptr reminderDataManager_ = nullptr; -// }; - -// class ReminderEventCustomSubscriber : public EventFwk::CommonEventSubscriber { -// public: -// ReminderEventCustomSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, -// std::shared_ptr &reminderDataManager); -// virtual void OnReceiveEvent(const EventFwk::CommonEventData &data); - -// private: -// std::shared_ptr reminderDataManager_ = nullptr; -// }; - -// class SystemAbilityStatusChangeListener : public OHOS::SystemAbilityStatusChangeStub { -// public: -// explicit SystemAbilityStatusChangeListener(std::shared_ptr &reminderDataManager); -// ~SystemAbilityStatusChangeListener() {}; -// virtual void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; -// virtual void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; -// private: -// std::shared_ptr reminderDataManager_ = nullptr; -// }; - -// class ReminderNotificationSubscriber : public NotificationSubscriber { -// public: -// explicit ReminderNotificationSubscriber(std::shared_ptr &reminderDataManager); -// ~ReminderNotificationSubscriber() override; -// void OnConnected() override; -// void OnDisconnected() override; -// void OnCanceled(const std::shared_ptr &request, -// const std::shared_ptr &sortingMap, int deleteReason) override; -// void OnConsumed(const std::shared_ptr &request, -// const std::shared_ptr &sortingMap) override; -// void OnUpdate(const std::shared_ptr &sortingMap) override; -// void OnDied() override; -// void OnDoNotDisturbDateChange( -// const std::shared_ptr &date) override; -// void OnEnabledNotificationChanged( -// const std::shared_ptr &callbackData) override; -// void OnBadgeChanged(const std::shared_ptr &badgeData) override; -// void OnBadgeEnabledChanged(const sptr &callbackData) override; -// void OnBatchCanceled(const std::vector> &requestList, -// const std::shared_ptr &sortingMap, int32_t deleteReason) override; -// private: -// std::shared_ptr reminderDataManager_ = nullptr; -// }; - -// static std::shared_ptr subscriber_; -// }; -// } // namespace OHOS -// } // namespace Notification -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H diff --git a/services/ans/include/reminder_store.h b/services/ans/include/reminder_store.h deleted file mode 100644 index 22bcf9487..000000000 --- a/services/ans/include/reminder_store.h +++ /dev/null @@ -1,109 +0,0 @@ -// /* -// * Copyright (c) 2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H - -// #include - -// #include "notification_bundle_option.h" -// #include "reminder_request.h" -// #include "rdb_errno.h" -// #include "rdb_helper.h" -// #include "rdb_open_callback.h" -// #include "rdb_store_config.h" - -// namespace OHOS { -// namespace Notification { -// class ReminderStore { -// public: -// ReminderStore() {}; -// virtual ~ReminderStore() {}; - -// public: -// int32_t Init(); -// int32_t Delete(const int32_t reminderId); -// int32_t Delete(const std::string& pkg, const int32_t userId, const int32_t uid); -// int32_t DeleteUser(const int32_t userId); -// int32_t UpdateOrInsert(const sptr& reminder, const sptr& bundleOption); -// int32_t GetMaxId(); -// std::vector> GetAllValidReminders(); - -// public: -// static void GetUInt8Val(const std::shared_ptr& resultSet, -// const std::string& name, uint8_t& value); -// static void GetUInt16Val(const std::shared_ptr& resultSet, -// const std::string& name, uint16_t& value); -// static void GetInt32Val(const std::shared_ptr& resultSet, -// const std::string& name, int32_t& value); -// static void GetInt64Val(const std::shared_ptr& resultSet, -// const std::string& name, int64_t& value); -// static void GetUInt64Val(const std::shared_ptr& resultSet, -// const std::string& name, uint64_t& value); -// static void GetStringVal(const std::shared_ptr& resultSet, -// const std::string& name, std::string& value); - -// static const int32_t STATE_OK; -// static const int32_t STATE_FAIL; - -// static const std::string REMINDER_DB_DIR; -// static const std::string REMINDER_DB_NAME; -// static const std::string REMINDER_DB_TABLE; - -// private: -// /** -// * @brief Inits the data in database when system boot on or proxy process reboot on. -// * -// * 1. Deletes all the reminders which IS_EXPIRED is true. -// * 2. Sets all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE -// * -// * @return int32_t result code. -// */ -// int32_t InitData(); -// int32_t DeleteBase(const std::string& deleteCondition); -// int32_t Delete(const std::string& baseCondition, const std::string& assoConditon); -// int32_t Insert(const sptr& reminder, const sptr& bundleOption); -// int32_t Update(const sptr& reminder, const sptr& bundleOption); - -// bool IsReminderExist(const sptr& reminder); -// std::vector> GetReminders(const std::string& queryCondition); -// sptr BuildReminder(const std::shared_ptr& resultBase); - -// std::shared_ptr Query(const std::string& tableName, const std::string& colums, -// const int32_t reminderId); -// std::shared_ptr Query(const std::string& queryCondition) const; - -// private: -// std::shared_ptr rdbStore_ = nullptr; - -// private: -// class ReminderStoreDataCallBack : public NativeRdb::RdbOpenCallback { -// public: -// int32_t OnCreate(NativeRdb::RdbStore& store) override; -// int32_t OnUpgrade(NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) override; -// int32_t OnDowngrade(NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) override; - -// private: -// int32_t CreateTable(NativeRdb::RdbStore& store); -// int32_t CopyData(NativeRdb::RdbStore& store); -// std::vector> GetOldReminders(NativeRdb::RdbStore& store); -// void InsertNewReminders(NativeRdb::RdbStore& store, const std::vector>& reminders); -// void AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, -// const std::string& columnName, const std::string& columnType, const std::string& defValue); -// }; -// }; -// } // namespace Notification -// } // namespace OHOS -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H \ No newline at end of file diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h deleted file mode 100644 index 1a63c8126..000000000 --- a/services/ans/include/reminder_timer_info.h +++ /dev/null @@ -1,88 +0,0 @@ -// /* -// * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H - -// #include "advanced_notification_service.h" -// #include "itimer_info.h" -// #include "notification_request.h" -// #include "reminder_request.h" - -// namespace OHOS { -// namespace Notification { -// class ReminderTimerInfo : public MiscServices::ITimerInfo { -// public: -// ReminderTimerInfo() {}; -// virtual ~ReminderTimerInfo() {}; - -// ReminderTimerInfo(ReminderTimerInfo &other) = delete; -// ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; - -// inline void SetAction(const std::string &action) -// { -// action_ = action; -// } - -// inline void SetPid(const int32_t pid) -// { -// pid_ = pid; -// } - -// inline void SetUid(const int32_t uid) -// { -// uid_ = uid; -// } - -// inline void SetBundleName(const std::string &bundleName) -// { -// bundleName_ = bundleName; -// } - -// /** -// * When timing is up, this function will execute as call back. -// */ -// void OnTrigger() override; - -// /** -// * Indicates the timing type. -// */ -// void SetType(const int32_t &type) override; - -// /** -// * Indicates the repeat policy. -// */ -// void SetRepeat(bool repeat) override; - -// /** -// * Indicates the interval time for repeat timing. -// */ -// void SetInterval(const uint64_t &interval) override; - -// /** -// * Indicates the want agent information. -// */ -// void SetWantAgent(std::shared_ptr wantAgent) override; - -// private: -// std::string action_; -// int32_t pid_ {-1}; -// int32_t uid_ {-1}; -// std::string bundleName_; -// }; -// } // namespace OHOS -// } // namespace Notification - -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index 1953c6a0e..e190d2890 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -64,7 +64,6 @@ void AdvancedNotificationServiceAbility::OnStart() void AdvancedNotificationServiceAbility::OnStop() { service_ = nullptr; - // reminderAgent_ = nullptr; } void AdvancedNotificationServiceAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) diff --git a/services/ans/src/reminder_config_change_observer.cpp b/services/ans/src/reminder_config_change_observer.cpp deleted file mode 100644 index 03ce6e250..000000000 --- a/services/ans/src/reminder_config_change_observer.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// /* -// * Copyright (c) 2023 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 "reminder_config_change_observer.h" - -// #include "ans_log_wrapper.h" -// #include "reminder_data_manager.h" - -// namespace OHOS { -// namespace Notification { - -// void ReminderConfigChangeObserver::OnConfigurationUpdated(const AppExecFwk::Configuration &configuration) -// { -// ANSR_LOGD("OnConfigurationUpdated."); -// auto reminderDataMgr = ReminderDataManager::GetInstance(); -// if (reminderDataMgr == nullptr) { -// ANSR_LOGW("Reminder data manager is nullptr"); -// return; -// } -// std::string newLanguageInfo = configuration.GetItem(AAFwk::GlobalConfigurationKey::SYSTEM_LANGUAGE); -// if (!newLanguageInfo.empty() && newLanguageInfo != languageInfo_) { -// ANSR_LOGD("language change: %{public}s -> %{public}s", languageInfo_.c_str(), newLanguageInfo.c_str()); -// reminderDataMgr->OnLanguageChanged(); -// languageInfo_ = newLanguageInfo; -// } -// } - -// } // namespace Notification -// } // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp deleted file mode 100644 index 185ab9c7c..000000000 --- a/services/ans/src/reminder_data_manager.cpp +++ /dev/null @@ -1,2073 +0,0 @@ -// /* -// * Copyright (c) 2021-2023 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 "reminder_data_manager.h" - -// #include "ability_manager_client.h" -// #include "access_token_helper.h" -// #include "ans_log_wrapper.h" -// #include "ans_const_define.h" -// #include "common_event_support.h" -// #include "common_event_manager.h" -// #include "reminder_request_calendar.h" -// #include "in_process_call_wrapper.h" -// #ifdef DEVICE_STANDBY_ENABLE -// #include "standby_service_client.h" -// #include "allow_type.h" -// #endif -// #include "ipc_skeleton.h" -// #include "notification_slot.h" -// #include "os_account_manager.h" -// #include "os_account_manager_helper.h" -// #include "reminder_event_manager.h" -// #include "time_service_client.h" -// #include "singleton.h" -// #include "locale_config.h" -// #include "bundle_manager_helper.h" -// #include "datashare_predicates_object.h" -// #include "datashare_value_object.h" -// #include "datashare_helper.h" -// #include "data_share_permission.h" -// #include "datashare_errno.h" -// #include "datashare_template.h" -// #include "system_ability_definition.h" -// #include "app_mgr_constants.h" -// #include "iservice_registry.h" -// #include "config_policy_utils.h" -// #include "hitrace_meter_adapter.h" -// #ifdef HAS_HISYSEVENT_PART -// #include "hisysevent.h" -// #endif - -// namespace OHOS { -// namespace Notification { -// namespace { -// const std::string ALL_PACKAGES = "allPackages"; -// const int32_t MAIN_USER_ID = 100; -// #ifdef DEVICE_STANDBY_ENABLE -// const int REASON_APP_API = 1; -// #endif -// const int INDEX_KEY = 0; -// const int INDEX_TYPE = 1; -// const int INDEX_VALUE = 2; -// } - -// /** -// * Default reminder sound. -// */ -// const std::string DEFAULT_REMINDER_SOUND_1 = "/system/etc/capture.ogg"; -// const std::string DEFAULT_REMINDER_SOUND_2 = "resource/media/audio/alarms/Aegean_Sea.ogg"; - -// std::shared_ptr ReminderDataManager::REMINDER_DATA_MANAGER = nullptr; -// std::mutex ReminderDataManager::MUTEX; -// std::mutex ReminderDataManager::SHOW_MUTEX; -// std::mutex ReminderDataManager::ALERT_MUTEX; -// std::mutex ReminderDataManager::TIMER_MUTEX; -// std::mutex ReminderDataManager::ACTIVE_MUTEX; -// constexpr int32_t CONNECT_EXTENSION_INTERVAL = 100; -// constexpr int32_t CONNECT_EXTENSION_MAX_RETRY_TIMES = 3; -// std::shared_ptr ReminderDataManager::serviceQueue_ = nullptr; -// ReminderDataManager::~ReminderDataManager() = default; - -// ErrCode ReminderDataManager::PublishReminder(const sptr &reminder, -// const sptr &bundleOption) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// uint32_t callerTokenId = IPCSkeleton::GetCallingTokenID(); -// if (callerTokenId == 0) { -// ANSR_LOGE("pushlish failed, callerTokenId is 0"); -// return ERR_REMINDER_CALLER_TOKEN_INVALID; -// } - -// if (!IsActionButtonDataShareValid(reminder, callerTokenId)) { -// return ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED; -// } - -// if (CheckReminderLimitExceededLocked(bundleOption, reminder)) { -// return ERR_REMINDER_NUMBER_OVERLOAD; -// } -// UpdateAndSaveReminderLocked(reminder, bundleOption); -// queue_->submit([this, reminder]() { -// StartRecentReminder(); -// }); -// return ERR_OK; -// } - -// ErrCode ReminderDataManager::CancelReminder( -// const int32_t &reminderId, const sptr &bundleOption) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("cancel reminder id: %{public}d", reminderId); -// sptr reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName()); -// if (reminder == nullptr) { -// ANSR_LOGW("Cancel reminder, not find the reminder"); -// return ERR_REMINDER_NOT_EXIST; -// } -// if (!CheckIsSameApp(reminder, bundleOption)) { -// ANSR_LOGW("Not find the reminder due to not match"); -// return ERR_REMINDER_NOT_EXIST; -// } -// if (activeReminderId_ == reminderId) { -// ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId); -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_->OnStop(); -// } -// StopTimerLocked(TimerType::TRIGGER_TIMER); -// } -// if (alertingReminderId_ == reminderId) { -// StopSoundAndVibrationLocked(reminder); -// StopTimerLocked(TimerType::ALERTING_TIMER); -// } -// CancelNotification(reminder); -// RemoveReminderLocked(reminderId); -// StartRecentReminder(); -// return ERR_OK; -// } - -// ErrCode ReminderDataManager::CancelAllReminders(const std::string& packageName, const int32_t userId, -// const int32_t uid) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGD("CancelAllReminders, userId=%{private}d, pkgName=%{public}s", userId, packageName.c_str()); -// CancelRemindersImplLocked(packageName, userId, uid); -// return ERR_OK; -// } - -// sptr ReminderDataManager::CheckExcludeDateParam(const int32_t reminderId, -// const sptr &bundleOption) -// { -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGW("Check reminder failed, not find the reminder"); -// return nullptr; -// } -// if (!CheckIsSameApp(reminder, bundleOption)) { -// ANSR_LOGW("Check reminder failed, due to not match"); -// return nullptr; -// } -// if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR -// || !reminder->IsRepeat()) { -// ANSR_LOGW("Check reminder failed, due to type not match or not repeat"); -// return nullptr; -// } -// return reminder; -// } - -// ErrCode ReminderDataManager::AddExcludeDate(const int32_t reminderId, const uint64_t date, -// const sptr &bundleOption) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); -// if (reminder == nullptr) { -// return ERR_REMINDER_NOT_EXIST; -// } -// { -// std::lock_guard locker(ReminderDataManager::MUTEX); -// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); -// calendar->AddExcludeDate(date); -// store_->UpdateOrInsert(reminder, bundleOption); -// } -// return ERR_OK; -// } - -// ErrCode ReminderDataManager::DelExcludeDates(const int32_t reminderId, -// const sptr &bundleOption) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); -// if (reminder == nullptr) { -// return ERR_REMINDER_NOT_EXIST; -// } -// { -// std::lock_guard locker(ReminderDataManager::MUTEX); -// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); -// calendar->DelExcludeDates(); -// store_->UpdateOrInsert(reminder, bundleOption); -// } -// return ERR_OK; -// } - -// ErrCode ReminderDataManager::GetExcludeDates(const int32_t reminderId, -// const sptr &bundleOption, std::vector& dates) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// sptr reminder = CheckExcludeDateParam(reminderId, bundleOption); -// if (reminder == nullptr) { -// return ERR_REMINDER_NOT_EXIST; -// } -// { -// std::lock_guard locker(ReminderDataManager::MUTEX); -// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); -// dates = calendar->GetExcludeDates(); -// } -// return ERR_OK; -// } - -// void ReminderDataManager::GetValidReminders( -// const sptr &bundleOption, std::vector> &reminders) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto& eachReminder : reminderVector_) { -// if (eachReminder->IsExpired()) { -// continue; -// } - -// if (CheckIsSameApp(eachReminder, bundleOption)) { -// reminders.push_back(eachReminder); -// } -// } -// } - -// void ReminderDataManager::CancelAllReminders(const int32_t userId) -// { -// ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); -// CancelRemindersImplLocked(ALL_PACKAGES, userId, -1); -// } - -// void ReminderDataManager::CancelRemindersImplLocked(const std::string &packageName, const int32_t userId, -// const int32_t uid) -// { -// MUTEX.lock(); -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// if (activeReminderId_ != -1 && IsMatched(activeReminder_, packageName, userId, uid)) { -// activeReminder_->OnStop(); -// StopTimer(TimerType::TRIGGER_TIMER); -// ANSR_LOGD("Stop active reminder, reminderId=%{public}d", activeReminderId_.load()); -// } -// } -// for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { -// if (IsMatched(*vit, packageName, userId, uid)) { -// if ((*vit)->IsAlerting()) { -// StopAlertingReminder(*vit); -// } -// CancelNotification(*vit); -// RemoveFromShowedReminders(*vit); -// vit = reminderVector_.erase(vit); -// totalCount_--; -// continue; -// } -// ++vit; -// } -// if (packageName == ALL_PACKAGES) { -// store_->DeleteUser(userId); -// } else { -// store_->Delete(packageName, userId, uid); -// } -// MUTEX.unlock(); -// StartRecentReminder(); -// } - -// bool ReminderDataManager::IsMatchedForGroupIdAndPkgName(const sptr &reminder, -// const std::string &packageName, const std::string &groupId) const -// { -// std::string packageNameTemp = reminder->GetBundleName(); -// if (packageNameTemp.empty()) { -// ANSR_LOGW("reminder package name is null"); -// return false; -// } -// if (packageNameTemp == packageName && reminder->GetGroupId() == groupId) { -// return true; -// } -// return false; -// } - -// bool ReminderDataManager::IsMatched(const sptr &reminder, -// const std::string &packageName, const int32_t userId, const int32_t uid) const -// { -// if (reminder->GetUserId() != userId) { -// return false; -// } -// if (packageName == ALL_PACKAGES) { -// return true; -// } -// if (reminder->GetBundleName() != packageName) { -// return false; -// } -// if (uid != -1 && reminder->GetUid() == uid) { -// return true; -// } -// return false; -// } - -// void ReminderDataManager::CancelNotification(const sptr &reminder) const -// { -// if (!(reminder->IsShowing())) { -// ANSR_LOGD("No need to cancel notification"); -// return; -// } -// sptr notification = reminder->GetNotificationRequest(); -// if (notification == nullptr) { -// ANSR_LOGW("Cancel notification fail"); -// return; -// } -// ANSR_LOGD("Cancel notification"); -// if (advancedNotificationService_ == nullptr) { -// ANSR_LOGE("Cancel notification fail"); -// return; -// } -// sptr bundleOption = reminder->GetNotificationBundleOption(); -// advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), -// ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); -// } - -// bool ReminderDataManager::CheckReminderLimitExceededLocked(const sptr &bundleOption, -// const sptr &reminder) const -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { -// ANSR_LOGW("The number of validate reminders exceeds the system upper limit:%{public}d, \ -// and new reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); -// return true; -// } -// int32_t count = 0; -// for (const auto& eachReminder : reminderVector_) { -// if (eachReminder->IsExpired()) { -// continue; -// } -// if (CheckIsSameApp(eachReminder, bundleOption)) { -// count++; -// } -// } -// auto maxReminderNum = reminder->IsSystemApp() ? MAX_NUM_REMINDER_LIMIT_SYS_APP : MAX_NUM_REMINDER_LIMIT_APP; -// if (count >= maxReminderNum) { -// ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ -// reminder can not be published", maxReminderNum); -// return true; -// } -// return false; -// } - -// void ReminderDataManager::AddToShowedReminders(const sptr &reminder) -// { -// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); -// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { -// if (reminder->GetReminderId() == (*it)->GetReminderId()) { -// ANSR_LOGD("Showed reminder is already exist"); -// return; -// } -// } -// showedReminderVector_.push_back(reminder); -// } - -// void ReminderDataManager::OnUserRemove(const int32_t& userId) -// { -// if (!IsReminderAgentReady()) { -// ANSR_LOGW("Give up to remove user id: %{private}d for reminderAgent is not ready", userId); -// return; -// } -// CancelAllReminders(userId); -// } - -// void ReminderDataManager::OnUserSwitch(const int32_t& userId) -// { -// ANSR_LOGD("Switch user id from %{private}d to %{private}d", currentUserId_, userId); -// currentUserId_ = userId; -// std::lock_guard lock(ReminderDataManager::MUTEX); -// if ((alertingReminderId_ != -1) && IsReminderAgentReady()) { -// TerminateAlerting(alertingReminder_, "OnUserSwitch"); -// } -// } - -// void ReminderDataManager::OnProcessDiedLocked(const sptr &bundleOption) -// { -// std::string bundleName = bundleOption->GetBundleName(); -// int32_t uid = bundleOption->GetUid(); -// ANSR_LOGD("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); -// std::lock_guard locker(ReminderDataManager::MUTEX); -// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); -// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { -// if ((*it)->GetBundleName() != bundleName || (*it)->GetUid() != uid) { -// continue; -// } -// if ((*it)->IsAlerting()) { -// TerminateAlerting((*it), "onProcessDied"); -// } else { -// CancelNotification(*it); -// (*it)->OnClose(false); -// showedReminderVector_.erase(it); -// --it; -// } -// store_->UpdateOrInsert((*it), bundleOption); -// } -// } - -// void ReminderDataManager::InitTimerInfo(std::shared_ptr &sharedTimerInfo, -// const sptr &reminderRequest, TimerType reminderType) const -// { -// uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); -// uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); -// sharedTimerInfo->SetRepeat(false); -// sharedTimerInfo->SetInterval(0); - -// sharedTimerInfo->SetBundleName(reminderRequest->GetBundleName()); -// sharedTimerInfo->SetUid(reminderRequest->GetUid()); - -// int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); -// sharedTimerInfo->SetType(timerType); -// } - -// std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type, -// const sptr &reminderRequest) const -// { -// auto sharedTimerInfo = std::make_shared(); -// if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { -// ANSR_LOGE("Failed to set timer type."); -// return nullptr; -// } -// InitTimerInfo(sharedTimerInfo, reminderRequest, type); - -// int32_t requestCode = 10; -// std::vector flags; -// flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); - -// auto want = std::make_shared(); -// switch (type) { -// case (TimerType::TRIGGER_TIMER): { -// want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); -// sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); -// want->SetParam(ReminderRequest::PARAM_REMINDER_ID, activeReminderId_); -// break; -// } -// case (TimerType::ALERTING_TIMER): { -// if (alertingReminderId_ == -1) { -// ANSR_LOGE("Create alerting time out timer Illegal."); -// return sharedTimerInfo; -// } -// want->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); -// sharedTimerInfo->SetAction(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); -// want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_); -// break; -// } -// default: -// ANSR_LOGE("TimerType not support"); -// break; -// } -// std::vector> wants; -// wants.push_back(want); -// AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( -// requestCode, -// AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, -// flags, wants, nullptr); - -// std::string identity = IPCSkeleton::ResetCallingIdentity(); -// std::shared_ptr wantAgent = -// AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); -// IPCSkeleton::SetCallingIdentity(identity); - -// sharedTimerInfo->SetWantAgent(wantAgent); -// return sharedTimerInfo; -// } - -// sptr ReminderDataManager::FindReminderRequestLocked(const int32_t &reminderId) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// if (reminderId == (*it)->GetReminderId()) { -// return *it; -// } -// } -// ANSR_LOGD("Not find the reminder"); -// return nullptr; -// } - -// sptr ReminderDataManager::FindReminderRequestLocked( -// const int32_t &reminderId, const std::string &pkgName) -// { -// sptr reminder = FindReminderRequestLocked(reminderId); -// std::lock_guard lock(ReminderDataManager::MUTEX); -// if (reminder == nullptr) { -// return nullptr; -// } -// if (reminder->GetCreatorBundleName() != pkgName) { -// ANSR_LOGW("Not find the reminder due to package name not match"); -// return nullptr; -// } -// return reminder; -// } - -// bool ReminderDataManager::cmp(sptr &reminderRequest, sptr &other) -// { -// return reminderRequest->GetTriggerTimeInMilli() < other->GetTriggerTimeInMilli(); -// } - -// void ReminderDataManager::CloseReminder(const OHOS::EventFwk::Want &want, bool cancelNotification) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// std::string packageName = reminder->GetBundleName(); -// std::string groupId = reminder->GetGroupId(); -// if (!(packageName.empty() || groupId.empty())) { -// ANSR_LOGD("this reminder can close by groupId"); -// CloseRemindersByGroupId(reminderId, packageName, groupId); -// } -// CloseReminder(reminder, cancelNotification); -// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); -// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); -// StartRecentReminder(); -// } - -// void ReminderDataManager::CloseRemindersByGroupId(const int32_t &oldReminderId, const std::string &packageName, -// const std::string &groupId) -// { -// if (packageName == "") { -// ANSR_LOGD("packageName is empty"); -// return; -// } -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto vit = reminderVector_.begin(); vit != reminderVector_.end(); vit++) { -// sptr reminder = *vit; -// if (reminder == nullptr) { -// ANSR_LOGD("reminder is null"); -// continue; -// } -// int32_t reminderId = reminder->GetReminderId(); -// if (reminderId == oldReminderId) { -// ANSR_LOGD("The old and new reminder are the same"); -// continue; -// } -// if (IsMatchedForGroupIdAndPkgName(reminder, packageName, groupId)) { -// reminder->SetExpired(true); -// reminder->SetStateToInActive(); -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -// ResetStates(TimerType::TRIGGER_TIMER); -// ANSR_LOGD("Cancel reminders by groupid, reminder is %{public}s", reminder->Dump().c_str()); -// } -// } -// } - -// void ReminderDataManager::CloseReminder(const sptr &reminder, bool cancelNotification) -// { -// int32_t reminderId = reminder->GetReminderId(); -// if (activeReminderId_ == reminderId) { -// ANSR_LOGD("Stop active reminder due to CloseReminder"); -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_->OnStop(); -// } -// StopTimerLocked(TimerType::TRIGGER_TIMER); -// } -// if (alertingReminderId_ == reminderId) { -// StopSoundAndVibrationLocked(reminder); -// StopTimerLocked(TimerType::ALERTING_TIMER); -// } -// reminder->OnClose(true); -// RemoveFromShowedReminders(reminder); -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -// if (cancelNotification) { -// CancelNotification(reminder); -// } -// } - -// std::shared_ptr ReminderDataManager::GetInstance() -// { -// return REMINDER_DATA_MANAGER; -// } - -// std::shared_ptr ReminderDataManager::InitInstance( -// const sptr &advancedNotificationService) -// { -// if (REMINDER_DATA_MANAGER == nullptr) { -// REMINDER_DATA_MANAGER = std::make_shared(); -// REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; -// ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); -// } -// return REMINDER_DATA_MANAGER; -// } - -// bool ReminderDataManager::CheckUpdateConditions(const sptr &reminder, -// const ReminderRequest::ActionButtonType &actionButtonType, -// const std::map &actionButtonMap) -// { -// if (!reminder->IsSystemApp()) { -// ANSR_LOGI("UpdateAppDatabase faild, is not SystemApp"); -// return false; -// } -// if (actionButtonType == ReminderRequest::ActionButtonType::INVALID) { -// ANSR_LOGI("actionButtonType is NVALID"); -// return false; -// } -// if (!actionButtonMap.count(actionButtonType)) { -// ANSR_LOGI("actionButtonType does not exist"); -// return false; -// } -// if (actionButtonMap.at(actionButtonType).dataShareUpdate == nullptr) { -// ANSR_LOGI("dataShareUpdate is null"); -// return false; -// } -// if (actionButtonMap.at(actionButtonType).dataShareUpdate->uri == "" || -// actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo == "" || -// actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket == "") { -// ANSR_LOGI("datashare parameter is invalid"); -// return false; -// } -// return true; -// } - -// void ReminderDataManager::UpdateAppDatabase(const sptr &reminder, -// const ReminderRequest::ActionButtonType &actionButtonType) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// auto actionButtonMap = reminder->GetActionButtons(); -// if (!CheckUpdateConditions(reminder, actionButtonType, actionButtonMap)) { -// return; -// } -// // init default dstBundleName -// std::string dstBundleName = reminder->GetBundleName(); -// GenDstBundleName(dstBundleName, actionButtonMap.at(actionButtonType).dataShareUpdate->uri); - -// DataShare::CreateOptions options; -// options.enabled_ = true; -// auto userID = reminder->GetUserId(); -// auto tokenID = IPCSkeleton::GetSelfTokenID(); -// std::string uriStr = actionButtonMap.at(actionButtonType).dataShareUpdate->uri + "?user=" + std::to_string(userID) + -// "&srcToken=" + std::to_string(tokenID) + "&dstBundleName=" + dstBundleName; - -// // create datashareHelper -// std::shared_ptr dataShareHelper = DataShare::DataShareHelper::Creator(uriStr, options); -// if (dataShareHelper == nullptr) { -// ANSR_LOGE("create datashareHelper failed"); -// return; -// } -// // gen uri equalTo valuesBucket -// Uri uri(uriStr); - -// DataShare::DataSharePredicates predicates; -// std::vector equalToVector = ReminderRequest::StringSplit( -// actionButtonMap.at(actionButtonType).dataShareUpdate->equalTo, ReminderRequest::SEP_BUTTON_VALUE_TYPE); -// GenPredicates(predicates, equalToVector); - -// DataShare::DataShareValuesBucket valuesBucket; -// std::vector valuesBucketVector = ReminderRequest::StringSplit( -// actionButtonMap.at(actionButtonType).dataShareUpdate->valuesBucket, ReminderRequest::SEP_BUTTON_VALUE_TYPE); -// GenValuesBucket(valuesBucket, valuesBucketVector); - -// // update app store -// int retVal = dataShareHelper->Update(uri, predicates, valuesBucket); -// if (retVal > 0) { -// // update success -// ANSR_LOGI("update app store success retval:%{public}d", retVal); -// } -// } - -// void ReminderDataManager::GenPredicates(DataShare::DataSharePredicates &predicates, -// const std::vector &equalToVector) -// { -// // predicates -// for (auto &it : equalToVector) { -// std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); -// if (temp.size() <= INDEX_VALUE) { -// continue; -// } -// if (temp[INDEX_TYPE] == "string") { -// predicates.EqualTo(temp[INDEX_KEY], temp[INDEX_VALUE]); -// } else if (temp[INDEX_TYPE] == "double") { -// predicates.EqualTo(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); -// } else if (temp[INDEX_TYPE] == "bool") { -// bool valueBool = false; -// if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true" || temp[INDEX_VALUE] == "True") { -// valueBool = true; -// } -// predicates.EqualTo(temp[INDEX_KEY], valueBool); -// } -// } -// } - -// void ReminderDataManager::GenValuesBucket(DataShare::DataShareValuesBucket & valuesBucket, -// const std::vector &valuesBucketVector) -// { -// // valuesBucket -// for (auto &it : valuesBucketVector) { -// std::vector temp = ReminderRequest::StringSplit(it, ReminderRequest::SEP_BUTTON_VALUE); -// if (temp.size() <= INDEX_VALUE) { -// continue; -// } -// if (temp[INDEX_TYPE] == "string") { -// valuesBucket.Put(temp[INDEX_KEY], temp[INDEX_VALUE]); -// } else if (temp[INDEX_TYPE] == "double") { -// valuesBucket.Put(temp[INDEX_KEY], std::stod(temp[INDEX_VALUE])); -// } else if (temp[INDEX_TYPE] == "bool") { -// bool valueBool = false; -// if (temp[INDEX_VALUE] == "1" || temp[INDEX_VALUE] == "true") { -// valueBool = true; -// } -// valuesBucket.Put(temp[INDEX_KEY], valueBool); -// } else if (temp[INDEX_TYPE] == "null") { -// valuesBucket.Put(temp[INDEX_KEY]); -// } else if (temp[INDEX_TYPE] == "vector") { -// std::vector arr = ReminderRequest::StringSplit(temp[INDEX_VALUE], -// ReminderRequest::SEP_BUTTON_VALUE_BLOB); -// std::vector value; -// for (auto &num : arr) { -// value.emplace_back(static_cast(std::atoi(num.c_str()))); -// } -// valuesBucket.Put(temp[INDEX_KEY], value); -// } -// } -// } - -// void ReminderDataManager::GenDstBundleName(std::string &dstBundleName, const std::string &uri) const -// { -// size_t left = 0; -// size_t right = 0; -// left = uri.find("/", left); -// right = uri.find("/", left + 1); -// while (right != std::string::npos && right - left <= 1) { -// left = right + 1; -// right = uri.find("/", left); -// } -// if (left == std::string::npos) { -// return; -// } -// if (right != std::string::npos) { -// dstBundleName = uri.substr(left, right - left); -// } else { -// dstBundleName = uri.substr(left); -// } -// } - -// void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) -// { -// if (!IsSystemReady()) { -// ANSR_LOGW("bundle service or ability service not ready."); -// return; -// } -// std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; -// ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); -// if (activeReminderId_ != -1) { -// ANSR_LOGD("Stop active reminder due to date/time or timeZone change"); -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_->OnStop(); -// } -// StopTimerLocked(TimerType::TRIGGER_TIMER); -// } -// std::vector> showImmediately; -// std::vector> extensionReminders; -// RefreshRemindersLocked(type, showImmediately, extensionReminders); -// HandleImmediatelyShow(showImmediately, true); -// HandleExtensionReminder(extensionReminders); -// StartRecentReminder(); -// } - -// void ReminderDataManager::TerminateAlerting(const OHOS::EventFwk::Want &want) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// TerminateAlerting(reminder, "timeOut"); -// } - -// void ReminderDataManager::TerminateAlerting(const uint16_t waitInSecond, const sptr &reminder) -// { -// sleep(waitInSecond); -// TerminateAlerting(reminder, "waitInMillis"); -// } - -// void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) -// { -// if (reminder == nullptr) { -// ANSR_LOGE("TerminateAlerting illegal."); -// return; -// } -// ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", -// reminder->Dump().c_str(), reason.c_str()); -// StopAlertingReminder(reminder); - -// if (!reminder->OnTerminate()) { -// return; -// } -// int32_t reminderId = reminder->GetReminderId(); -// sptr bundleOption = reminder->GetNotificationBundleOption(); -// sptr notificationRequest = reminder->GetNotificationRequest(); -// if (bundleOption == nullptr) { -// ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); -// return; -// } -// ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); -// UpdateNotification(reminder, false); -// if (advancedNotificationService_ == nullptr) { -// ANSR_LOGE("Ans instance is null."); -// return; -// } -// // Set the notification SoundEnabled and VibrationEnabled by soltType -// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); -// advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); -// store_->UpdateOrInsert(reminder, bundleOption); -// } - -// void ReminderDataManager::UpdateAndSaveReminderLocked( -// const sptr &reminder, const sptr &bundleOption) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// reminder->InitReminderId(); -// int32_t userId = -1; -// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); -// reminder->InitUserId(userId); -// reminder->InitUid(bundleOption->GetUid()); -// reminder->InitBundleName(bundleOption->GetBundleName()); - -// if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) { -// ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); -// reminder->SetExpired(true); -// } -// reminder->SetNotificationBundleOption(bundleOption); -// reminderVector_.push_back(reminder); -// totalCount_++; -// store_->UpdateOrInsert(reminder, bundleOption); -// } - -// void ReminderDataManager::SetService(sptr &advancedNotificationService) -// { -// advancedNotificationService_ = advancedNotificationService; -// } - -// bool ReminderDataManager::ShouldAlert(const sptr &reminder) const -// { -// if (reminder == nullptr) { -// return false; -// } -// int32_t reminderId = reminder->GetReminderId(); -// sptr bundleOption = reminder->GetNotificationBundleOption(); -// if (bundleOption == nullptr) { -// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); -// return false; -// } -// int32_t userId = -1; -// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); -// if (currentUserId_ != userId) { -// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for not in active user, " \ -// "current user id: %{private}d, reminder user id: %{private}d", reminderId, currentUserId_, userId); -// return false; -// } - -// sptr date; -// ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); -// if (errCode != ERR_OK) { -// ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); -// return true; -// } -// if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { -// return true; -// } -// std::vector> slots; -// errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); -// if (errCode != ERR_OK) { -// ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); -// return false; -// } -// for (auto slot : slots) { -// if (slot->GetType() != reminder->GetSlotType()) { -// continue; -// } -// if (slot->IsEnableBypassDnd()) { -// ANSR_LOGD("Not silent for enable by pass Dnd, reminderId=%{public}d", reminderId); -// return true; -// } -// } -// ANSR_LOGD("The reminder (reminderId=%{public}d) is silent for Dnd", reminderId); -// return false; -// } - -// void ReminderDataManager::ShowActiveReminder(const EventFwk::Want &want) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// ANSR_LOGI("Begin to show reminder(reminderId=%{public}d)", reminderId); -// if (reminderId == activeReminderId_) { -// ResetStates(TimerType::TRIGGER_TIMER); -// } -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// if (HandleSysTimeChange(reminder)) { -// return; -// } -// ShowActiveReminderExtendLocked(reminder); -// StartRecentReminder(); -// } - -// bool ReminderDataManager::HandleSysTimeChange(const sptr reminder) const -// { -// if (reminder->CanShow()) { -// return false; -// } else { -// ANSR_LOGI("handleSystimeChange, no need to show reminder again."); -// return true; -// } -// } - -// void ReminderDataManager::SetActiveReminder(const sptr &reminder) -// { -// if (reminder == nullptr) { -// // activeReminder_ should not be set with null as it point to actual object. -// activeReminderId_ = -1; -// } else { -// activeReminderId_ = reminder->GetReminderId(); -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_ = reminder; -// } -// ANSR_LOGD("Set activeReminderId=%{public}d", activeReminderId_.load()); -// } - -// void ReminderDataManager::SetAlertingReminder(const sptr &reminder) -// { -// if (reminder == nullptr) { -// // alertingReminder_ should not be set with null as it point to actual object. -// alertingReminderId_ = -1; -// } else { -// alertingReminderId_ = reminder->GetReminderId(); -// alertingReminder_ = reminder; -// } -// ANSR_LOGD("Set alertingReminderId=%{public}d", alertingReminderId_.load()); -// } - -// void ReminderDataManager::ShowActiveReminderExtendLocked(sptr &reminder) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); -// bool isAlerting = false; -// sptr playSoundReminder = nullptr; -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// if ((*it)->IsExpired()) { -// continue; -// } -// uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli(); -// if (tempTriggerTime < triggerTime) { -// ANSR_LOGD("this reminder triggerTime is less than target triggerTime."); -// continue; -// } -// if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { -// continue; -// } -// if (!(*it)->IsNeedNotification()) { -// continue; -// } -// ReminderDataManager::AsyncStartExtensionAbility((*it), CONNECT_EXTENSION_MAX_RETRY_TIMES); -// if ((*it)->CheckExcludeDate()) { -// ANSR_LOGI("reminder[%{public}d] trigger time is in exclude date", (*it)->GetReminderId()); -// continue; -// } -// if (((*it)->GetRingDuration() > 0) && !isAlerting) { -// playSoundReminder = (*it); -// isAlerting = true; -// } else { -// ShowReminder((*it), false, false, false, false); -// } -// } -// if (playSoundReminder != nullptr) { -// ShowReminder(playSoundReminder, true, false, false, true); -// } -// } - -// bool ReminderDataManager::StartExtensionAbility(const sptr &reminder) -// { -// ANSR_LOGD("StartExtensionAbility"); -// if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { -// ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); -// std::shared_ptr wantInfo = calendar->GetRRuleWantAgentInfo(); -// if (wantInfo != nullptr && wantInfo->pkgName.size() != 0 && wantInfo->abilityName.size() != 0) { -// AAFwk::Want want; -// want.SetElementName(wantInfo->pkgName, wantInfo->abilityName); -// want.SetParam(ReminderRequest::PARAM_REMINDER_ID, reminder->GetReminderId()); -// int32_t result = IN_PROCESS_CALL( -// AAFwk::AbilityManagerClient::GetInstance()->StartExtensionAbility(want, nullptr)); -// if (result != ERR_OK) { -// ANSR_LOGE("StartExtensionAbility failed[%{public}d]", result); -// return false; -// } -// } -// } -// return true; -// } - -// void ReminderDataManager::AsyncStartExtensionAbility(const sptr &reminder, int32_t times) -// { -// auto manager = ReminderDataManager::GetInstance(); -// if (manager == nullptr) { -// ANSR_LOGW("ReminderDataManager is nullptr."); -// return; -// } -// if (!manager->IsSystemReady()) { -// ANSR_LOGW("bundle service or ability service not ready."); -// return; -// } -// if (!reminder->IsSystemApp()) { -// ANSR_LOGI("Start extension ability failed, is not system app"); -// return; -// } -// times--; -// bool ret = ReminderDataManager::StartExtensionAbility(reminder); -// if (!ret && times > 0 && serviceQueue_ != nullptr) { -// ANSR_LOGD("StartExtensionAbilty failed, reminder times: %{public}d", times); -// ffrt::task_attr taskAttr; -// taskAttr.delay(CONNECT_EXTENSION_INTERVAL); -// auto callback = [reminder, times]() { ReminderDataManager::AsyncStartExtensionAbility(reminder, times); }; -// serviceQueue_->submit(callback, taskAttr); -// } -// } - -// void ReminderDataManager::ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, -// const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout) -// { -// ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", -// static_cast(isNeedToPlaySound), reminder->Dump().c_str()); -// int32_t reminderId = reminder->GetReminderId(); -// sptr bundleOption = reminder->GetNotificationBundleOption(); -// sptr notificationRequest = reminder->GetNotificationRequest(); -// if (bundleOption == nullptr) { -// ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); -// return; -// } -// if (advancedNotificationService_ == nullptr) { -// ANSR_LOGE("ShowReminder fail"); -// reminder->OnShow(false, isSysTimeChanged, false); -// store_->UpdateOrInsert(reminder, bundleOption); -// return; -// } -// if (!IsAllowedNotify(reminder)) { -// ANSR_LOGE("Not allow to notify."); -// reminder->OnShow(false, isSysTimeChanged, false); -// store_->UpdateOrInsert(reminder, bundleOption); -// return; -// } -// ReportSysEvent(reminder); -// bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; -// reminder->OnShow(toPlaySound, isSysTimeChanged, true); -// AddToShowedReminders(reminder); -// UpdateNotification(reminder, false); // this should be called after OnShow - -// if (alertingReminderId_ != -1) { -// TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); -// } -// // Set the notification SoundEnabled and VibrationEnabled by soltType -// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); -// ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); -// if (errCode != ERR_OK) { -// reminder->OnShowFail(); -// RemoveFromShowedReminders(reminder); -// } else { -// if (toPlaySound) { -// PlaySoundAndVibration(reminder); // play sound and vibration -// if (needScheduleTimeout) { -// StartTimer(reminder, TimerType::ALERTING_TIMER); -// } else { -// TerminateAlerting(1, reminder); -// } -// } -// HandleSameNotificationIdShowing(reminder); -// } -// store_->UpdateOrInsert(reminder, bundleOption); - -// if (isNeedToStartNext) { -// StartRecentReminder(); -// } -// } - -// void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) -// { -// if (isSnooze) { -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); -// } else { -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); -// } -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); -// reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); -// } - -// void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// SnoozeReminderImpl(reminder); -// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::SNOOZE); -// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::SNOOZE); -// } - -// void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) -// { -// ANSR_LOGI("Snooze the reminder request, %{public}s", reminder->Dump().c_str()); -// int32_t reminderId = reminder->GetReminderId(); -// if (activeReminderId_ == reminderId) { -// ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_.load()); -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_->OnStop(); -// } -// StopTimerLocked(TimerType::TRIGGER_TIMER); -// } - -// // 1) Snooze the reminder by manual -// if (alertingReminderId_ == reminder->GetReminderId()) { -// StopSoundAndVibrationLocked(reminder); -// StopTimerLocked(TimerType::ALERTING_TIMER); -// } -// reminder->OnSnooze(); -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); - -// // 2) Show the notification dialog in the systemUI -// sptr bundleOption = reminder->GetNotificationBundleOption(); -// sptr notificationRequest = reminder->GetNotificationRequest(); -// if (bundleOption == nullptr) { -// ANSR_LOGW("snoozeReminder, invalid bundle option"); -// return; -// } -// ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); -// UpdateNotification(reminder, true); -// if (advancedNotificationService_ == nullptr) { -// ANSR_LOGE("Ans instance is null"); -// return; -// } -// // Set the notification SoundEnabled and VibrationEnabled by soltType -// advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); -// advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); -// StartRecentReminder(); -// } - -// void ReminderDataManager::StartRecentReminder() -// { -// sptr reminder = GetRecentReminderLocked(); -// if (reminder == nullptr) { -// ANSR_LOGI("No reminder need to start"); -// SetActiveReminder(reminder); -// return; -// } -// if (activeReminderId_ == reminder->GetReminderId()) { -// ANSR_LOGI("Recent reminder has already run, no need to start again."); -// return; -// } -// if (activeReminderId_ != -1) { -// { -// std::lock_guard locker(ReminderDataManager::ACTIVE_MUTEX); -// activeReminder_->OnStop(); -// store_->UpdateOrInsert(activeReminder_, activeReminder_->GetNotificationBundleOption()); -// } -// StopTimerLocked(TimerType::TRIGGER_TIMER); -// } -// ANSR_LOGI("Start recent reminder"); -// StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); -// reminder->OnStart(); -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -// } - -// void ReminderDataManager::StopAlertingReminder(const sptr &reminder) -// { -// if (reminder == nullptr) { -// ANSR_LOGE("StopAlertingReminder illegal."); -// return; -// } -// if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { -// ANSR_LOGE("StopAlertingReminder is illegal."); -// return; -// } -// StopSoundAndVibration(alertingReminder_); -// StopTimer(TimerType::ALERTING_TIMER); -// } - -// std::string ReminderDataManager::Dump() const -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// std::map>> bundleNameMap; -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// if ((*it)->IsExpired()) { -// continue; -// } -// std::string bundleName = (*it)->GetBundleName(); -// auto val = bundleNameMap.find(bundleName); -// if (val == bundleNameMap.end()) { -// std::vector> reminders; -// reminders.push_back(*it); -// bundleNameMap.insert(std::pair>>(bundleName, reminders)); -// } else { -// val->second.push_back(*it); -// } -// } - -// std::string allReminders = ""; -// for (auto it = bundleNameMap.begin(); it != bundleNameMap.end(); ++it) { -// std::string bundleName = it->first; -// std::vector> reminders = it->second; -// sort(reminders.begin(), reminders.end(), cmp); -// std::string oneBundleReminders = bundleName + ":{\n"; -// oneBundleReminders += " totalCount:" + std::to_string(reminders.size()) + ",\n"; -// oneBundleReminders += " reminders:{\n"; -// for (auto vit = reminders.begin(); vit != reminders.end(); ++vit) { -// oneBundleReminders += " [\n"; -// std::string reminderInfo = (*vit)->Dump(); -// oneBundleReminders += " " + reminderInfo + "\n"; -// oneBundleReminders += " ],\n"; -// } -// oneBundleReminders += " },\n"; -// oneBundleReminders += "},\n"; -// allReminders += oneBundleReminders; -// } - -// return "ReminderDataManager{ totalCount:" + std::to_string(totalCount_) + ",\n" + -// "timerId:" + std::to_string(timerId_) + ",\n" + -// "activeReminderId:" + std::to_string(activeReminderId_) + ",\n" + -// allReminders + "}"; -// } - -// sptr ReminderDataManager::GetRecentReminderLocked() -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// sort(reminderVector_.begin(), reminderVector_.end(), cmp); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { -// if (!(*it)->IsExpired()) { -// time_t now; -// (void)time(&now); // unit is seconds. -// if (now < 0 -// || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) { -// it++; -// continue; -// } -// ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); -// return *it; -// } -// if (!(*it)->CanRemove()) { -// ANSR_LOGD("Reminder has been expired: %{public}s", (*it)->Dump().c_str()); -// it++; -// continue; -// } -// int32_t reminderId = (*it)->GetReminderId(); -// ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); -// it = reminderVector_.erase(it); -// totalCount_--; -// store_->Delete(reminderId); -// } -// return nullptr; -// } - -// void ReminderDataManager::HandleImmediatelyShow( -// std::vector> &showImmediately, bool isSysTimeChanged) -// { -// bool isAlerting = false; -// for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { -// if ((*it)->IsShowing()) { -// continue; -// } -// if (((*it)->GetRingDuration() > 0) && !isAlerting) { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// ShowReminder((*it), true, false, isSysTimeChanged, true); -// isAlerting = true; -// } else { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// ShowReminder((*it), false, false, isSysTimeChanged, false); -// } -// } -// } - -// void ReminderDataManager::HandleExtensionReminder(std::vector>& extensionReminders) -// { -// for (auto& reminder : extensionReminders) { -// ReminderDataManager::AsyncStartExtensionAbility(reminder, CONNECT_EXTENSION_MAX_RETRY_TIMES); -// } -// } - -// sptr ReminderDataManager::HandleRefreshReminder(const uint8_t &type, sptr &reminder) -// { -// reminder->SetReminderTimeInMilli(ReminderRequest::INVALID_LONG_LONG_VALUE); -// uint64_t triggerTimeBefore = reminder->GetTriggerTimeInMilli(); -// bool needShowImmediately = false; -// if (type == TIME_ZONE_CHANGE) { -// needShowImmediately = reminder->OnTimeZoneChange(); -// } -// if (type == DATE_TIME_CHANGE) { -// needShowImmediately = reminder->OnDateTimeChange(); -// } -// if (!needShowImmediately) { -// uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli(); -// if (triggerTimeBefore != triggerTimeAfter || reminder->GetReminderId() == alertingReminderId_) { -// CloseReminder(reminder, true); -// } -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -// return nullptr; -// } -// store_->UpdateOrInsert(reminder, reminder->GetNotificationBundleOption()); -// return reminder; -// } - -// void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) -// { -// // not add ReminderDataManager::MUTEX, as ShowActiveReminderExtendLocked has locked -// int32_t notificationId = reminder->GetNotificationId(); -// ANSR_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); -// int32_t curReminderId = reminder->GetReminderId(); -// sptr option1 = reminder->GetNotificationBundleOption(); -// if (option1 == nullptr) { -// ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", curReminderId); -// return; -// } - -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// int32_t tmpId = (*it)->GetReminderId(); -// if (tmpId == curReminderId) { -// continue; -// } -// if (!(*it)->IsShowing()) { -// continue; -// } -// sptr bundleOption = (*it)->GetNotificationBundleOption(); -// if (bundleOption == nullptr) { -// ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); -// continue; -// } -// if (notificationId == (*it)->GetNotificationId() && IsBelongToSameApp(bundleOption, option1)) { -// if ((*it)->IsAlerting()) { -// StopAlertingReminder(*it); -// } -// (*it)->OnSameNotificationIdCovered(); -// RemoveFromShowedReminders(*it); -// store_->UpdateOrInsert((*it), bundleOption); -// } -// } -// } - -// void ReminderDataManager::Init(bool isFromBootComplete) -// { -// ANSR_LOGD("ReminderDataManager Init, isFromBootComplete:%{public}d", isFromBootComplete); -// if (isFromBootComplete) { -// std::vector> immediatelyReminders; -// std::vector> extensionReminders; -// CheckReminderTime(immediatelyReminders, extensionReminders); -// HandleImmediatelyShow(immediatelyReminders, false); -// HandleExtensionReminder(extensionReminders); -// StartRecentReminder(); -// } -// if (IsReminderAgentReady()) { -// return; -// } -// // Register config observer for language change -// if (!RegisterConfigurationObserver()) { -// ANSR_LOGW("Register configuration observer failed."); -// return; -// } -// if (queue_ == nullptr) { -// queue_ = std::make_shared("ReminderDataManager"); -// if (queue_ == nullptr) { -// ANSR_LOGE("create ffrt queue failed!"); -// return; -// } -// } -// if (store_ == nullptr) { -// store_ = std::make_shared(); -// } -// if (store_->Init() != ReminderStore::STATE_OK) { -// ANSR_LOGW("Db init fail."); -// return; -// } -// InitServiceHandler(); -// LoadReminderFromDb(); -// InitUserId(); -// isReminderAgentReady_ = true; -// ANSR_LOGD("ReminderAgent is ready."); -// } - -// void ReminderDataManager::InitServiceHandler() -// { -// ANSR_LOGD("InitServiceHandler started"); -// if (serviceQueue_ != nullptr) { -// ANSR_LOGD("InitServiceHandler already init."); -// return; -// } -// serviceQueue_ = std::make_shared("ReminderService"); - -// ANSR_LOGD("InitServiceHandler suceeded."); -// } - -// void ReminderDataManager::CheckReminderTime(std::vector>& immediatelyReminders, -// std::vector>& extensionReminders) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto reminder : reminderVector_) { -// if (reminder->GetReminderType() != ReminderRequest::ReminderType::CALENDAR) { -// continue; -// } - -// if (reminder->IsPullUpService()) { -// extensionReminders.push_back(reminder); -// } - -// if (reminder->OnDateTimeChange()) { -// immediatelyReminders.push_back(reminder); -// } -// } -// } - -// void ReminderDataManager::InitUserId() -// { -// currentUserId_ = MAIN_USER_ID; -// OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(currentUserId_); -// } - -// bool ReminderDataManager::RegisterConfigurationObserver() -// { -// if (configChangeObserver_ != nullptr) { -// return true; -// } - -// auto appMgrClient = std::make_shared(); -// configChangeObserver_ = sptr( -// new (std::nothrow) ReminderConfigChangeObserver()); -// if (appMgrClient->RegisterConfigurationObserver(configChangeObserver_) != ERR_OK) { -// ANSR_LOGE("Register configuration observer failed."); -// return false; -// } -// return true; -// } - -// void ReminderDataManager::GetImmediatelyShowRemindersLocked(std::vector> &reminders) const -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto reminderSptr : reminderVector_) { -// if (!(reminderSptr->ShouldShowImmediately())) { -// break; -// } -// if (reminderSptr->GetReminderType() != ReminderRequest::ReminderType::TIMER) { -// reminderSptr->SetSnoozeTimesDynamic(0); -// } -// reminders.push_back(reminderSptr); -// } -// } - -// bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) const -// { -// if (reminder == nullptr) { -// return false; -// } -// auto option = reminder->GetNotificationBundleOption(); -// if (option == nullptr) { -// ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); -// return false; -// } -// bool isAllowed = false; -// ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); -// if (errCode != ERR_OK) { -// ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); -// return false; -// } -// return isAllowed; -// } - -// bool ReminderDataManager::IsReminderAgentReady() const -// { -// return isReminderAgentReady_; -// } - -// bool ReminderDataManager::CheckIsSameApp(const sptr &reminder, -// const sptr &other) const -// { -// std::string bundleName = reminder->GetCreatorBundleName(); -// int32_t uid = reminder->GetCreatorUid(); -// if (uid == -1) { -// uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, reminder->GetUserId()); -// } -// return bundleName == other->GetBundleName() && uid == other->GetUid(); -// } - -// bool ReminderDataManager::IsBelongToSameApp(const sptr &bundleOption, -// const sptr &other) const -// { -// int32_t uidSrc = bundleOption->GetUid(); -// int32_t uidTar = other->GetUid(); -// bool result = uidSrc == uidTar; -// int32_t userIdSrc = -1; -// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidSrc, userIdSrc); -// int32_t userIdTar = -1; -// OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uidTar, userIdTar); -// result = result && (userIdSrc == userIdTar); -// result = result && (bundleOption->GetBundleName() == other->GetBundleName()); -// return result; -// } - -// void ReminderDataManager::LoadReminderFromDb() -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// std::vector> existReminders = store_->GetAllValidReminders(); -// reminderVector_ = existReminders; -// ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// sptr bundleOption = new (std::nothrow) NotificationBundleOption(); -// if (bundleOption == nullptr) { -// ANS_LOGE("Failed to create bundle option due to low memory."); -// return; -// } -// bundleOption->SetBundleName((*it)->GetBundleName()); -// bundleOption->SetUid((*it)->GetUid()); -// (*it)->SetNotificationBundleOption(bundleOption); -// } -// totalCount_ = static_cast(reminderVector_.size()); -// ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; -// } - -// void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) -// { -// std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); -// PlaySoundAndVibration(reminder); -// } - -// std::string ReminderDataManager::GetCustomRingUri(const sptr &reminder) -// { -// if (reminder == nullptr) { -// return ""; -// } -// return reminder->GetCustomRingUri(); -// } - -// std::string ReminderDataManager::GetFullPath(const std::string& oriPath) -// { -// char buf[MAX_PATH_LEN] = {0}; -// char* path = GetOneCfgFile(oriPath.c_str(), buf, MAX_PATH_LEN); -// if (path == nullptr || *path == '\0') { -// ANSR_LOGE("GetOneCfgFile failed"); -// return ""; -// } -// std::string filePath = path; -// return filePath; -// } - -// void ReminderDataManager::PlaySoundAndVibration(const sptr &reminder) -// { -// if (reminder == nullptr) { -// ANSR_LOGE("Play sound and vibration failed as reminder is null."); -// return; -// } -// if (alertingReminderId_ != -1) { -// TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); -// } -// ANSR_LOGD("Play sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); -// #ifdef PLAYER_FRAMEWORK_ENABLE -// if (soundPlayer_ == nullptr) { -// soundPlayer_ = Media::PlayerFactory::CreatePlayer(); -// if (soundPlayer_ == nullptr) { -// ANSR_LOGE("Fail to creat player."); -// return; -// } -// } -// std::string customRingUri = reminder->GetCustomRingUri(); -// if (customRingUri.empty()) { -// // use default ring -// std::string defaultPath; -// if (access(DEFAULT_REMINDER_SOUND_1.c_str(), F_OK) == 0) { -// defaultPath = "file:/" + DEFAULT_REMINDER_SOUND_1; -// } else { -// defaultPath = "file:/" + GetFullPath(DEFAULT_REMINDER_SOUND_2); -// } -// Uri defaultSound(defaultPath); -// soundPlayer_->SetSource(defaultSound.GetSchemeSpecificPart()); -// ANSR_LOGI("Play default sound."); -// } else { -// Global::Resource::ResourceManager::RawFileDescriptor desc; -// if (GetCustomRingFileDesc(reminder, desc)) { -// soundPlayer_->SetSource(desc.fd, desc.offset, desc.length); -// } -// ANSR_LOGI("Play custom sound, reminderId:[%{public}d].", reminder->GetReminderId()); -// } -// soundPlayer_->SetLooping(true); -// soundPlayer_->PrepareAsync(); -// soundPlayer_->Play(); -// #endif -// SetAlertingReminder(reminder); -// } - -// std::string ReminderDataManager::GetSoundUri(const sptr &reminder) -// { -// Uri uri = DEFAULT_NOTIFICATION_SOUND; -// if (advancedNotificationService_ == nullptr) { -// ANSR_LOGE("Ans instance is null."); -// return uri.GetSchemeSpecificPart(); -// } -// sptr bundle = reminder->GetNotificationBundleOption(); -// std::vector> slots; -// ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); -// if (errCode != ERR_OK) { -// ANSR_LOGW("Get sound uri fail, use default sound instead."); -// return uri.GetSchemeSpecificPart(); -// } -// for (auto it = slots.begin(); it != slots.end(); ++it) { -// if ((*it)->GetType() == reminder->GetSlotType()) { -// uri = (*it)->GetSound(); -// break; -// } -// } -// return uri.GetSchemeSpecificPart(); -// } - -// void ReminderDataManager::StopSoundAndVibrationLocked(const sptr &reminder) -// { -// std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); -// StopSoundAndVibration(reminder); -// } - -// void ReminderDataManager::StopSoundAndVibration(const sptr &reminder) -// { -// if (reminder == nullptr) { -// ANSR_LOGE("Stop sound and vibration failed as reminder is null."); -// return; -// } -// if ((alertingReminderId_ == -1) || (reminder->GetReminderId() != alertingReminderId_)) { -// ANSR_LOGE("Stop sound and vibration failed as alertingReminder is illegal, alertingReminderId_=" \ -// "%{public}d, tarReminderId=%{public}d", alertingReminderId_.load(), reminder->GetReminderId()); -// return; -// } -// ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); -// #ifdef PLAYER_FRAMEWORK_ENABLE -// if (soundPlayer_ == nullptr) { -// ANSR_LOGW("Sound player is null"); -// } else { -// std::string customRingUri = reminder->GetCustomRingUri(); -// if (customRingUri.empty()) { -// ANSR_LOGI("Stop default sound."); -// } else { -// CloseCustomRingFileDesc(reminder->GetReminderId(), customRingUri); -// } -// soundPlayer_->Stop(); -// soundPlayer_->Release(); -// soundPlayer_ = nullptr; -// } -// #endif -// sptr nullReminder = nullptr; -// SetAlertingReminder(nullReminder); -// } - -// void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) -// { -// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); -// for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { -// if ((*it)->GetReminderId() == reminder->GetReminderId()) { -// ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); -// showedReminderVector_.erase(it); -// break; -// } -// } -// } - -// void ReminderDataManager::RefreshRemindersLocked(uint8_t type, -// std::vector>& immediatelyReminders, std::vector>& extensionReminders) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// if ((*it)->IsPullUpService()) { -// extensionReminders.push_back((*it)); -// } - -// sptr reminder = HandleRefreshReminder(type, (*it)); -// if (reminder != nullptr) { -// immediatelyReminders.push_back(reminder); -// } -// } -// } - -// void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { -// if (reminderId == (*it)->GetReminderId()) { -// ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); -// it = reminderVector_.erase(it); -// totalCount_--; -// store_->Delete(reminderId); -// break; -// } else { -// ++it; -// } -// } -// } - -// void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) -// { -// std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); -// StartTimer(reminderRequest, type); -// } - -// void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) -// { -// sptr timer = MiscServices::TimeServiceClient::GetInstance(); -// if (timer == nullptr) { -// ANS_LOGE("Failed to start timer due to get TimeServiceClient is null."); -// return; -// } -// time_t now; -// (void)time(&now); // unit is seconds. -// if (now < 0) { -// ANSR_LOGE("Get now time error"); -// return; -// } -// uint64_t triggerTime = 0; -// switch (type) { -// case TimerType::TRIGGER_TIMER: { -// if (timerId_ != 0) { -// ANSR_LOGE("Trigger timer has already started."); -// break; -// } -// triggerTime = HandleTriggerTimeInner(reminderRequest, type, timer); -// break; -// } -// case TimerType::ALERTING_TIMER: { -// if (timerIdAlerting_ != 0) { -// ANSR_LOGE("Alerting time out timer has already started."); -// break; -// } -// triggerTime = HandleAlertingTimeInner(reminderRequest, type, timer, now); -// break; -// } -// default: { -// ANSR_LOGE("TimerType not support"); -// break; -// } -// } -// if (triggerTime == 0) { -// ANSR_LOGW("Start timer fail"); -// } else { -// ANSR_LOGD("Timing info: now:(%{public}" PRIu64 "), tar:(%{public}" PRIu64 ")", -// ReminderRequest::GetDurationSinceEpochInMilli(now), triggerTime); -// } -// } - -// uint64_t ReminderDataManager::HandleTriggerTimeInner(const sptr &reminderRequest, TimerType type, -// const sptr &timer) -// { -// uint64_t triggerTime = 0; -// SetActiveReminder(reminderRequest); -// timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); -// triggerTime = reminderRequest->GetTriggerTimeInMilli(); -// timer->StartTimer(timerId_, triggerTime); -// ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}" PRIu64 "", timerId_); -// return triggerTime; -// } - -// uint64_t ReminderDataManager::HandleAlertingTimeInner(const sptr &reminderRequest, TimerType type, -// const sptr &timer, time_t now) -// { -// uint64_t triggerTime = 0; -// triggerTime = ReminderRequest::GetDurationSinceEpochInMilli(now) -// + static_cast(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS); -// timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type, reminderRequest)); -// timer->StartTimer(timerIdAlerting_, triggerTime); -// ANSR_LOGD("Start timing (alerting time out), timerId=%{public}" PRIu64 "", timerIdAlerting_.load()); -// return triggerTime; -// } - -// void ReminderDataManager::StopTimerLocked(TimerType type) -// { -// std::lock_guard lock(ReminderDataManager::TIMER_MUTEX); -// StopTimer(type); -// } - -// void ReminderDataManager::StopTimer(TimerType type) -// { -// sptr timer = MiscServices::TimeServiceClient::GetInstance(); -// if (timer == nullptr) { -// ANSR_LOGE("Failed to stop timer due to get TimeServiceClient is null."); -// return; -// } -// uint64_t timerId = 0; -// switch (type) { -// case TimerType::TRIGGER_TIMER: { -// timerId = timerId_; -// ANSR_LOGD("Stop timing (next triggerTime)"); -// break; -// } -// case TimerType::ALERTING_TIMER: { -// timerId = timerIdAlerting_; -// ANSR_LOGD("Stop timing (alerting time out)"); -// break; -// } -// default: { -// ANSR_LOGE("TimerType not support"); -// break; -// } -// } -// if (timerId == 0) { -// ANSR_LOGD("Timer is not running"); -// return; -// } -// ANSR_LOGD("Stop timer id=%{public}" PRIu64 "", timerId); -// timer->StopTimer(timerId); -// ResetStates(type); -// } - -// void ReminderDataManager::ResetStates(TimerType type) -// { -// uint64_t timerId = 0; -// switch (type) { -// case TimerType::TRIGGER_TIMER: { -// ANSR_LOGD("ResetStates(activeReminderId, timerId(next triggerTime))"); -// timerId = timerId_; -// timerId_ = 0; -// activeReminderId_ = -1; -// break; -// } -// case TimerType::ALERTING_TIMER: { -// ANSR_LOGD("ResetStates(alertingReminderId, timeId(alerting time out))"); -// timerId = timerIdAlerting_; -// timerIdAlerting_ = 0; -// alertingReminderId_ = -1; -// break; -// } -// default: { -// ANSR_LOGE("TimerType not support"); -// break; -// } -// } -// sptr timer = MiscServices::TimeServiceClient::GetInstance(); -// if (timer == nullptr) { -// ANSR_LOGE("Failed to destroy timer due to get TimeServiceClient is null."); -// return; -// } -// if (timerId != 0) { -// timer->DestroyTimer(timerId); -// } -// } - -// void ReminderDataManager::HandleCustomButtonClick(const OHOS::EventFwk::Want &want) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGE("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// if (!reminder->IsSystemApp()) { -// ANSR_LOGI("Custom button click, is not system app"); -// return; -// } -// CloseReminder(reminder, false); -// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CUSTOM); -// std::string buttonPkgName = want.GetStringParam("PkgName"); -// std::string buttonAbilityName = want.GetStringParam("AbilityName"); - -// AAFwk::Want abilityWant; -// abilityWant.SetElementName(buttonPkgName, buttonAbilityName); -// abilityWant.SetUri(reminder->GetCustomButtonUri()); -// auto client = AppExecFwk::AbilityManagerClient::GetInstance(); -// if (client == nullptr) { -// return; -// } -// uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); -// int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); -// if (result != 0) { -// ANSR_LOGE("Start ability failed, result = %{public}d", result); -// return; -// } -// } - -// void ReminderDataManager::ClickReminder(const OHOS::EventFwk::Want &want) -// { -// int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); -// ANSR_LOGI("click reminder[%{public}d] start", reminderId); -// sptr reminder = FindReminderRequestLocked(reminderId); -// if (reminder == nullptr) { -// ANSR_LOGW("Invalid reminder id: %{public}d", reminderId); -// return; -// } -// CloseReminder(reminder, true); -// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); -// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); -// StartRecentReminder(); - -// auto wantInfo = reminder->GetWantAgentInfo(); -// if (wantInfo == nullptr || (wantInfo->pkgName.empty() && wantInfo->abilityName.empty())) { -// ANSR_LOGW("want info is nullptr or no pkg name"); -// return; -// } -// AAFwk::Want abilityWant; -// AppExecFwk::ElementName element("", wantInfo->pkgName, wantInfo->abilityName); -// abilityWant.SetElement(element); -// abilityWant.SetUri(wantInfo->uri); -// abilityWant.SetParams(wantInfo->parameters); -// int32_t appIndex = BundleManagerHelper::GetInstance()->GetAppIndexByUid(reminder->GetUid()); -// abilityWant.SetParam("ohos.extra.param.key.appCloneIndex", appIndex); - -// auto client = AppExecFwk::AbilityManagerClient::GetInstance(); -// if (client == nullptr) { -// ANSR_LOGE("start ability failed, due to ability mgr client is nullptr."); -// return; -// } -// uint32_t specifyTokenId = static_cast(IPCSkeleton::GetSelfTokenID()); -// int32_t result = client->StartAbilityOnlyUIAbility(abilityWant, nullptr, specifyTokenId); -// if (result != 0) { -// ANSR_LOGE("Start ability failed, result = %{public}d", result); -// } -// } - -// std::shared_ptr ReminderDataManager::GetResourceMgr(const std::string& bundleName, -// const int32_t uid) -// { -// AppExecFwk::BundleInfo bundleInfo; -// if (!BundleManagerHelper::GetInstance()->GetBundleInfo(bundleName, -// AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES, uid, bundleInfo)) { -// ANSR_LOGE("GetBundleInfo[%{public}s][%{public}d] fail.", bundleName.c_str(), uid); -// return nullptr; -// } -// // obtains the resource manager -// std::shared_ptr resourceManager(Global::Resource::CreateResourceManager()); -// if (!resourceManager) { -// ANSR_LOGE("CreateResourceManager fail."); -// return nullptr; -// } -// // obtains the resource path. -// for (const auto &hapModuleInfo : bundleInfo.hapModuleInfos) { -// std::string moduleResPath = hapModuleInfo.hapPath.empty() ? hapModuleInfo.resourcePath : hapModuleInfo.hapPath; -// if (moduleResPath.empty()) { -// continue; -// } -// if (!resourceManager->AddResource(moduleResPath.c_str())) { -// ANSR_LOGW("AddResource fail."); -// } -// } -// // obtains the current system language. -// std::unique_ptr resConfig(Global::Resource::CreateResConfig()); -// UErrorCode status = U_ZERO_ERROR; -// icu::Locale locale = icu::Locale::forLanguageTag(Global::I18n::LocaleConfig::GetSystemLanguage(), status); -// resConfig->SetLocaleInfo(locale); -// resourceManager->UpdateResConfig(*resConfig); -// return resourceManager; -// } - -// void ReminderDataManager::UpdateReminderLanguageLocked(const int32_t uid, -// const std::vector>& reminders) -// { -// // obtains the bundle info by bundle name -// if (reminders.empty()) { -// return; -// } - -// std::string bundleName = reminders[0]->GetBundleName(); -// // obtains the resource manager -// auto resourceMgr = GetResourceMgr(bundleName, uid); -// if (resourceMgr == nullptr) { -// ANSR_LOGE("Get reminder request[%{public}d][%{public}s] resource manager failed.", -// uid, bundleName.c_str()); -// return; -// } -// // update action button title -// for (auto reminder : reminders) { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// reminder->OnLanguageChange(resourceMgr); -// } -// } - -// void ReminderDataManager::OnLanguageChanged() -// { -// ANSR_LOGI("System language config changed start."); -// std::unordered_map>> reminders; -// { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { -// reminders[(*it)->GetUid()].push_back((*it)); -// } -// } -// for (auto& each : reminders) { -// UpdateReminderLanguageLocked(each.first, each.second); -// } -// std::vector> showedReminder; -// { -// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); -// showedReminder = showedReminderVector_; -// } -// for (auto it = showedReminder.begin(); it != showedReminder.end(); ++it) { -// std::lock_guard lock(ReminderDataManager::MUTEX); -// ShowReminder((*it), false, false, false, false); -// } -// ANSR_LOGI("System language config changed end."); -// } - -// void ReminderDataManager::OnRemoveAppMgr() -// { -// std::lock_guard lock(appMgrMutex_); -// appMgrProxy_ = nullptr; -// } - -// bool ReminderDataManager::ConnectAppMgr() -// { -// if (appMgrProxy_ != nullptr) { -// return true; -// } - -// sptr systemAbilityManager = -// SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); -// if (systemAbilityManager == nullptr) { -// ANSR_LOGE("get SystemAbilityManager failed"); -// return false; -// } - -// sptr remoteObject = systemAbilityManager->GetSystemAbility(APP_MGR_SERVICE_ID); -// if (remoteObject == nullptr) { -// ANSR_LOGE("get app manager service failed"); -// return false; -// } - -// appMgrProxy_ = iface_cast(remoteObject); -// if (!appMgrProxy_ || !appMgrProxy_->AsObject()) { -// ANSR_LOGE("get app mgr proxy failed!"); -// return false; -// } -// return true; -// } - -// void ReminderDataManager::CheckNeedNotifyStatus(const sptr &reminder, -// const ReminderRequest::ActionButtonType buttonType) -// { -// const std::string bundleName = reminder->GetBundleName(); -// if (bundleName.empty()) { -// return; -// } -// bool isRunning = false; -// { -// std::lock_guard lock(appMgrMutex_); -// if (!ConnectAppMgr()) { -// return; -// } -// isRunning = appMgrProxy_->GetAppRunningStateByBundleName(bundleName); -// } -// if (!isRunning) { -// return; -// } - -// EventFwk::Want want; -// // common event not add COMMON_EVENT_REMINDER_STATUS_CHANGE, Temporary use of string -// want.SetAction("usual.event.REMINDER_STATUS_CHANGE"); -// EventFwk::CommonEventData eventData(want); - -// std::string data; -// data.append(std::to_string(static_cast(buttonType))).append(","); -// data.append(std::to_string(reminder->GetReminderId())); -// eventData.SetData(data); - -// EventFwk::CommonEventPublishInfo info; -// info.SetBundleName(bundleName); -// if (EventFwk::CommonEventManager::PublishCommonEvent(eventData, info)) { -// ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); -// } -// } -// } -// } diff --git a/services/ans/src/reminder_data_manager_inner.cpp b/services/ans/src/reminder_data_manager_inner.cpp deleted file mode 100644 index d73a6e36c..000000000 --- a/services/ans/src/reminder_data_manager_inner.cpp +++ /dev/null @@ -1,168 +0,0 @@ -// /* -// * Copyright (c) 2024-2024 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 "reminder_data_manager.h" - -// #include "ability_manager_client.h" -// #include "access_token_helper.h" -// #include "ans_log_wrapper.h" -// #include "ans_const_define.h" -// #include "common_event_support.h" -// #include "common_event_manager.h" -// #include "reminder_request_calendar.h" -// #include "in_process_call_wrapper.h" -// #ifdef DEVICE_STANDBY_ENABLE -// #include "standby_service_client.h" -// #include "allow_type.h" -// #endif -// #include "ipc_skeleton.h" -// #include "notification_slot.h" -// #include "os_account_manager.h" -// #include "reminder_event_manager.h" -// #include "time_service_client.h" -// #include "singleton.h" -// #include "locale_config.h" -// #include "bundle_manager_helper.h" -// #include "datashare_predicates_object.h" -// #include "datashare_value_object.h" -// #include "datashare_helper.h" -// #include "data_share_permission.h" -// #include "datashare_errno.h" -// #include "datashare_template.h" -// #include "system_ability_definition.h" -// #include "app_mgr_constants.h" -// #include "iservice_registry.h" -// #include "config_policy_utils.h" -// #include "hitrace_meter_adapter.h" -// #ifdef HAS_HISYSEVENT_PART -// #include "hisysevent.h" -// #endif - -// namespace OHOS { -// namespace Notification { -// namespace { -// constexpr int32_t ALL_SA_READY_FLAG = 2; // bundle service and ability service ready. -// } - -// bool ReminderDataManager::IsSystemReady() -// { -// return saReadyFlag_ >= ALL_SA_READY_FLAG; -// } - -// bool ReminderDataManager::IsActionButtonDataShareValid(const sptr& reminder, -// const uint32_t callerTokenId) -// { -// auto actionButtonMap = reminder->GetActionButtons(); -// for (auto it = actionButtonMap.begin(); it != actionButtonMap.end(); ++it) { -// ReminderRequest::ActionButtonInfo& buttonInfo = it->second; -// if (buttonInfo.dataShareUpdate->uri.empty()) { -// continue; -// } -// Uri uri(buttonInfo.dataShareUpdate->uri); -// auto ret = DataShare::DataSharePermission::VerifyPermission(callerTokenId, uri, false); -// if (ret != DataShare::E_OK) { -// ANSR_LOGE("publish failed, DataSharePermission::VerifyPermission return error[%{public}d],", -// static_cast(ret)); -// return false; -// } -// } -// return true; -// } - -// void ReminderDataManager::HandleAutoDeleteReminder(const int32_t notificationId, const int32_t uid, -// const int64_t autoDeletedTime) -// { -// ANSR_LOGI("auto delete reminder start"); -// std::vector> showedReminder; -// { -// std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); -// showedReminder = showedReminderVector_; -// } -// for (auto reminder : showedReminder) { -// if (reminder == nullptr) { -// continue; -// } - -// if (reminder->GetUid() != uid || notificationId != reminder->GetNotificationId() || -// reminder->GetAutoDeletedTime() != autoDeletedTime) { -// continue; -// } -// CloseReminder(reminder, true); -// UpdateAppDatabase(reminder, ReminderRequest::ActionButtonType::CLOSE); -// CheckNeedNotifyStatus(reminder, ReminderRequest::ActionButtonType::CLOSE); -// } -// StartRecentReminder(); -// } - -// void ReminderDataManager::OnBundleMgrServiceStart() -// { -// saReadyFlag_.fetch_add(1); -// } - -// void ReminderDataManager::OnAbilityMgrServiceStart() -// { -// saReadyFlag_.fetch_add(1); -// } - -// bool ReminderDataManager::GetCustomRingFileDesc(const sptr& reminder, -// Global::Resource::ResourceManager::RawFileDescriptor& desc) -// { -// // obtains the resource manager -// std::lock_guard locker(resourceMutex_); -// soundResource_ = GetResourceMgr(reminder->GetBundleName(), reminder->GetUid()); -// if (soundResource_ == nullptr) { -// ANSR_LOGE("GetResourceMgr fail."); -// return false; -// } -// auto result = soundResource_->GetRawFileDescriptor(reminder->GetCustomRingUri(), desc); -// if (result != Global::Resource::SUCCESS) { -// ANSR_LOGE("GetRawFileDescriptor fail[%{public}d].", static_cast(result)); -// return false; -// } -// return true; -// } - -// void ReminderDataManager::CloseCustomRingFileDesc(const int32_t reminderId, const std::string& customRingUri) -// { -// std::lock_guard locker(resourceMutex_); -// if (soundResource_ == nullptr) { -// ANSR_LOGW("ResourceManager is nullptr."); -// return; -// } -// auto result = soundResource_->CloseRawFileDescriptor(customRingUri); -// if (result != Global::Resource::SUCCESS) { -// ANSR_LOGW("CloseRawFileDescriptor fail[%{public}d]", static_cast(result)); -// } -// ANSR_LOGI("Stop custom sound, reminderId:[%{public}d].", reminderId); -// soundResource_ = nullptr; -// } - -// void ReminderDataManager::ReportSysEvent(const sptr& reminder) -// { -// #ifdef HAS_HISYSEVENT_PART -// std::string event = "ALARM_TRIGGER"; -// std::string bundleName = reminder->GetBundleName(); -// int32_t uid = reminder->GetUid(); -// int32_t type = static_cast(reminder->GetReminderType()); -// int32_t repeat = static_cast(reminder->IsRepeat()); -// uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); -// int32_t ringTime = static_cast(reminder->GetRingDuration()); -// HiSysEventWrite(HiviewDFX::HiSysEvent::Domain::NOTIFICATION, event, HiviewDFX::HiSysEvent::EventType::STATISTIC, -// "UID", uid, "NAME", bundleName, "TYPE", type, "REPEAT", repeat, "TRIGGER_TIME", triggerTime, -// "RING_TIME", ringTime); -// #endif -// } -// } -// } diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp deleted file mode 100644 index b56f8d9e2..000000000 --- a/services/ans/src/reminder_event_manager.cpp +++ /dev/null @@ -1,361 +0,0 @@ -// /* -// * Copyright (c) 2021-2022 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 "reminder_event_manager.h" - -// #include "ans_log_wrapper.h" -// #include "bundle_constants.h" -// #include "bundle_mgr_interface.h" -// #include "common_event_manager.h" -// #include "common_event_support.h" -// #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 "notification_helper.h" -// #include "string_ex.h" - -// using namespace OHOS::EventFwk; -// namespace OHOS { -// namespace Notification { -// static const std::string NOTIFICATION_LABEL = "REMINDER_AGENT"; -// std::shared_ptr ReminderEventManager::subscriber_ -// = nullptr; - -// ReminderEventManager::ReminderEventManager(std::shared_ptr &reminderDataManager) -// { -// init(reminderDataManager); -// } - -// void ReminderEventManager::init(std::shared_ptr &reminderDataManager) const -// { -// MatchingSkills customMatchingSkills; -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT); -// customMatchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLICK_ALERT); -// CommonEventSubscribeInfo customSubscriberInfo(customMatchingSkills); -// customSubscriberInfo.SetPermission("ohos.permission.GRANT_SENSITIVE_PERMISSIONS"); -// customSubscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); -// auto customSubscriber = std::make_shared(customSubscriberInfo, reminderDataManager); - -// MatchingSkills matchingSkills; -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_TIME_CHANGED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_SWITCHED); -// matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED); -// CommonEventSubscribeInfo subscriberInfo(matchingSkills); -// subscriberInfo.SetThreadMode(EventFwk::CommonEventSubscribeInfo::COMMON); -// auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); - -// std::string identity = IPCSkeleton::ResetCallingIdentity(); -// if (CommonEventManager::SubscribeCommonEvent(subscriber) && -// CommonEventManager::SubscribeCommonEvent(customSubscriber)) { -// ANSR_LOGD("SubscribeCommonEvent ok"); -// } else { -// ANSR_LOGD("SubscribeCommonEvent fail"); -// } -// IPCSkeleton::SetCallingIdentity(identity); - -// subscriber_ = std::make_shared(reminderDataManager); -// if (NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { -// ANSR_LOGD("SubscribeNotification failed"); -// } - -// SubscribeSystemAbility(reminderDataManager); -// } - -// void ReminderEventManager::SubscribeSystemAbility(std::shared_ptr &reminderDataManager) const -// { -// sptr statusChangeListener -// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); -// if (statusChangeListener == nullptr) { -// ANSR_LOGE("Failed to create statusChangeListener due to no memory."); -// return; -// } -// // app mgr -// sptr appMgrStatusChangeListener -// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); -// if (appMgrStatusChangeListener == nullptr) { -// ANSR_LOGE("Failed to create appMgrStatusChangeListener due to no memory."); -// return; -// } -// // ability mgr -// sptr abilityMgrStatusListener -// = new (std::nothrow) SystemAbilityStatusChangeListener(reminderDataManager); -// if (abilityMgrStatusListener == nullptr) { -// ANSR_LOGE("Failed to create abilityMgrStatusListener due to no memory."); -// return; -// } - -// sptr samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); -// if (samgrProxy == nullptr) { -// ANSR_LOGD("samgrProxy is null"); -// return; -// } -// int32_t ret = samgrProxy->SubscribeSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID, statusChangeListener); -// if (ret != ERR_OK) { -// ANSR_LOGE("subscribe system ability id: %{public}d failed", BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); -// } -// ret = samgrProxy->SubscribeSystemAbility(APP_MGR_SERVICE_ID, appMgrStatusChangeListener); -// if (ret != ERR_OK) { -// ANSR_LOGE("subscribe system ability id: %{public}d failed", APP_MGR_SERVICE_ID); -// } -// ret = samgrProxy->SubscribeSystemAbility(ABILITY_MGR_SERVICE_ID, abilityMgrStatusListener); -// if (ret != ERR_OK) { -// ANSR_LOGE("subscribe system ability id: %{public}d failed", ABILITY_MGR_SERVICE_ID); -// } -// } - -// ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( -// const CommonEventSubscribeInfo &subscriberInfo, -// std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) -// { -// reminderDataManager_ = reminderDataManager; -// } - -// ReminderEventManager::ReminderEventCustomSubscriber::ReminderEventCustomSubscriber( -// const CommonEventSubscribeInfo &subscriberInfo, -// std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) -// { -// reminderDataManager_ = reminderDataManager; -// } - -// void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) -// { -// Want want = data.GetWant(); -// std::string action = want.GetAction(); -// ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); -// if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { -// reminderDataManager_->ShowActiveReminder(want); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT) { -// reminderDataManager_->TerminateAlerting(want); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_CLOSE_ALERT) { -// reminderDataManager_->CloseReminder(want, true); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT) { -// reminderDataManager_->SnoozeReminder(want); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT) { -// reminderDataManager_->HandleCustomButtonClick(want); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { -// reminderDataManager_->CloseReminder(want, false); -// return; -// } -// if (action == ReminderRequest::REMINDER_EVENT_CLICK_ALERT) { -// reminderDataManager_->ClickReminder(want); -// return; -// } -// } - -// void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) -// { -// Want want = data.GetWant(); -// std::string action = want.GetAction(); -// ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); -// if (action == CommonEventSupport::COMMON_EVENT_BOOT_COMPLETED) { -// reminderDataManager_->Init(true); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { -// HandlePackageRemove(want); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { -// HandlePackageRemove(want); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { -// HandleProcessDied(want); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { -// reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::TIME_ZONE_CHANGE); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_TIME_CHANGED) { -// reminderDataManager_->RefreshRemindersDueToSysTimeChange(ReminderDataManager::DATE_TIME_CHANGE); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_USER_SWITCHED) { -// reminderDataManager_->OnUserSwitch(data.GetCode()); -// return; -// } -// if (action == CommonEventSupport::COMMON_EVENT_USER_REMOVED) { -// reminderDataManager_->OnUserRemove(data.GetCode()); -// return; -// } -// } - -// void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const -// { -// OHOS::AppExecFwk::ElementName ele = want.GetElement(); -// std::string bundleName = ele.GetBundleName(); -// int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); -// int32_t uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); -// reminderDataManager_->CancelAllReminders(bundleName, userId, uid); -// } - -// void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const -// { -// sptr bundleOption = GetBundleOption(want); -// if (bundleOption == nullptr) { -// ANSR_LOGE("Get bundle option error."); -// return; -// } -// reminderDataManager_->OnProcessDiedLocked(bundleOption); -// } - -// sptr ReminderEventManager::ReminderEventSubscriber::GetBundleOption( -// const OHOS::EventFwk::Want &want) const -// { -// OHOS::AppExecFwk::ElementName ele = want.GetElement(); -// std::string bundleName = ele.GetBundleName(); -// int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); -// int32_t uid = BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName, userId); -// ANSR_LOGD("bundleName=%{public}s, userId=%{private}d, uid=%{public}d", bundleName.c_str(), userId, uid); -// sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); -// if (bundleOption == nullptr) { -// ANSR_LOGE("new NotificationBundleOption fail due to no memory."); -// } -// return bundleOption; -// } - -// ReminderEventManager::SystemAbilityStatusChangeListener::SystemAbilityStatusChangeListener( -// std::shared_ptr &reminderDataManager) -// { -// reminderDataManager_ = reminderDataManager; -// } - -// void ReminderEventManager::SystemAbilityStatusChangeListener::OnAddSystemAbility( -// int32_t systemAbilityId, const std::string& deviceId) -// { -// ANSR_LOGD("OnAddSystemAbilityInner"); -// switch (systemAbilityId) { -// case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: -// ANSR_LOGD("OnAddSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); -// reminderDataManager_->OnBundleMgrServiceStart(); -// break; -// case APP_MGR_SERVICE_ID: -// ANSR_LOGD("OnAddSystemAbilityInner: APP_MGR_SERVICE"); -// break; -// case ABILITY_MGR_SERVICE_ID: -// ANSR_LOGD("OnAddSystemAbilityInner ABILITY_MGR_SERVICE_ID"); -// reminderDataManager_->OnAbilityMgrServiceStart(); -// break; -// default: -// break; -// } -// } - -// void ReminderEventManager::SystemAbilityStatusChangeListener::OnRemoveSystemAbility( -// int32_t systemAbilityId, const std::string& deviceId) -// { -// ANSR_LOGD("OnRemoveSystemAbilityInner"); -// switch (systemAbilityId) { -// case BUNDLE_MGR_SERVICE_SYS_ABILITY_ID: -// ANSR_LOGD("OnRemoveSystemAbilityInner: BUNDLE_MGR_SERVICE_SYS_ABILITY"); -// break; -// case APP_MGR_SERVICE_ID: -// ANSR_LOGD("OnRemoveSystemAbilityInner: APP_MGR_SERVICE"); -// reminderDataManager_->OnRemoveAppMgr(); -// break; -// case ABILITY_MGR_SERVICE_ID: -// ANSR_LOGD("OnRemoveSystemAbilityInner ABILITY_MGR_SERVICE_ID"); -// break; -// default: -// break; -// } -// } - -// ReminderEventManager::ReminderNotificationSubscriber::ReminderNotificationSubscriber( -// std::shared_ptr &reminderDataManager) -// { -// reminderDataManager_ = reminderDataManager; -// } - -// ReminderEventManager::ReminderNotificationSubscriber::~ReminderNotificationSubscriber() {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnConnected() {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnDisconnected() {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnCanceled( -// const std::shared_ptr ¬ification, -// const std::shared_ptr &sortingMap, int deleteReason) -// { -// // Note: Don't modify param notification -// if (deleteReason != NotificationConstant::TRIGGER_AUTO_DELETE_REASON_DELETE) { -// return; -// } -// if (notification == nullptr) { -// return; -// } -// NotificationRequest request = notification->GetNotificationRequest(); -// std::string label = request.GetLabel(); -// int64_t autoDeletedTime = request.GetAutoDeletedTime(); -// if (autoDeletedTime <= 0 || label != NOTIFICATION_LABEL) { -// return; -// } - -// if (reminderDataManager_ == nullptr) { -// return; -// } -// int32_t notificationId = request.GetNotificationId(); -// int32_t uid = request.GetOwnerUid() == 0 ? request.GetCreatorUid() : request.GetOwnerUid(); -// reminderDataManager_->HandleAutoDeleteReminder(notificationId, uid, autoDeletedTime); -// } - -// void ReminderEventManager::ReminderNotificationSubscriber::OnConsumed(const std::shared_ptr ¬ification, -// const std::shared_ptr &sortingMap) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnUpdate( -// const std::shared_ptr &sortingMap) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnDied() {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnDoNotDisturbDateChange( -// const std::shared_ptr &date) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnEnabledNotificationChanged( -// const std::shared_ptr &callbackData) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeChanged( -// const std::shared_ptr &badgeData) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnBadgeEnabledChanged( -// const sptr &callbackData) {} - -// void ReminderEventManager::ReminderNotificationSubscriber::OnBatchCanceled( -// const std::vector> &requestList, -// const std::shared_ptr &sortingMap, int32_t deleteReason) {} -// } // namespace OHOS -// } // namespace Notification diff --git a/services/ans/src/reminder_store.cpp b/services/ans/src/reminder_store.cpp deleted file mode 100644 index 6429468fe..000000000 --- a/services/ans/src/reminder_store.cpp +++ /dev/null @@ -1,817 +0,0 @@ -// /* -// * Copyright (c) 2022 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 "reminder_store.h" - -// #include -// #include -// #include -// #include - -// #include "fa_ability_context.h" -// #include "ans_log_wrapper.h" -// #include "reminder_table.h" -// #include "reminder_table_old.h" -// #include "reminder_request_alarm.h" -// #include "reminder_request_timer.h" -// #include "reminder_request_calendar.h" -// #include "reminder_store_strategy.h" - -// namespace OHOS { -// namespace Notification { -// namespace { -// const int32_t REMINDER_RDB_VERSION_V1 = 1; -// const int32_t REMINDER_RDB_VERSION_V2 = 2; -// const int32_t REMINDER_RDB_VERSION_V3 = 3; -// const int32_t REMINDER_RDB_VERSION_V4 = 4; -// const int32_t REMINDER_RDB_VERSION_V5 = 5; -// const int32_t REMINDER_RDB_VERSION_V6 = 6; -// const int32_t REMINDER_RDB_VERSION = 7; -// } - -// const int32_t ReminderStore::STATE_OK = 0; -// const int32_t ReminderStore::STATE_FAIL = -1; -// const std::string ReminderStore::REMINDER_DB_DIR = "/data/service/el1/public/notification/"; -// const std::string ReminderStore::REMINDER_DB_NAME = "notification.db"; - -// int32_t ReminderStore::ReminderStoreDataCallBack::OnCreate(NativeRdb::RdbStore& store) -// { -// ANSR_LOGI("Create table"); -// return CreateTable(store); -// } - -// int32_t ReminderStore::ReminderStoreDataCallBack::OnUpgrade( -// NativeRdb::RdbStore& store, int32_t oldVersion, int32_t newVersion) -// { -// ANSR_LOGI("OnUpgrade oldVersion is %{public}d, newVersion is %{public}d", oldVersion, newVersion); -// if (oldVersion < newVersion && newVersion == REMINDER_RDB_VERSION) { -// switch (oldVersion) { -// case REMINDER_RDB_VERSION_V1: -// AddRdbColum(store, ReminderTable::TABLE_NAME, "groupId", "TEXT", "''"); -// [[fallthrough]]; -// case REMINDER_RDB_VERSION_V2: -// AddRdbColum(store, ReminderTable::TABLE_NAME, "custom_ring_uri", "TEXT", "''"); -// AddRdbColum(store, ReminderTable::TABLE_NAME, "snooze_slot_id", "INT", "3"); -// [[fallthrough]]; -// case REMINDER_RDB_VERSION_V3: -// AddRdbColum(store, ReminderTable::TABLE_NAME, "creator_bundle_name", "TEXT", "''"); -// [[fallthrough]]; -// case REMINDER_RDB_VERSION_V4: -// CreateTable(store); -// CopyData(store); -// [[fallthrough]]; -// case REMINDER_RDB_VERSION_V5: -// AddRdbColum(store, ReminderBaseTable::TABLE_NAME, ReminderBaseTable::CREATOR_UID, "INT", "-1"); -// [[fallthrough]]; -// case REMINDER_RDB_VERSION_V6: -// AddRdbColum(store, ReminderCalendarTable::TABLE_NAME, -// ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, "BIGINT", "0"); -// [[fallthrough]]; -// default: -// break; -// } -// } -// store.SetVersion(newVersion); -// return NativeRdb::E_OK; -// } - -// int32_t ReminderStore::ReminderStoreDataCallBack::OnDowngrade( -// NativeRdb::RdbStore& store, int32_t currentVersion, int32_t targetVersion) -// { -// ANSR_LOGI("OnDowngrade currentVersion is %{public}d, targetVersion is %{public}d", currentVersion, targetVersion); -// if (currentVersion > targetVersion && targetVersion <= REMINDER_RDB_VERSION_V4) { -// std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTable::TABLE_NAME + " (" -// + ReminderTable::ADD_COLUMNS + ")"; -// int32_t ret = store.ExecuteSql(createSql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Create reminder table failed:%{public}d", ret); -// } -// return ret; -// } -// store.SetVersion(targetVersion); -// return NativeRdb::E_OK; -// } - -// int32_t ReminderStore::ReminderStoreDataCallBack::CreateTable(NativeRdb::RdbStore& store) -// { -// std::string createSql = "CREATE TABLE IF NOT EXISTS " + ReminderBaseTable::TABLE_NAME + " (" -// + ReminderBaseTable::ADD_COLUMNS + ")"; -// int32_t ret = store.ExecuteSql(createSql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Create reminder_base table failed:%{public}d", ret); -// return ret; -// } - -// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderAlarmTable::TABLE_NAME + " (" -// + ReminderAlarmTable::ADD_COLUMNS + ")"; -// ret = store.ExecuteSql(createSql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Create reminder_alarm table failed:%{public}d", ret); -// return ret; -// } - -// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderCalendarTable::TABLE_NAME + " (" -// + ReminderCalendarTable::ADD_COLUMNS + ")"; -// ret = store.ExecuteSql(createSql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Create reminder_calendar table failed:%{public}d", ret); -// return ret; -// } - -// createSql = "CREATE TABLE IF NOT EXISTS " + ReminderTimerTable::TABLE_NAME + " (" -// + ReminderTimerTable::ADD_COLUMNS + ")"; -// ret = store.ExecuteSql(createSql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Create reminder_timer table failed:%{public}d", ret); -// return ret; -// } -// return ret; -// } - -// int32_t ReminderStore::ReminderStoreDataCallBack::CopyData(NativeRdb::RdbStore& store) -// { -// // select old data -// auto reminders = GetOldReminders(store); -// // insert new data -// if (!reminders.empty()) { -// InsertNewReminders(store, reminders); -// } -// // delete old table -// std::string sql = "DELETE FROM " + ReminderTable::TABLE_NAME; -// store.ExecuteSql(sql); -// return NativeRdb::E_OK; -// } - -// std::vector> ReminderStore::ReminderStoreDataCallBack::GetOldReminders(NativeRdb::RdbStore& store) -// { -// std::string sql = "SELECT " + ReminderTable::SELECT_COLUMNS + " FROM " -// + ReminderTable::TABLE_NAME; -// std::vector> reminders; -// std::vector whereArgs; -// auto queryResult = store.QuerySql(sql, whereArgs); -// if (queryResult == nullptr) { -// return reminders; -// } - -// bool isLastRow = false; -// queryResult->IsAtLastRow(isLastRow); -// while (!isLastRow) { -// queryResult->GoToNextRow(); -// int32_t reminderId; -// int32_t reminderType; -// GetInt32Val(queryResult, ReminderTable::REMINDER_ID, reminderId); -// GetInt32Val(queryResult, ReminderTable::REMINDER_TYPE, reminderType); - -// sptr reminderReq = nullptr; -// switch (reminderType) { -// case (static_cast(ReminderRequest::ReminderType::TIMER)): { -// reminderReq = new (std::nothrow) ReminderRequestTimer(reminderId); -// ReminderTimerStrategy::RecoverFromOldVersion(reminderReq, queryResult); -// break; -// } -// case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { -// reminderReq = new (std::nothrow) ReminderRequestCalendar(reminderId); -// ReminderCalendarStrategy::RecoverFromOldVersion(reminderReq, queryResult); -// break; -// } -// case (static_cast(ReminderRequest::ReminderType::ALARM)): { -// reminderReq = new (std::nothrow) ReminderRequestAlarm(reminderId); -// ReminderAlarmStrategy::RecoverFromOldVersion(reminderReq, queryResult); -// break; -// } -// default: { -// break; -// } -// } -// if (reminderReq != nullptr) { -// reminders.push_back(reminderReq); -// } -// queryResult->IsAtLastRow(isLastRow); -// } -// return reminders; -// } - -// void ReminderStore::ReminderStoreDataCallBack::InsertNewReminders(NativeRdb::RdbStore& store, -// const std::vector>& reminders) -// { -// for (auto reminder : reminders) { -// int64_t rowId = STATE_FAIL; -// sptr bundleOption = new (std::nothrow) NotificationBundleOption(); -// if (bundleOption == nullptr) { -// continue; -// } -// bundleOption->SetBundleName(reminder->GetBundleName()); -// NativeRdb::ValuesBucket baseValues; -// ReminderStrategy::AppendValuesBucket(reminder, baseValues, true); - -// store.BeginTransaction(); -// // insert reminder_base -// int32_t ret = store.Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// store.RollBack(); -// continue; -// } - -// // insert reminder_alarm or reminder_calendar -// NativeRdb::ValuesBucket values; -// rowId = STATE_FAIL; -// switch (reminder->GetReminderType()) { -// case ReminderRequest::ReminderType::CALENDAR: -// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); -// ret = store.Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); -// break; -// case ReminderRequest::ReminderType::ALARM: -// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); -// ret = store.Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); -// break; -// case ReminderRequest::ReminderType::TIMER: -// ReminderTimerStrategy::AppendValuesBucket(reminder, values); -// ret = store.Insert(rowId, ReminderTimerTable::TABLE_NAME, values); -// break; -// default: -// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); -// ret = STATE_FAIL; -// break; -// } -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// store.RollBack(); -// continue; -// } -// store.Commit(); -// ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); -// } -// } - -// void ReminderStore::ReminderStoreDataCallBack::AddRdbColum(NativeRdb::RdbStore& store, const std::string& tableName, -// const std::string& columnName, const std::string& columnType, const std::string& defValue) -// { -// std::string sqlStr = ""; -// sqlStr = "ALTER TABLE " + tableName + " ADD " + columnName + " " + columnType + " DEFAULT " + defValue + ";"; -// ANSR_LOGD("AddRdbColum sqlStr = %{public}s", sqlStr.c_str()); -// int errorCode = store.ExecuteSql(sqlStr); -// if (errorCode != NativeRdb::E_OK) { -// ANSR_LOGE("AddRdbColum error,errorCode is = %{public}d", errorCode); -// } -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Init() -// { -// ANSR_LOGD("Reminder store init."); -// if (access(REMINDER_DB_DIR.c_str(), F_OK) != 0) { -// int createDir = mkdir(REMINDER_DB_DIR.c_str(), S_IRWXU); -// if (createDir != 0) { -// ANSR_LOGE("Failed to create directory %{private}s", REMINDER_DB_DIR.c_str()); -// return STATE_FAIL; -// } -// } - -// ReminderTable::InitDbColumns(); -// ReminderBaseTable::InitDbColumns(); -// ReminderTimerTable::InitDbColumns(); -// ReminderAlarmTable::InitDbColumns(); -// ReminderCalendarTable::InitDbColumns(); - -// std::string dbConfig = REMINDER_DB_DIR + REMINDER_DB_NAME; -// NativeRdb::RdbStoreConfig config(dbConfig); -// config.SetSecurityLevel(NativeRdb::SecurityLevel::S1); - -// ReminderStoreDataCallBack rdbDataCallBack; -// int32_t errCode = STATE_FAIL; -// rdbStore_ = NativeRdb::RdbHelper::GetRdbStore(config, REMINDER_RDB_VERSION, rdbDataCallBack, errCode); -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("ReminderStore init fail, errCode %{public}d.", errCode); -// return STATE_FAIL; -// } -// return InitData(); -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const int32_t reminderId) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// std::string condition = ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); -// rdbStore_->BeginTransaction(); -// int32_t delRows = STATE_FAIL; -// std::vector whereArgs; -// int32_t ret = rdbStore_->Delete(delRows, ReminderBaseTable::TABLE_NAME, condition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", -// ReminderBaseTable::TABLE_NAME.c_str(), reminderId); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// delRows = STATE_FAIL; -// ret = rdbStore_->Delete(delRows, ReminderAlarmTable::TABLE_NAME, condition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", -// ReminderAlarmTable::TABLE_NAME.c_str(), reminderId); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// delRows = STATE_FAIL; -// ret = rdbStore_->Delete(delRows, ReminderCalendarTable::TABLE_NAME, condition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", -// ReminderCalendarTable::TABLE_NAME.c_str(), reminderId); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// delRows = STATE_FAIL; -// ret = rdbStore_->Delete(delRows, ReminderTimerTable::TABLE_NAME, condition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed, reminderId = %{public}d", -// ReminderTimerTable::TABLE_NAME.c_str(), reminderId); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// rdbStore_->Commit(); -// return STATE_OK; -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& pkg, const int32_t userId, -// const int32_t uid) -// { -// std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME -// + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg -// + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - -// std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " -// + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - -// if (uid != -1) { -// assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID -// + " = " + std::to_string(uid); -// baseCondtion += " AND " + ReminderBaseTable::UID + " = " + std::to_string(uid); -// } -// assoConditon += ")"; -// return Delete(baseCondtion, assoConditon); -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteUser(const int32_t userId) -// { -// std::string assoConditon = "(SELECT " + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderBaseTable::TABLE_NAME -// + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " -// + std::to_string(userId) + ")"; - -// std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); -// return Delete(baseCondtion, assoConditon); -// } - -// int32_t ReminderStore::UpdateOrInsert( -// const sptr& reminder, const sptr& bundleOption) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// if (bundleOption == nullptr) { -// ANSR_LOGE("BundleOption is null."); -// return STATE_FAIL; -// } -// if (IsReminderExist(reminder)) { -// return Update(reminder, bundleOption); -// } else { -// return Insert(reminder, bundleOption); -// } -// } - -// int32_t ReminderStore::GetMaxId() -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// std::string queryCondition = "SELECT " + ReminderBaseTable::REMINDER_ID -// + " FROM " + ReminderBaseTable::TABLE_NAME + " ORDER BY " -// + ReminderBaseTable::REMINDER_ID + " DESC"; -// auto queryResultSet = Query(queryCondition); -// if (queryResultSet == nullptr) { -// ANSR_LOGE("QueryResultSet is null."); -// return STATE_FAIL; -// } -// int32_t resultNum = 0; -// queryResultSet->GetRowCount(resultNum); -// if (resultNum == 0) { -// ANSR_LOGI("QueryResultSet is zero."); -// return STATE_FAIL; -// } -// queryResultSet->GoToNextRow(); -// int32_t maxId = STATE_FAIL; -// int32_t result = queryResultSet->GetInt(0, maxId); -// if (result != NativeRdb::E_OK) { -// ANSR_LOGE("Query operation failed, result %{public}d.", result); -// } -// ANSR_LOGD("MaxId: %{public}d.", maxId); -// return maxId; -// } - -// __attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() -// { -// std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " -// + ReminderBaseTable::TABLE_NAME + " WHERE " -// + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " -// + ReminderBaseTable::TRIGGER_TIME + " ASC"; -// ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); -// return GetReminders(sql); -// } - -// void ReminderStore::GetUInt8Val(const std::shared_ptr& resultSet, -// const std::string& name, uint8_t& value) -// { -// int32_t val; -// GetInt32Val(resultSet, name, val); -// value = static_cast(val); -// } - -// void ReminderStore::GetUInt16Val(const std::shared_ptr& resultSet, -// const std::string& name, uint16_t& value) -// { -// int32_t val; -// GetInt32Val(resultSet, name, val); -// value = static_cast(val); -// } - -// void ReminderStore::GetInt32Val(const std::shared_ptr& resultSet, -// const std::string& name, int32_t& value) -// { -// value = 0; -// int32_t columnIndex = -1; -// resultSet->GetColumnIndex(name, columnIndex); -// if (columnIndex == -1) { -// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); -// return; -// } -// resultSet->GetInt(columnIndex, value); -// } - -// void ReminderStore::GetInt64Val(const std::shared_ptr& resultSet, -// const std::string& name, int64_t& value) -// { -// value = 0; -// int32_t columnIndex = -1; -// resultSet->GetColumnIndex(name, columnIndex); -// if (columnIndex == -1) { -// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); -// return; -// } -// resultSet->GetLong(columnIndex, value); -// } - -// void ReminderStore::GetUInt64Val(const std::shared_ptr& resultSet, -// const std::string& name, uint64_t& value) -// { -// int64_t val; -// GetInt64Val(resultSet, name, val); -// value = static_cast(val); -// } - -// void ReminderStore::GetStringVal(const std::shared_ptr& resultSet, -// const std::string& name, std::string& value) -// { -// int32_t columnIndex = -1; -// resultSet->GetColumnIndex(name, columnIndex); -// if (columnIndex == -1) { -// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); -// return; -// } -// resultSet->GetString(columnIndex, value); -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::InitData() -// { -// ANSR_LOGD("Reminder data init."); -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// // delete all the reminders which IS_EXPIRED is true. -// std::string deleteCondition = ReminderBaseTable::IS_EXPIRED + " is true"; -// DeleteBase(deleteCondition); - -// // set all the value of STATE to ReminderRequest::REMINDER_STATUS_INACTIVE -// NativeRdb::ValuesBucket statusValues; -// statusValues.PutInt(ReminderBaseTable::STATE, ReminderRequest::REMINDER_STATUS_INACTIVE); -// int32_t statusChangedRows = STATE_FAIL; -// int32_t ret = rdbStore_->Update(statusChangedRows, ReminderBaseTable::TABLE_NAME, statusValues); -// ANSR_LOGD("Change status to inactive, changed rows: %{public}d.", statusChangedRows); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Init data failed."); -// return STATE_FAIL; -// } -// return STATE_OK; -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::DeleteBase(const std::string& deleteCondition) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// int32_t deletedRows = STATE_FAIL; -// std::vector whereArgs; -// int32_t ret = rdbStore_->Delete(deletedRows, ReminderBaseTable::TABLE_NAME, deleteCondition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete operation failed, deleteConditon: %{public}s," \ -// "result: %{public}d.", deleteCondition.c_str(), ret); -// } -// ANSR_LOGD("Delete operation done, deleteConditon: %{public}s," \ -// "deleted rows: %{public}d.", deleteCondition.c_str(), deletedRows); -// return deletedRows; -// } - -// __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::string& baseCondition, -// const std::string& assoConditon) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// rdbStore_->BeginTransaction(); -// // delete reminder_calendar -// std::string sql = "DELETE FROM " + ReminderCalendarTable::TABLE_NAME + " WHERE " -// + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::REMINDER_ID -// + " IN " + assoConditon; -// int32_t ret = rdbStore_->ExecuteSql(sql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } - -// // delete reminder_alarm -// sql = "DELETE FROM " + ReminderAlarmTable::TABLE_NAME + " WHERE " -// + ReminderAlarmTable::TABLE_NAME + "." + ReminderAlarmTable::REMINDER_ID -// + " IN " + assoConditon; -// ret = rdbStore_->ExecuteSql(sql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } - -// // delete reminder_timer -// sql = "DELETE FROM " + ReminderTimerTable::TABLE_NAME + " WHERE " -// + ReminderTimerTable::TABLE_NAME + "." + ReminderTimerTable::REMINDER_ID -// + " IN " + assoConditon; -// ret = rdbStore_->ExecuteSql(sql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed", ReminderTimerTable::TABLE_NAME.c_str()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } - -// // delete reminder_base -// sql = "DELETE FROM " + ReminderBaseTable::TABLE_NAME + " WHERE " + baseCondition; -// ret = rdbStore_->ExecuteSql(sql); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Delete from %{public}s failed", ReminderCalendarTable::TABLE_NAME.c_str()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// rdbStore_->Commit(); -// return STATE_OK; -// } - -// int32_t ReminderStore::Insert( -// const sptr& reminder, const sptr& bundleOption) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// int64_t rowId = STATE_FAIL; -// NativeRdb::ValuesBucket baseValues; -// ReminderStrategy::AppendValuesBucket(reminder, baseValues); - -// rdbStore_->BeginTransaction(); -// // insert reminder_base -// int32_t ret = rdbStore_->Insert(rowId, ReminderBaseTable::TABLE_NAME, baseValues); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Insert reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } - -// // insert reminder_alarm or reminder_calendar -// NativeRdb::ValuesBucket values; -// rowId = STATE_FAIL; -// switch (reminder->GetReminderType()) { -// case ReminderRequest::ReminderType::CALENDAR: { -// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Insert(rowId, ReminderCalendarTable::TABLE_NAME, values); -// break; -// } -// case ReminderRequest::ReminderType::ALARM: { -// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Insert(rowId, ReminderAlarmTable::TABLE_NAME, values); -// break; -// } -// case ReminderRequest::ReminderType::TIMER: { -// ReminderTimerStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Insert(rowId, ReminderTimerTable::TABLE_NAME, values); -// break; -// } -// default: { -// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); -// ret = STATE_FAIL; -// break; -// } -// } -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Insert operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// rdbStore_->Commit(); -// ANSR_LOGD("Insert successfully, reminderId=%{public}d.", reminder->GetReminderId()); -// return STATE_OK; -// } - -// int32_t ReminderStore::Update( -// const sptr& reminder, const sptr& bundleOption) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return STATE_FAIL; -// } -// int32_t rowId = STATE_FAIL; -// NativeRdb::ValuesBucket baseValues; -// ReminderStrategy::AppendValuesBucket(reminder, baseValues); - -// std::string updateCondition = ReminderBaseTable::REMINDER_ID -// + " = " + std::to_string(reminder->GetReminderId()); - -// rdbStore_->BeginTransaction(); -// // update reminder_base -// std::vector whereArgs; -// int32_t ret = rdbStore_->Update(rowId, ReminderBaseTable::TABLE_NAME, baseValues, updateCondition, whereArgs); -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Update reminder_base operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } - -// // update reminder_alarm or reminder_calendar -// NativeRdb::ValuesBucket values; -// rowId = STATE_FAIL; -// switch (reminder->GetReminderType()) { -// case ReminderRequest::ReminderType::CALENDAR: -// ReminderCalendarStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Update(rowId, ReminderCalendarTable::TABLE_NAME, values, updateCondition, whereArgs); -// break; -// case ReminderRequest::ReminderType::ALARM: -// ReminderAlarmStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Update(rowId, ReminderAlarmTable::TABLE_NAME, values, updateCondition, whereArgs); -// break; -// case ReminderRequest::ReminderType::TIMER: -// ReminderTimerStrategy::AppendValuesBucket(reminder, values); -// ret = rdbStore_->Update(rowId, ReminderTimerTable::TABLE_NAME, values, updateCondition, whereArgs); -// break; -// default: -// ANSR_LOGE("Insert reminder_base operation failed, unkown type."); -// ret = STATE_FAIL; -// break; -// } -// if (ret != NativeRdb::E_OK) { -// ANSR_LOGE("Update operation failed, result: %{public}d, reminderId=%{public}d.", -// ret, reminder->GetReminderId()); -// rdbStore_->RollBack(); -// return STATE_FAIL; -// } -// rdbStore_->Commit(); -// ANSR_LOGD("Update successfully, reminderId=%{public}d.", reminder->GetReminderId()); -// return STATE_OK; -// } - -// bool ReminderStore::IsReminderExist(const sptr& reminder) -// { -// NativeRdb::AbsRdbPredicates absRdbPredicates(ReminderBaseTable::TABLE_NAME); -// absRdbPredicates.EqualTo(ReminderBaseTable::REMINDER_ID, std::to_string(reminder->GetReminderId())); -// auto queryResultSet = rdbStore_->Query(absRdbPredicates, std::vector()); -// if (queryResultSet == nullptr) { -// ANSR_LOGE("QueryResultSet is null."); -// return false; -// } -// int32_t resultNum; -// queryResultSet->GetRowCount(resultNum); -// return resultNum != 0; -// } - -// std::vector> ReminderStore::GetReminders(const std::string& queryCondition) -// { -// std::vector> reminders; -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return reminders; -// } -// auto queryResultSet = Query(queryCondition); -// if (queryResultSet == nullptr) { -// return reminders; -// } -// bool isAtLastRow = false; -// int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); -// while (ret == NativeRdb::E_OK && !isAtLastRow) { -// queryResultSet->GoToNextRow(); -// sptr reminder = BuildReminder(queryResultSet); -// if (reminder != nullptr) { -// reminders.push_back(reminder); -// } -// ret = queryResultSet->IsAtLastRow(isAtLastRow); -// } -// ANSR_LOGD("Size=%{public}zu", reminders.size()); -// return reminders; -// } - -// sptr ReminderStore::BuildReminder(const std::shared_ptr& resultBase) -// { -// int32_t reminderId; -// int32_t reminderType; -// GetInt32Val(resultBase, ReminderBaseTable::REMINDER_ID, reminderId); -// GetInt32Val(resultBase, ReminderBaseTable::REMINDER_TYPE, reminderType); - -// sptr reminder = nullptr; -// std::shared_ptr resultSet; -// switch (reminderType) { -// case (static_cast(ReminderRequest::ReminderType::TIMER)): { -// reminder = new (std::nothrow) ReminderRequestTimer(reminderId); -// resultSet = Query(ReminderTimerTable::TABLE_NAME, ReminderTimerTable::SELECT_COLUMNS, reminderId); -// ReminderTimerStrategy::RecoverFromDb(reminder, resultBase, resultSet); -// break; -// } -// case (static_cast(ReminderRequest::ReminderType::CALENDAR)): { -// reminder = new (std::nothrow) ReminderRequestCalendar(reminderId); -// resultSet = Query(ReminderCalendarTable::TABLE_NAME, ReminderCalendarTable::SELECT_COLUMNS, reminderId); -// ReminderCalendarStrategy::RecoverFromDb(reminder, resultBase, resultSet); -// break; -// } -// case (static_cast(ReminderRequest::ReminderType::ALARM)): { -// reminder = new (std::nothrow) ReminderRequestAlarm(reminderId); -// resultSet = Query(ReminderAlarmTable::TABLE_NAME, ReminderAlarmTable::SELECT_COLUMNS, reminderId); -// ReminderAlarmStrategy::RecoverFromDb(reminder, resultBase, resultSet); -// break; -// } -// default: { -// ANSR_LOGE("ReminderType from database is error, reminderType %{public}d.", reminderType); -// break; -// } -// } -// if (reminder == nullptr) { -// ANSR_LOGW("BuildReminder fail."); -// } -// return reminder; -// } - -// std::shared_ptr ReminderStore::Query(const std::string& tableName, const std::string& colums, -// const int32_t reminderId) -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return nullptr; -// } -// std::string queryCondition = "SELECT " + colums + " FROM " + tableName -// + " WHERE " + ReminderBaseTable::REMINDER_ID + " = " + std::to_string(reminderId); -// auto queryResultSet = Query(queryCondition); -// if (queryResultSet == nullptr) { -// return nullptr; -// } -// int32_t resultNum = 0; -// queryResultSet->GetRowCount(resultNum); -// if (resultNum == 0) { -// return nullptr; -// } -// queryResultSet->GoToNextRow(); -// return queryResultSet; -// } - -// std::shared_ptr ReminderStore::Query(const std::string& queryCondition) const -// { -// if (rdbStore_ == nullptr) { -// ANSR_LOGE("Rdb store is not initialized."); -// return nullptr; -// } -// std::vector whereArgs; -// return rdbStore_->QuerySql(queryCondition, whereArgs); -// } -// } // namespace Notification -// } // namespace OHOS diff --git a/services/ans/src/reminder_table.cpp b/services/ans/src/reminder_table.cpp deleted file mode 100644 index bd0096ab8..000000000 --- a/services/ans/src/reminder_table.cpp +++ /dev/null @@ -1,178 +0,0 @@ -// /* -// * Copyright (c) 2023 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 "reminder_table.h" - -// namespace OHOS { -// namespace Notification { -// // reminder base table -// const std::string ReminderBaseTable::TABLE_NAME = "reminder_base"; -// const std::string ReminderBaseTable::REMINDER_ID = "reminder_id"; -// const std::string ReminderBaseTable::PACKAGE_NAME = "package_name"; -// const std::string ReminderBaseTable::USER_ID = "user_id"; -// const std::string ReminderBaseTable::UID = "uid"; -// const std::string ReminderBaseTable::SYSTEM_APP = "system_app"; -// const std::string ReminderBaseTable::REMINDER_TYPE = "reminder_type"; -// const std::string ReminderBaseTable::REMINDER_TIME = "reminder_time"; -// const std::string ReminderBaseTable::TRIGGER_TIME = "trigger_time"; -// const std::string ReminderBaseTable::TIME_INTERVAL = "time_interval"; -// const std::string ReminderBaseTable::SNOOZE_TIMES = "snooze_times"; -// const std::string ReminderBaseTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; -// const std::string ReminderBaseTable::RING_DURATION = "ring_duration"; -// const std::string ReminderBaseTable::IS_EXPIRED = "is_expired"; -// const std::string ReminderBaseTable::STATE = "state"; -// const std::string ReminderBaseTable::ACTION_BUTTON_INFO = "button_info"; -// const std::string ReminderBaseTable::CUSTOM_BUTTON_URI = "custom_button_uri"; -// const std::string ReminderBaseTable::SLOT_ID = "slot_id"; -// const std::string ReminderBaseTable::SNOOZE_SLOT_ID = "snooze_slot_id"; -// const std::string ReminderBaseTable::NOTIFICATION_ID = "notification_id"; -// const std::string ReminderBaseTable::TITLE = "title"; -// const std::string ReminderBaseTable::CONTENT = "content"; -// const std::string ReminderBaseTable::SNOOZE_CONTENT = "snooze_content"; -// const std::string ReminderBaseTable::EXPIRED_CONTENT = "expired_content"; -// const std::string ReminderBaseTable::WANT_AGENT = "want_agent"; -// const std::string ReminderBaseTable::MAX_SCREEN_WANT_AGENT = "max_screen_want_agent"; -// const std::string ReminderBaseTable::TAP_DISMISSED = "tap_dismissed"; -// const std::string ReminderBaseTable::AUTO_DELETED_TIME = "auto_deleted_time"; -// const std::string ReminderBaseTable::GROUP_ID = "group_id"; -// const std::string ReminderBaseTable::CUSTOM_RING_URI = "custom_ring_uri"; -// const std::string ReminderBaseTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; -// const std::string ReminderBaseTable::CREATOR_UID = "creator_uid"; - -// // reminder alarm table -// const std::string ReminderAlarmTable::TABLE_NAME = "reminder_alarm"; -// const std::string ReminderAlarmTable::REMINDER_ID = "reminder_id"; -// const std::string ReminderAlarmTable::ALARM_HOUR = "alarm_hour"; -// const std::string ReminderAlarmTable::ALARM_MINUTE = "alarm_minute"; -// const std::string ReminderAlarmTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; - -// // reminder calendar table -// const std::string ReminderCalendarTable::TABLE_NAME = "reminder_calendar"; -// const std::string ReminderCalendarTable::REMINDER_ID = "reminder_id"; -// const std::string ReminderCalendarTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; -// const std::string ReminderCalendarTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; -// const std::string ReminderCalendarTable::FIRST_DESIGNATE_DAY = "first_designate_day"; -// const std::string ReminderCalendarTable::CALENDAR_DATE_TIME = "calendar_date_time"; -// const std::string ReminderCalendarTable::CALENDAR_END_DATE_TIME = "calendar_end_date_time"; -// const std::string ReminderCalendarTable::REPEAT_DAYS = "repeat_days"; -// const std::string ReminderCalendarTable::REPEAT_MONTHS = "repeat_months"; -// const std::string ReminderCalendarTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; -// const std::string ReminderCalendarTable::RRULE_WANT_AGENT = "rrule_want_agent"; -// const std::string ReminderCalendarTable::EXCLUDE_DATES = "exclude_dates"; -// const std::string ReminderCalendarTable::CALENDAR_LAST_DATE_TIME = "calendar_last_date_time"; - -// // reminder timer table -// const std::string ReminderTimerTable::TABLE_NAME = "reminder_timer"; -// const std::string ReminderTimerTable::REMINDER_ID = "reminder_id"; -// const std::string ReminderTimerTable::TRIGGER_SECOND = "trigger_second"; -// const std::string ReminderTimerTable::START_DATE_TIME = "start_date_time"; -// const std::string ReminderTimerTable::END_DATE_TIME = "end_date_time"; - -// std::string ReminderBaseTable::ADD_COLUMNS = ""; -// std::string ReminderBaseTable::SELECT_COLUMNS = ""; - -// std::string ReminderAlarmTable::ADD_COLUMNS = ""; -// std::string ReminderAlarmTable::SELECT_COLUMNS = ""; - -// std::string ReminderCalendarTable::ADD_COLUMNS = ""; -// std::string ReminderCalendarTable::SELECT_COLUMNS = ""; - -// std::string ReminderTimerTable::ADD_COLUMNS = ""; -// std::string ReminderTimerTable::SELECT_COLUMNS = ""; - -// static inline void AddColumn(const std::string& name, const std::string& type, std::string& sqlOfColumns, -// std::string& columns) -// { -// columns.append(name).append(","); -// sqlOfColumns.append(name).append(" "); -// sqlOfColumns.append(type).append(", "); -// } - -// static inline void AddColumnEnd(const std::string& name, const std::string& type, std::string& sqlOfColumns, -// std::string& columns) -// { -// columns.append(name); -// sqlOfColumns.append(name).append(" "); -// sqlOfColumns.append(type); -// } - -// void ReminderBaseTable::InitDbColumns() -// { -// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(PACKAGE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(USER_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(SYSTEM_APP, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(REMINDER_TYPE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(REMINDER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(TRIGGER_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(TIME_INTERVAL, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(RING_DURATION, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(IS_EXPIRED, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(STATE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(ACTION_BUTTON_INFO, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CUSTOM_BUTTON_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(SNOOZE_SLOT_ID, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(NOTIFICATION_ID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(TITLE, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(SNOOZE_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(EXPIRED_CONTENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(MAX_SCREEN_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(TAP_DISMISSED, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(AUTO_DELETED_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(GROUP_ID, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CUSTOM_RING_URI, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CREATOR_BUNDLE_NAME, "TEXT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumnEnd(CREATOR_UID, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// } - -// void ReminderAlarmTable::InitDbColumns() -// { -// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(ALARM_HOUR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(ALARM_MINUTE, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumnEnd(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// } - -// void ReminderCalendarTable::InitDbColumns() -// { -// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(FIRST_DESIGNATE_YEAR, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(FIRST_DESIGNATE_MONTH, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(FIRST_DESIGNATE_DAY, "INT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CALENDAR_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(CALENDAR_END_DATE_TIME, "BIGINT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(REPEAT_DAYS, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(REPEAT_MONTHS, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(REPEAT_DAYS_OF_WEEK, "INT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(RRULE_WANT_AGENT, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(EXCLUDE_DATES, "TEXT", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumnEnd(CALENDAR_LAST_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// } - -// void ReminderTimerTable::InitDbColumns() -// { -// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(TRIGGER_SECOND, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumn(START_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// AddColumnEnd(END_DATE_TIME, "BIGINT NOT NULL", ADD_COLUMNS, SELECT_COLUMNS); -// } -// } -// } diff --git a/services/ans/src/reminder_table_old.cpp b/services/ans/src/reminder_table_old.cpp deleted file mode 100644 index bbcac59c4..000000000 --- a/services/ans/src/reminder_table_old.cpp +++ /dev/null @@ -1,157 +0,0 @@ -// /* -// * Copyright (c) 2024 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 "reminder_table_old.h" - -// namespace OHOS { -// namespace Notification { -// // Reminder Table Basic Columns. -// const std::string ReminderTable::TABLE_NAME = "reminder"; -// const std::string ReminderTable::REMINDER_ID = "reminder_id"; -// const std::string ReminderTable::PKG_NAME = "package_name"; -// const std::string ReminderTable::USER_ID = "user_id"; -// const std::string ReminderTable::UID = "uid"; -// const std::string ReminderTable::SYS_APP = "system_app"; -// const std::string ReminderTable::APP_LABEL = "app_label"; -// const std::string ReminderTable::REMINDER_TYPE = "reminder_type"; -// const std::string ReminderTable::REMINDER_TIME = "reminder_time"; -// const std::string ReminderTable::TRIGGER_TIME = "trigger_time"; -// const std::string ReminderTable::RTC_TRIGGER_TIME = "rtc_trigger_time"; -// const std::string ReminderTable::TIME_INTERVAL = "time_interval"; -// const std::string ReminderTable::SNOOZE_TIMES = "snooze_times"; -// const std::string ReminderTable::DYNAMIC_SNOOZE_TIMES = "dynamic_snooze_times"; -// const std::string ReminderTable::RING_DURATION = "ring_duration"; -// const std::string ReminderTable::IS_EXPIRED = "is_expired"; -// const std::string ReminderTable::IS_ACTIVE = "is_active"; -// const std::string ReminderTable::STATE = "state"; -// const std::string ReminderTable::ZONE_ID = "zone_id"; -// const std::string ReminderTable::HAS_SCHEDULED_TIMEOUT = "has_ScheduledTimeout"; -// const std::string ReminderTable::ACTION_BUTTON_INFO = "button_info"; -// const std::string ReminderTable::CUSTOM_BUTTON_URI = "custom_button_uri"; -// const std::string ReminderTable::SLOT_ID = "slot_id"; -// const std::string ReminderTable::SNOOZE_SLOT_ID = "snooze_slot_id"; -// const std::string ReminderTable::NOTIFICATION_ID = "notification_id"; -// const std::string ReminderTable::TITLE = "title"; -// const std::string ReminderTable::CONTENT = "content"; -// const std::string ReminderTable::SNOOZE_CONTENT = "snooze_content"; -// const std::string ReminderTable::EXPIRED_CONTENT = "expired_content"; -// const std::string ReminderTable::AGENT = "agent"; -// const std::string ReminderTable::MAX_SCREEN_AGENT = "maxScreen_agent"; -// const std::string ReminderTable::TAP_DISMISSED = "tapDismissed"; -// const std::string ReminderTable::AUTO_DELETED_TIME = "autoDeletedTime"; -// const std::string ReminderTable::REPEAT_DAYS_OF_WEEK = "repeat_days_of_week"; -// const std::string ReminderTable::GROUP_ID = "groupId"; -// const std::string ReminderTable::CUSTOM_RING_URI = "custom_ring_uri"; -// const std::string ReminderTable::CREATOR_BUNDLE_NAME = "creator_bundle_name"; - -// // Reminder Table Calendar Columns. -// const std::string ReminderTable::REPEAT_DAYS = "repeat_days"; -// const std::string ReminderTable::REPEAT_MONTHS = "repeat_months"; -// const std::string ReminderTable::FIRST_DESIGNATE_YEAR = "first_designate_year"; -// const std::string ReminderTable::FIRST_DESIGNATE_MONTH = "first_designate_month"; -// const std::string ReminderTable::FIRST_DESIGNATE_DAY = "first_designate_day"; -// const std::string ReminderTable::CALENDAR_YEAR = "calendar_year"; -// const std::string ReminderTable::CALENDAR_MONTH = "calendar_month"; -// const std::string ReminderTable::CALENDAR_DAY = "calendar_day"; -// const std::string ReminderTable::CALENDAR_HOUR = "calendar_hour"; -// const std::string ReminderTable::CALENDAR_MINUTE = "calendar_minute"; - -// // Reminder Table Alarm Columns. -// const std::string ReminderTable::ALARM_HOUR = "alarm_hour"; -// const std::string ReminderTable::ALARM_MINUTE = "alarm_minute"; - -// std::string ReminderTable::ADD_COLUMNS = ""; -// std::string ReminderTable::SELECT_COLUMNS = ""; - -// void ReminderTable::InitDbColumns() -// { -// InitBasicColumns(); -// InitCalendarColumns(); -// InitAlarmColumns(); -// } - -// void ReminderTable::InitBasicColumns() -// { -// AddColumn(REMINDER_ID, "INTEGER PRIMARY KEY"); -// AddColumn(PKG_NAME, "TEXT NOT NULL"); -// AddColumn(USER_ID, "INT NOT NULL"); -// AddColumn(UID, "INT NOT NULL"); -// AddColumn(SYS_APP, "TEXT NOT NULL"); -// AddColumn(APP_LABEL, "TEXT"); -// AddColumn(REMINDER_TYPE, "INT NOT NULL"); -// AddColumn(REMINDER_TIME, "BIGINT NOT NULL"); -// AddColumn(TRIGGER_TIME, "BIGINT NOT NULL"); -// AddColumn(RTC_TRIGGER_TIME, "BIGINT NOT NULL"); -// AddColumn(TIME_INTERVAL, "BIGINT NOT NULL"); -// AddColumn(SNOOZE_TIMES, "INT NOT NULL"); -// AddColumn(DYNAMIC_SNOOZE_TIMES, "INT NOT NULL"); -// AddColumn(RING_DURATION, "BIGINT NOT NULL"); -// AddColumn(IS_EXPIRED, "TEXT NOT NULL"); -// AddColumn(IS_ACTIVE, "TEXT NOT NULL"); -// AddColumn(STATE, "INT NOT NULL"); -// AddColumn(ZONE_ID, "TEXT"); -// AddColumn(HAS_SCHEDULED_TIMEOUT, "TEXT"); -// AddColumn(ACTION_BUTTON_INFO, "TEXT"); -// AddColumn(CUSTOM_BUTTON_URI, "TEXT"); -// AddColumn(SLOT_ID, "INT"); -// AddColumn(SNOOZE_SLOT_ID, "INT"); -// AddColumn(NOTIFICATION_ID, "INT NOT NULL"); -// AddColumn(TITLE, "TEXT"); -// AddColumn(CONTENT, "TEXT"); -// AddColumn(SNOOZE_CONTENT, "TEXT"); -// AddColumn(EXPIRED_CONTENT, "TEXT"); -// AddColumn(AGENT, "TEXT"); -// AddColumn(MAX_SCREEN_AGENT, "TEXT"); -// AddColumn(TAP_DISMISSED, "TEXT"); -// AddColumn(AUTO_DELETED_TIME, "BIGINT"); -// AddColumn(REPEAT_DAYS_OF_WEEK, "INT"); -// AddColumn(GROUP_ID, "TEXT"); -// AddColumn(CUSTOM_RING_URI, "TEXT"); -// AddColumn(CREATOR_BUNDLE_NAME, "TEXT", false); -// } - -// void ReminderTable::InitCalendarColumns() -// { -// AddColumn(REPEAT_DAYS, "INT"); -// AddColumn(REPEAT_MONTHS, "INT"); -// AddColumn(FIRST_DESIGNATE_YEAR, "INT"); -// AddColumn(FIRST_DESIGNATE_MONTH, "INT"); -// AddColumn(FIRST_DESIGNATE_DAY, "INT"); -// AddColumn(CALENDAR_YEAR, "INT"); -// AddColumn(CALENDAR_MONTH, "INT"); -// AddColumn(CALENDAR_DAY, "INT"); -// AddColumn(CALENDAR_HOUR, "INT"); -// AddColumn(CALENDAR_MINUTE, "INT"); -// } - -// void ReminderTable::InitAlarmColumns() -// { -// AddColumn(ALARM_HOUR, "INT"); -// AddColumn(ALARM_MINUTE, "INT", true); -// } - -// void ReminderTable ::AddColumn( -// const std::string& name, const std::string& type, bool isEnd) -// { -// if (!isEnd) { -// SELECT_COLUMNS.append(name).append(","); -// ADD_COLUMNS += name + " " + type + ", "; -// } else { -// SELECT_COLUMNS.append(name); -// ADD_COLUMNS += name + " " + type; -// } -// } -// } -// } diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp deleted file mode 100644 index 13360671d..000000000 --- a/services/ans/src/reminder_timer_info.cpp +++ /dev/null @@ -1,51 +0,0 @@ -// /* -// * Copyright (c) 2021-2022 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 "reminder_timer_info.h" - -// #include "ans_log_wrapper.h" -// #include "common_event_manager.h" -// #include "reminder_request.h" - -// using namespace OHOS::EventFwk; -// using namespace OHOS::HiviewDFX; -// namespace OHOS { -// namespace Notification { -// void ReminderTimerInfo::SetType(const int &_type) -// { -// type = _type; -// } - -// void ReminderTimerInfo::SetRepeat(bool _repeat) -// { -// repeat = _repeat; -// } - -// void ReminderTimerInfo::SetInterval(const uint64_t &_interval) -// { -// interval = _interval; -// } - -// void ReminderTimerInfo::SetWantAgent(std::shared_ptr _wantAgent) -// { -// wantAgent = _wantAgent; -// } - -// void ReminderTimerInfo::OnTrigger() -// { -// ANSR_LOGI("Timing is arrivelled."); -// } -// } -// } -- Gitee From b40c985ff8a34958a73a8575807389d81e83b5d3 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 15 Nov 2024 17:40:52 +0800 Subject: [PATCH 05/29] push Signed-off-by: fengyang --- .../manager/ans_manager_proxy_reminder.cpp | 295 ------------------ interfaces/ndk/BUILD.gn | 5 +- tools/dump/BUILD.gn | 5 +- 3 files changed, 2 insertions(+), 303 deletions(-) delete mode 100644 frameworks/core/src/manager/ans_manager_proxy_reminder.cpp diff --git a/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp b/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp deleted file mode 100644 index e5b32313d..000000000 --- a/frameworks/core/src/manager/ans_manager_proxy_reminder.cpp +++ /dev/null @@ -1,295 +0,0 @@ -/* - * Copyright (c) 2021-2023 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 "ans_const_define.h" -#include "ans_inner_errors.h" -#include "ans_log_wrapper.h" -#include "ans_subscriber_local_live_view_interface.h" -#include "distributed_notification_service_ipc_interface_code.h" -#include "message_option.h" -#include "message_parcel.h" -#include "parcel.h" -#include "reminder_request_alarm.h" -#include "reminder_request_calendar.h" -#include "reminder_request_timer.h" -#include "ans_manager_proxy.h" - -namespace OHOS { -namespace Notification { -// ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) -// { -// ANSR_LOGI("PublishReminder"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[PublishReminder] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (reminder == nullptr) { -// ANSR_LOGW("[PublishReminder] fail: reminder is null ptr."); -// return ERR_ANS_INVALID_PARAM; -// } -// if (!data.WriteUint8(static_cast(reminder->GetReminderType()))) { -// ANSR_LOGE("[PublishReminder] fail: write reminder type failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteParcelable(reminder)) { -// ANSR_LOGE("[Publish] fail: write reminder parcelable failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::PUBLISH_REMINDER, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// int32_t reminderId = -1; -// if (!reply.ReadInt32(reminderId)) { -// ANSR_LOGE("[PublishReminder] fail: read reminder id failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// reminder->SetReminderId(reminderId); -// ANSR_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[PublishReminder] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) -// { -// ANSR_LOGI("[CancelReminder]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[CancelReminder] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteInt32(reminderId)) { -// ANSR_LOGE("[CancelReminder] fail: write reminder id failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_REMINDER, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[CancelReminder] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::CancelAllReminders() -// { -// ANSR_LOGI("[CancelAllReminders]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[CancelAllReminders] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::CANCEL_ALL_REMINDERS, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[CancelAllReminders] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::GetValidReminders(std::vector> &reminders) -// { -// ANSR_LOGI("[GetValidReminders]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[GetValidReminders] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// uint8_t count = 0; -// if (!reply.ReadUint8(count)) { -// ANSR_LOGE("[GetValidReminders] fail: read reminder count failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// ANSR_LOGD("[GetValidReminders] count=%{public}hhu", count); -// reminders.clear(); -// result = ReadReminders(count, reply, reminders); -// if (result != ERR_OK) { -// ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); -// return result; -// } else { -// ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[GetValidReminders] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::AddExcludeDate(const int32_t reminderId, const uint64_t date) -// { -// ANSR_LOGI("[AddExcludeDate]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[AddExcludeDate] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteInt32(reminderId)) { -// ANSR_LOGE("[AddExcludeDate] fail: write reminder id failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteUint64(date)) { -// ANSR_LOGE("[AddExcludeDate] fail: write exclude date failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[AddExcludeDate] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[AddExcludeDate] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::DelExcludeDates(const int32_t reminderId) -// { -// ANSR_LOGI("[DelExcludeDates]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[DelExcludeDates] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteInt32(reminderId)) { -// ANSR_LOGE("[DelExcludeDates] fail: write reminder id failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[DelExcludeDates] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[DelExcludeDates] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::GetExcludeDates(const int32_t reminderId, std::vector& dates) -// { -// ANSR_LOGI("[GetExcludeDates]"); -// MessageParcel data; -// if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { -// ANSR_LOGE("[GetExcludeDates] fail: write interface token failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// if (!data.WriteInt32(reminderId)) { -// ANSR_LOGE("[GetExcludeDates] fail: write reminder id failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } - -// MessageParcel reply; -// MessageOption option = {MessageOption::TF_SYNC}; -// ErrCode result = InnerTransact(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER, option, data, reply); -// if (result != ERR_OK) { -// ANSR_LOGE("[GetExcludeDates] fail: transact ErrCode=%{public}d", result); -// return ERR_ANS_TRANSACT_FAILED; -// } -// uint8_t count = 0; -// if (!reply.ReadUint8(count)) { -// ANSR_LOGE("[GetExcludeDates] fail: read exclude date count failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// ANSR_LOGD("[GetExcludeDates] count=%{public}hhu", count); -// dates.clear(); -// for (uint8_t i = 0; i < count; i++) { -// uint64_t date = 0; -// if (!reply.ReadUint64(date)) { -// ANSR_LOGE("[GetExcludeDates] fail: read exclude date"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// dates.push_back(date); -// } -// if (!reply.ReadInt32(result)) { -// ANSR_LOGE("[GetExcludeDates] fail: read result failed."); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// return result; -// } - -// ErrCode AnsManagerProxy::ReadReminders( -// uint8_t &count, MessageParcel &reply, std::vector> &reminders) -// { -// for (uint8_t i = 0; i < count; i++) { -// uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); -// if (!reply.ReadUint8(typeInfo)) { -// ANSR_LOGE("Failed to read reminder type"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// auto reminderType = static_cast(typeInfo); -// sptr reminder; -// if (ReminderRequest::ReminderType::ALARM == reminderType) { -// ANSR_LOGD("[GetValidReminders] alarm"); -// reminder = reply.ReadParcelable(); -// } else if (ReminderRequest::ReminderType::TIMER == reminderType) { -// ANSR_LOGD("[GetValidReminders] timer"); -// reminder = reply.ReadParcelable(); -// } else if (ReminderRequest::ReminderType::CALENDAR == reminderType) { -// ANSR_LOGD("[GetValidReminders] calendar"); -// reminder = reply.ReadParcelable(); -// } else { -// ANSR_LOGW("[GetValidReminders] type=%{public}hhu", typeInfo); -// return ERR_ANS_INVALID_PARAM; -// } -// if (!reminder) { -// ANSR_LOGE("[GetValidReminders] fail: Reminder ReadParcelable failed"); -// return ERR_ANS_PARCELABLE_FAILED; -// } -// reminders.push_back(reminder); -// } -// return ERR_OK; -// } -} // namespace Notification -} // namespace OHOS diff --git a/interfaces/ndk/BUILD.gn b/interfaces/ndk/BUILD.gn index ef401769f..08121f875 100644 --- a/interfaces/ndk/BUILD.gn +++ b/interfaces/ndk/BUILD.gn @@ -52,10 +52,7 @@ ohos_shared_library("ohnotification") { sources = [ "src/notification.cpp" ] - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${frameworks_module_reminder_path}:reminder_innerkits", - ] + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] external_deps = [ "ability_base:base", diff --git a/tools/dump/BUILD.gn b/tools/dump/BUILD.gn index a703f391e..c9bd4bc7d 100644 --- a/tools/dump/BUILD.gn +++ b/tools/dump/BUILD.gn @@ -46,10 +46,7 @@ ohos_executable("anm") { cflags += [ "-DBINDER_IPC_32BIT" ] } - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${frameworks_module_reminder_path}:reminder_innerkits", - ] + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] configs = [ "${frameworks_module_ans_path}:ans_innerkits_public_config" ] -- Gitee From 083d07614d2880832d838825f8fd0498b69fc975 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 18 Nov 2024 14:36:01 +0800 Subject: [PATCH 06/29] push Signed-off-by: fengyang --- frameworks/ans/BUILD.gn | 1 - frameworks/reminder/BUILD.gn | 1 - services/ans/BUILD.gn | 9 - .../advanced_notification_service_ability.h | 1 - ...advanced_notification_reminder_service.cpp | 201 ------ services/ans/src/reminder_store_strategy.cpp | 649 ------------------ 6 files changed, 862 deletions(-) delete mode 100644 services/ans/src/reminder_store_strategy.cpp diff --git a/frameworks/ans/BUILD.gn b/frameworks/ans/BUILD.gn index 2cd10c2ae..b82324819 100644 --- a/frameworks/ans/BUILD.gn +++ b/frameworks/ans/BUILD.gn @@ -63,7 +63,6 @@ ohos_shared_library("ans_innerkits") { "${core_path}/src/manager/ans_manager_proxy_bundle.cpp", "${core_path}/src/manager/ans_manager_proxy_distributed.cpp", "${core_path}/src/manager/ans_manager_proxy_disturb.cpp", - "${core_path}/src/manager/ans_manager_proxy_reminder.cpp", "${core_path}/src/manager/ans_manager_proxy_slot.cpp", "${core_path}/src/manager/ans_manager_proxy_subscribe.cpp", "${core_path}/src/manager/ans_manager_proxy_utils.cpp", diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index 05f61ec66..f33735e04 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -40,7 +40,6 @@ config("reminder_innerkits_public_config") { "${core_path}/common/include", "${core_path}/include", "${target_gen_dir}", - "//third_party/json/single_include", ] } diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 5e1cda269..060444e32 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -100,16 +100,7 @@ ohos_source_set("ans_service_sources") { "src/notification_timer_info.cpp", "src/os_account_manager_helper.cpp", "src/permission_filter.cpp", - "src/reminder_config_change_observer.cpp", - "src/reminder_data_manager.cpp", - "src/reminder_data_manager_inner.cpp", - "src/reminder_event_manager.cpp", - "src/reminder_store.cpp", - "src/reminder_store_strategy.cpp", "src/reminder_swing_decision_center.cpp", - "src/reminder_table.cpp", - "src/reminder_table_old.cpp", - "src/reminder_timer_info.cpp", "src/report_time_info.cpp", "src/system_dialog_connect_stb.cpp", "src/system_event_observer.cpp", diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 6caf7f477..682b0dbc8 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -20,7 +20,6 @@ #include "advanced_datashare_observer.h" #include "advanced_notification_service.h" -#include "reminder_data_manager.h" #include "system_ability_definition.h" #include "notification_extension_wrapper.h" diff --git a/services/ans/src/advanced_notification_reminder_service.cpp b/services/ans/src/advanced_notification_reminder_service.cpp index 02a63b7a1..98afa7212 100644 --- a/services/ans/src/advanced_notification_reminder_service.cpp +++ b/services/ans/src/advanced_notification_reminder_service.cpp @@ -40,207 +40,6 @@ namespace OHOS { namespace Notification { -// inline bool AdvancedNotificationService::CheckReminderPermission() -// { -// Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); -// ErrCode result = Security::AccessToken::AccessTokenKit::VerifyAccessToken( -// callerToken, "ohos.permission.PUBLISH_AGENT_REMINDER"); -// return result == Security::AccessToken::PermissionState::PERMISSION_GRANTED; -// } - -// ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Publish reminder"); -// if (!reminder) { -// ANSR_LOGE("ReminderRequest object is nullptr"); -// return ERR_ANS_INVALID_PARAM; -// } - -// std::string bundle = GetClientBundleName(); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } -// if (!AllowUseReminder(bundle)) { -// ANSR_LOGW("The number of reminders exceeds the limit[0]."); -// return ERR_REMINDER_NUMBER_OVERLOAD; -// } -// ANSR_LOGD("is system app: %{public}d", AccessTokenHelper::IsSystemApp()); -// reminder->SetSystemApp(AccessTokenHelper::IsSystemApp()); -// sptr notificationRequest = reminder->GetNotificationRequest(); -// reminder->InitCreatorBundleName(bundle); -// reminder->InitCreatorUid(IPCSkeleton::GetCallingUid()); -// if (reminder->GetWantAgentInfo() == nullptr || reminder->GetMaxScreenWantAgentInfo() == nullptr) { -// ANSR_LOGE("wantagent info is nullptr"); -// return ERR_ANS_INVALID_PARAM; -// } -// std::string wantAgentName = reminder->GetWantAgentInfo()->pkgName; -// std::string msWantAgentName = reminder->GetMaxScreenWantAgentInfo()->pkgName; -// if (wantAgentName != msWantAgentName && wantAgentName != "" && msWantAgentName != "") { -// ANSR_LOGE("wantAgentName is not same to msWantAgentName, wantAgentName:%{public}s, msWantAgentName:%{public}s", -// wantAgentName.c_str(), msWantAgentName.c_str()); -// return ERR_ANS_INVALID_PARAM; -// } -// if (wantAgentName != bundle && wantAgentName != "") { -// ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(), -// wantAgentName.c_str()); -// SetAgentNotification(notificationRequest, wantAgentName); -// } else if (msWantAgentName != bundle && msWantAgentName != "") { -// ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(), -// msWantAgentName.c_str()); -// SetAgentNotification(notificationRequest, msWantAgentName); -// } -// sptr bundleOption = nullptr; -// ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); -// if (result != ERR_OK) { -// ANSR_LOGW("PrepareNotificationInfo fail"); -// return result; -// } -// bool allowedNotify = false; -// result = IsAllowedNotifySelf(bundleOption, allowedNotify); -// if (!reminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { -// ANSR_LOGW("The application does not request enable notification"); -// return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// return ERR_NO_INIT; -// } -// return rdm->PublishReminder(reminder, bundleOption); -// } - -// ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Cancel Reminder"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// return ERR_ANS_INVALID_BUNDLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// return ERR_NO_INIT; -// } -// return rdm->CancelReminder(reminderId, bundleOption); -// } - -// ErrCode AdvancedNotificationService::CancelAllReminders() -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Cancel all reminders"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// return ERR_ANS_INVALID_BUNDLE; -// } -// int32_t userId = -1; -// AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// return ERR_NO_INIT; -// } -// return rdm->CancelAllReminders(bundleOption->GetBundleName(), userId, bundleOption->GetUid()); -// } - - -// ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("GetValidReminders"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// reminders.clear(); -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// return ERR_ANS_INVALID_BUNDLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// return ERR_NO_INIT; -// } -// rdm->GetValidReminders(bundleOption, reminders); -// ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); -// return ERR_OK; -// } - -// ErrCode AdvancedNotificationService::AddExcludeDate(const int32_t reminderId, const uint64_t date) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Add Exclude Date"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// ANSR_LOGW("Generate bundle option failed!"); -// return ERR_ANS_INVALID_BUNDLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// ANSR_LOGW("Reminder data manager not init!"); -// return ERR_NO_INIT; -// } -// return rdm->AddExcludeDate(reminderId, date, bundleOption); -// } - -// ErrCode AdvancedNotificationService::DelExcludeDates(const int32_t reminderId) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Del Exclude Dates"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// ANSR_LOGW("Generate bundle option failed!"); -// return ERR_ANS_INVALID_BUNDLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// ANSR_LOGW("Reminder data manager not init!"); -// return ERR_NO_INIT; -// } -// return rdm->DelExcludeDates(reminderId, bundleOption); -// } - -// ErrCode AdvancedNotificationService::GetExcludeDates(const int32_t reminderId, std::vector& dates) -// { -// HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); -// ANSR_LOGI("Get Exclude Dates"); -// if (!CheckReminderPermission()) { -// ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); -// return ERR_REMINDER_PERMISSION_DENIED; -// } - -// sptr bundleOption = GenerateBundleOption(); -// if (bundleOption == nullptr) { -// ANSR_LOGW("Generate bundle option failed!"); -// return ERR_ANS_INVALID_BUNDLE; -// } -// auto rdm = ReminderDataManager::GetInstance(); -// if (rdm == nullptr) { -// ANSR_LOGW("Reminder data manager not init!"); -// return ERR_NO_INIT; -// } -// return rdm->GetExcludeDates(reminderId, bundleOption, dates); -// } #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED NotificationConstant::RemindType AdvancedNotificationService::GetRemindType() diff --git a/services/ans/src/reminder_store_strategy.cpp b/services/ans/src/reminder_store_strategy.cpp deleted file mode 100644 index b880ea119..000000000 --- a/services/ans/src/reminder_store_strategy.cpp +++ /dev/null @@ -1,649 +0,0 @@ -/* - * Copyright (c) 2024 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 "reminder_store_strategy.h" - -#include "ans_log_wrapper.h" -#include "reminder_store.h" -#include "reminder_table.h" -#include "reminder_table_old.h" -#include "reminder_request_alarm.h" -#include "reminder_request_timer.h" -#include "reminder_request_calendar.h" - -namespace OHOS { -namespace Notification { -void ReminderStrategy::AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket &values, const bool oldVersion) -{ - values.PutInt(ReminderBaseTable::REMINDER_ID, reminder->GetReminderId()); - values.PutString(ReminderBaseTable::PACKAGE_NAME, reminder->GetBundleName()); - values.PutInt(ReminderBaseTable::USER_ID, reminder->GetUserId()); - values.PutInt(ReminderBaseTable::UID, reminder->GetUid()); - values.PutString(ReminderBaseTable::SYSTEM_APP, reminder->IsSystemApp() ? "true" : "false"); - values.PutInt(ReminderBaseTable::REMINDER_TYPE, static_cast(reminder->GetReminderType())); - values.PutLong(ReminderBaseTable::REMINDER_TIME, reminder->GetReminderTimeInMilli()); - values.PutLong(ReminderBaseTable::TRIGGER_TIME, reminder->GetTriggerTimeInMilli()); - values.PutLong(ReminderBaseTable::TIME_INTERVAL, reminder->GetTimeInterval()); - values.PutInt(ReminderBaseTable::SNOOZE_TIMES, reminder->GetSnoozeTimes()); - values.PutInt(ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, reminder->GetSnoozeTimesDynamic()); - values.PutLong(ReminderBaseTable::RING_DURATION, reminder->GetRingDuration()); - values.PutString(ReminderBaseTable::IS_EXPIRED, reminder->IsExpired() ? "true" : "false"); - values.PutInt(ReminderBaseTable::STATE, reminder->GetState()); - values.PutString(ReminderBaseTable::ACTION_BUTTON_INFO, reminder->SerializeButtonInfo()); - values.PutString(ReminderBaseTable::CUSTOM_BUTTON_URI, reminder->GetCustomButtonUri()); - values.PutInt(ReminderBaseTable::SLOT_ID, reminder->GetSlotType()); - values.PutInt(ReminderBaseTable::SNOOZE_SLOT_ID, reminder->GetSnoozeSlotType()); - values.PutInt(ReminderBaseTable::NOTIFICATION_ID, reminder->GetNotificationId()); - values.PutString(ReminderBaseTable::TITLE, reminder->GetTitle()); - values.PutString(ReminderBaseTable::CONTENT, reminder->GetContent()); - values.PutString(ReminderBaseTable::SNOOZE_CONTENT, reminder->GetSnoozeContent()); - values.PutString(ReminderBaseTable::EXPIRED_CONTENT, reminder->GetExpiredContent()); - - if (oldVersion) { - values.PutString(ReminderBaseTable::WANT_AGENT, reminder->GetWantAgentStr()); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, reminder->GetMaxWantAgentStr()); - } else { - std::string wantInfoStr; - std::string maxWantInfoStr; - reminder->SerializeWantAgent(wantInfoStr, maxWantInfoStr); - values.PutString(ReminderBaseTable::WANT_AGENT, wantInfoStr); - values.PutString(ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantInfoStr); - } - - values.PutString(ReminderBaseTable::TAP_DISMISSED, reminder->IsTapDismissed() ? "true" : "false"); - values.PutLong(ReminderBaseTable::AUTO_DELETED_TIME, reminder->GetAutoDeletedTime()); - values.PutString(ReminderBaseTable::GROUP_ID, reminder->GetGroupId()); - values.PutString(ReminderBaseTable::CUSTOM_RING_URI, reminder->GetCustomRingUri()); - values.PutString(ReminderBaseTable::CREATOR_BUNDLE_NAME, reminder->GetCreatorBundleName()); - values.PutInt(ReminderBaseTable::CREATOR_UID, reminder->GetCreatorUid()); -} - -void ReminderStrategy::RecoverTimeFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - uint64_t reminderTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TIME, reminderTime); - reminder->SetReminderTimeInMilli(reminderTime); - - uint64_t triggerTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TRIGGER_TIME, triggerTime); - reminder->SetTriggerTimeInMilli(triggerTime); - - uint64_t timeInterval = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TIME_INTERVAL, timeInterval); - reminder->SetTimeInterval(timeInterval); - - uint8_t snoozeTimes = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_TIMES, snoozeTimes); - reminder->SetSnoozeTimes(snoozeTimes); - - uint8_t dynamicSnoozeTimes = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); - reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); - - uint64_t ringDuration = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::RING_DURATION, ringDuration); - reminder->SetRingDuration(ringDuration); - - int64_t autoDeletedTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AUTO_DELETED_TIME, autoDeletedTime); - reminder->SetAutoDeletedTime(autoDeletedTime); -} - -void ReminderStrategy::RecoverIdFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - int32_t reminderId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_ID, reminderId); - reminder->SetReminderId(reminderId); - - int32_t userId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::USER_ID, userId); - reminder->InitUserId(userId); - - int32_t uid = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::UID, uid); - reminder->InitUid(uid); - - int32_t reminderType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REMINDER_TYPE, reminderType); - reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); - - int32_t slotType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SLOT_ID, slotType); - reminder->SetSlotType(NotificationConstant::SlotType(slotType)); - - int32_t snoozeSlotType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_SLOT_ID, snoozeSlotType); - reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); - - int32_t notificationId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::NOTIFICATION_ID, notificationId); - reminder->SetNotificationId(notificationId); - - std::string groupId; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::GROUP_ID, groupId); - reminder->SetGroupId(groupId); -} - -void ReminderStrategy::RecoverContextFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - std::string bundleName; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::PKG_NAME, bundleName); - reminder->InitBundleName(bundleName); - - std::string title; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TITLE, title); - reminder->SetTitle(title); - - std::string content; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CONTENT, content); - reminder->SetContent(content); - - std::string snoozeContent; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SNOOZE_CONTENT, snoozeContent); - reminder->SetSnoozeContent(snoozeContent); - - std::string expiredContent; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::EXPIRED_CONTENT, expiredContent); - reminder->SetExpiredContent(expiredContent); - - std::string customButtonUri; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_BUTTON_URI, customButtonUri); - reminder->SetCustomButtonUri(customButtonUri); - - std::string customRingUri; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CUSTOM_RING_URI, customRingUri); - reminder->SetCustomRingUri(customRingUri); - - std::string creatorBundleName; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CREATOR_BUNDLE_NAME, creatorBundleName); - reminder->InitCreatorBundleName(creatorBundleName); -} - -void ReminderStrategy::RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (reminder == nullptr || resultSet == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - - ReminderStrategy::RecoverTimeFromOldVersion(reminder, resultSet); - ReminderStrategy::RecoverIdFromOldVersion(reminder, resultSet); - ReminderStrategy::RecoverContextFromOldVersion(reminder, resultSet); - - std::string isSystemApp; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::SYS_APP, isSystemApp); - reminder->SetSystemApp(isSystemApp == "true" ? true : false); - - std::string isExpired; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::IS_EXPIRED, isExpired); - reminder->SetExpired(isExpired == "true" ? true : false); - - std::string actionButtons; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ACTION_BUTTON_INFO, actionButtons); - reminder->DeserializeButtonInfo(actionButtons); - - uint8_t state = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::STATE, state); - reminder->SetState(state); - - uint8_t repeatDaysOfWeek = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - reminder->SetRepeatDaysOfWeek(repeatDaysOfWeek); - - std::string wantAgent; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::AGENT, wantAgent); - reminder->SetWantAgentStr(wantAgent); - - std::string maxScreenWantAgent; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::MAX_SCREEN_AGENT, maxScreenWantAgent); - reminder->SetMaxWantAgentStr(maxScreenWantAgent); - - std::string tapDismissed; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::TAP_DISMISSED, tapDismissed); - reminder->SetTapDismissed(tapDismissed == "true" ? true : false); -} - -void ReminderStrategy::RecoverTimeFromDb(sptr& reminder, - const std::shared_ptr& resultSet) -{ - uint64_t reminderTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TIME, reminderTime); - reminder->SetReminderTimeInMilli(reminderTime); - - uint64_t triggerTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TRIGGER_TIME, triggerTime); - reminder->SetTriggerTimeInMilli(triggerTime); - - uint64_t timeInterval = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TIME_INTERVAL, timeInterval); - reminder->SetTimeInterval(timeInterval); - - uint8_t snoozeTimes = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_TIMES, snoozeTimes); - reminder->SetSnoozeTimes(snoozeTimes); - - uint8_t dynamicSnoozeTimes = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::DYNAMIC_SNOOZE_TIMES, dynamicSnoozeTimes); - reminder->SetSnoozeTimesDynamic(dynamicSnoozeTimes); - - uint64_t ringDuration = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::RING_DURATION, ringDuration); - reminder->SetRingDuration(ringDuration); - - int64_t autoDeletedTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::AUTO_DELETED_TIME, autoDeletedTime); - reminder->SetAutoDeletedTime(autoDeletedTime); -} - -void ReminderStrategy::RecoverIdFromDb(sptr& reminder, - const std::shared_ptr& resultSet) -{ - int32_t reminderId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_ID, reminderId); - reminder->SetReminderId(reminderId); - - int32_t userId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::USER_ID, userId); - reminder->InitUserId(userId); - - int32_t uid = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::UID, uid); - reminder->InitUid(uid); - - int32_t reminderType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::REMINDER_TYPE, reminderType); - reminder->SetReminderType(ReminderRequest::ReminderType(reminderType)); - - int32_t slotType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SLOT_ID, slotType); - reminder->SetSlotType(NotificationConstant::SlotType(slotType)); - - int32_t snoozeSlotType = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_SLOT_ID, snoozeSlotType); - reminder->SetSnoozeSlotType(NotificationConstant::SlotType(snoozeSlotType)); - - int32_t notificationId = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::NOTIFICATION_ID, notificationId); - reminder->SetNotificationId(notificationId); - - std::string groupId; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::GROUP_ID, groupId); - reminder->SetGroupId(groupId); - - int32_t creatorUid; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_UID, creatorUid); - reminder->InitCreatorUid(creatorUid); -} - -void ReminderStrategy::RecoverContextFromDb(sptr& reminder, - const std::shared_ptr& resultSet) -{ - std::string bundleName; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::PACKAGE_NAME, bundleName); - reminder->InitBundleName(bundleName); - - std::string customButtonUri; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_BUTTON_URI, customButtonUri); - reminder->SetCustomButtonUri(customButtonUri); - - std::string title; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TITLE, title); - reminder->SetTitle(title); - - std::string content; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CONTENT, content); - reminder->SetContent(content); - - std::string snoozeContent; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SNOOZE_CONTENT, snoozeContent); - reminder->SetSnoozeContent(snoozeContent); - - std::string expiredContent; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::EXPIRED_CONTENT, expiredContent); - reminder->SetExpiredContent(expiredContent); - - std::string customRingUri; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CUSTOM_RING_URI, customRingUri); - reminder->SetCustomRingUri(customRingUri); - - std::string creatorBundleName; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::CREATOR_BUNDLE_NAME, creatorBundleName); - reminder->InitCreatorBundleName(creatorBundleName); -} - -void ReminderStrategy::RecoverFromDb(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (reminder == nullptr || resultSet == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverTimeFromDb(reminder, resultSet); - ReminderStrategy::RecoverIdFromDb(reminder, resultSet); - ReminderStrategy::RecoverContextFromDb(reminder, resultSet); - - uint8_t state = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::STATE, state); - reminder->SetState(state); - - std::string isSystemApp; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::SYSTEM_APP, isSystemApp); - reminder->SetSystemApp(isSystemApp == "true" ? true : false); - - std::string isExpired; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::IS_EXPIRED, isExpired); - reminder->SetExpired(isExpired == "true" ? true : false); - - std::string actionButtons; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); - reminder->DeserializeButtonInfo(actionButtons); - - reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent - std::string wantAgent; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); - reminder->DeserializeWantAgent(wantAgent, 0); - - std::string maxWantAgent; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::MAX_SCREEN_WANT_AGENT, maxWantAgent); - reminder->DeserializeWantAgent(maxWantAgent, 1); - - std::string tapDismissed; - ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::TAP_DISMISSED, tapDismissed); - reminder->SetTapDismissed(tapDismissed == "true" ? true : false); -} - -void ReminderTimerStrategy::AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values) -{ - uint64_t seconds = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { - ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); - seconds = timer->GetInitInfo(); - } - values.PutInt(ReminderTimerTable::REMINDER_ID, reminder->GetReminderId()); - values.PutLong(ReminderTimerTable::TRIGGER_SECOND, seconds); - values.PutLong(ReminderTimerTable::START_DATE_TIME, 0); - values.PutLong(ReminderTimerTable::END_DATE_TIME, 0); -} - -void ReminderTimerStrategy::RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); -} - -void ReminderTimerStrategy::RecoverFromDb(sptr& reminder, - const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromDb(reminder, baseResult); - if (reminder->GetReminderType() == ReminderRequest::ReminderType::TIMER) { - ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); - uint64_t seconds; - ReminderStrategy::GetRdbValue(resultSet, ReminderTimerTable::TRIGGER_SECOND, seconds); - timer->SetInitInfo(seconds); - } -} - -void ReminderAlarmStrategy::AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values) -{ - uint8_t hour = 0; - uint8_t minute = 0; - uint8_t repeatDaysOfWeek = 0; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { - ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); - hour = alarm->GetHour(); - minute = alarm->GetMinute(); - repeatDaysOfWeek = alarm->GetRepeatDaysOfWeek(); - } - values.PutInt(ReminderAlarmTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderAlarmTable::ALARM_HOUR, hour); - values.PutInt(ReminderAlarmTable::ALARM_MINUTE, minute); - values.PutInt(ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); -} - -void ReminderAlarmStrategy::RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); - - if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { - ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); - uint8_t hour = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_HOUR, hour); - alarm->SetHour(hour); - - uint8_t minute = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::ALARM_MINUTE, minute); - alarm->SetMinute(minute); - } -} - -void ReminderAlarmStrategy::RecoverFromDb(sptr& reminder, - const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromDb(reminder, baseResult); - if (reminder->GetReminderType() == ReminderRequest::ReminderType::ALARM) { - ReminderRequestAlarm* alarm = static_cast(reminder.GetRefPtr()); - uint8_t hour = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_HOUR, hour); - alarm->SetHour(hour); - - uint8_t minute = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::ALARM_MINUTE, minute); - alarm->SetMinute(minute); - - uint8_t repeatDaysOfWeek = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderAlarmTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - alarm->SetRepeatDaysOfWeek(repeatDaysOfWeek); - } -} - -void ReminderCalendarStrategy::AppendValuesBucket(const sptr& reminder, - NativeRdb::ValuesBucket& values) -{ - uint16_t firstDesignateYear = 0; - uint8_t firstDesignateMonth = 0; - uint8_t firstDesignateDay = 0; - uint64_t dateTime = 0; - uint32_t repeatDay = 0; - uint16_t repeatMonth = 0; - uint8_t repeatDaysOfWeek = 0; - uint64_t endDateTime = 0; - uint64_t lastStartDateTime = 0; - std::string rruleWantAgent; - std::string excludeDates; - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - if (calendar != nullptr) { - repeatDay = calendar->GetRepeatDay(); - repeatMonth = calendar->GetRepeatMonth(); - firstDesignateYear = calendar->GetFirstDesignateYear(); - firstDesignateMonth = calendar->GetFirstDesignageMonth(); - firstDesignateDay = calendar->GetFirstDesignateDay(); - dateTime = calendar->GetDateTime(); - repeatDaysOfWeek = calendar->GetRepeatDaysOfWeek(); - endDateTime = calendar->GetEndDateTime(); - lastStartDateTime = calendar->GetLastStartDateTime(); - rruleWantAgent = calendar->SerializationRRule(); - excludeDates = calendar->SerializationExcludeDates(); - } - } - values.PutInt(ReminderCalendarTable::REMINDER_ID, reminder->GetReminderId()); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); - values.PutInt(ReminderCalendarTable::FIRST_DESIGNATE_DAY, firstDesignateDay); - values.PutLong(ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - values.PutLong(ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, lastStartDateTime); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS, repeatDay); - values.PutInt(ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); - values.PutInt(ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - values.PutString(ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - values.PutString(ReminderCalendarTable::EXCLUDE_DATES, excludeDates); -} - -void ReminderCalendarStrategy::RecoverFromOldVersion(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromOldVersion(reminder, resultSet); - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - uint32_t repeatDay = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_DAYS, repeatDay); - calendar->SetRepeatDay(repeatDay); - - uint16_t repeatMonth = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::REPEAT_MONTHS, repeatMonth); - calendar->SetRepeatMonth(repeatMonth); - - uint16_t firstDesignateYear = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_YEAR, firstDesignateYear); - calendar->SetFirstDesignateYear(firstDesignateYear); - - uint8_t firstDesignateMonth = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_MONTH, firstDesignateMonth); - calendar->SetFirstDesignageMonth(firstDesignateMonth); - - uint8_t firstDesignateDay = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::FIRST_DESIGNATE_DAY, firstDesignateDay); - calendar->SetFirstDesignateDay(firstDesignateDay); - - uint16_t year = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_YEAR, year); - calendar->SetYear(year); - - uint8_t month = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MONTH, month); - calendar->SetMonth(month); - - uint8_t day = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_DAY, day); - calendar->SetDay(day); - - uint8_t hour = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_HOUR, hour); - calendar->SetHour(hour); - - uint8_t minute = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderTable::CALENDAR_MINUTE, minute); - calendar->SetMinute(minute); - } -} - -void ReminderCalendarStrategy::RecoverTime(sptr& reminder, - const std::shared_ptr& resultSet) -{ - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - - uint16_t firstDesignateYear = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_YEAR, - firstDesignateYear); - calendar->SetFirstDesignateYear(firstDesignateYear); - - uint8_t firstDesignateMonth = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_MONTH, - firstDesignateMonth); - calendar->SetFirstDesignageMonth(firstDesignateMonth); - - uint8_t firstDesignateDay = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::FIRST_DESIGNATE_DAY, - firstDesignateDay); - calendar->SetFirstDesignateDay(firstDesignateDay); - - uint64_t dateTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_DATE_TIME, dateTime); - calendar->SetDateTime(dateTime); - - uint64_t endDateTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_END_DATE_TIME, endDateTime); - if (endDateTime != 0 && endDateTime >= dateTime) { - calendar->SetEndDateTime(endDateTime); - } else { - calendar->SetEndDateTime(dateTime); - } - - uint64_t lastStartDateTime = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::CALENDAR_LAST_DATE_TIME, - lastStartDateTime); - if (lastStartDateTime == 0) { - calendar->SetLastStartDateTime(dateTime); - } else { - calendar->SetLastStartDateTime(lastStartDateTime); - } - } -} - -void ReminderCalendarStrategy::RecoverFromDb(sptr& reminder, - const std::shared_ptr& baseResult, const std::shared_ptr& resultSet) -{ - if (resultSet == nullptr || reminder == nullptr || baseResult == nullptr) { - ANSR_LOGE("ResultSet is null or reminder is null"); - return; - } - ReminderStrategy::RecoverFromDb(reminder, baseResult); - ReminderCalendarStrategy::RecoverTime(reminder, resultSet); - if (reminder != nullptr && reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { - ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); - - uint32_t repeatDay = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS, repeatDay); - calendar->SetRepeatDay(repeatDay); - - uint16_t repeatMonth = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_MONTHS, repeatMonth); - calendar->SetRepeatMonth(repeatMonth); - - uint8_t repeatDaysOfWeek = 0; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::REPEAT_DAYS_OF_WEEK, repeatDaysOfWeek); - calendar->SetRepeatDaysOfWeek(repeatDaysOfWeek); - - std::string rruleWantAgent; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::RRULE_WANT_AGENT, rruleWantAgent); - calendar->DeserializationRRule(rruleWantAgent); - - std::string excludeDates; - ReminderStrategy::GetRdbValue(resultSet, ReminderCalendarTable::EXCLUDE_DATES, excludeDates); - calendar->DeserializationExcludeDates(excludeDates); - } -} -} -} \ No newline at end of file -- Gitee From b90b3c5e5c4c6165c1e0748b111d7931d9326024 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 18 Nov 2024 14:39:31 +0800 Subject: [PATCH 07/29] push Signed-off-by: fengyang --- services/ans/include/reminder_table.h | 272 ---------------------- services/ans/include/reminder_table_old.h | 239 ------------------- 2 files changed, 511 deletions(-) delete mode 100644 services/ans/include/reminder_table.h delete mode 100644 services/ans/include/reminder_table_old.h diff --git a/services/ans/include/reminder_table.h b/services/ans/include/reminder_table.h deleted file mode 100644 index 364adde4f..000000000 --- a/services/ans/include/reminder_table.h +++ /dev/null @@ -1,272 +0,0 @@ -// /* -// * Copyright (c) 2023 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H - -// #include -// #include - -// namespace OHOS { -// namespace Notification { -// class ReminderBaseTable { -// public: -// /* -// * reminder base table name -// */ -// static const std::string TABLE_NAME; - -// /* -// * reminder id -// */ -// static const std::string REMINDER_ID; - -// /* -// * package name -// */ -// static const std::string PACKAGE_NAME; - -// /* -// * user id -// */ -// static const std::string USER_ID; - -// /* -// * uid -// */ -// static const std::string UID; - -// /* -// * systerm app flag -// */ -// static const std::string SYSTEM_APP; - -// /* -// * reminder type: Timer/Calendar/Alarm -// */ -// static const std::string REMINDER_TYPE; - -// /* -// * reminder time -// */ -// static const std::string REMINDER_TIME; - -// /* -// * trigger time -// */ -// static const std::string TRIGGER_TIME; - -// /* -// * time interval -// */ -// static const std::string TIME_INTERVAL; - -// /* -// * snooze times -// */ -// static const std::string SNOOZE_TIMES; - -// /* -// * dynamic snooze times -// */ -// static const std::string DYNAMIC_SNOOZE_TIMES; - -// /* -// * ring duration -// */ -// static const std::string RING_DURATION; - -// /* -// * expired flag -// */ -// static const std::string IS_EXPIRED; - -// /* -// * reminder state -// */ -// static const std::string STATE; - -// /* -// * action button information -// */ -// static const std::string ACTION_BUTTON_INFO; - -// /* -// * custom button uri -// */ -// static const std::string CUSTOM_BUTTON_URI; - -// /* -// * slot type -// */ -// static const std::string SLOT_ID; - -// /* -// * snoozeslot type -// */ -// static const std::string SNOOZE_SLOT_ID; - -// /* -// * notification id -// */ -// static const std::string NOTIFICATION_ID; - -// /* -// * notification title -// */ -// static const std::string TITLE; - -// /* -// * notification content -// */ -// static const std::string CONTENT; - -// /* -// * notification snooze content -// */ -// static const std::string SNOOZE_CONTENT; - -// /* -// * notification expired content -// */ -// static const std::string EXPIRED_CONTENT; - -// /* -// * want agent information -// */ -// static const std::string WANT_AGENT; - -// /* -// * max screen want agent information -// */ -// static const std::string MAX_SCREEN_WANT_AGENT; - -// /* -// * tap dismissed flag -// */ -// static const std::string TAP_DISMISSED; - -// /* -// * auto deleted time -// */ -// static const std::string AUTO_DELETED_TIME; - -// /* -// * group id -// */ -// static const std::string GROUP_ID; - -// /* -// * custom ring uri -// */ -// static const std::string CUSTOM_RING_URI; - -// /* -// * creator bundle name -// */ -// static const std::string CREATOR_BUNDLE_NAME; - -// /* -// * creator uid -// */ -// static const std::string CREATOR_UID; - -// public: -// static void InitDbColumns(); - -// public: -// static std::string ADD_COLUMNS; -// static std::string SELECT_COLUMNS; -// }; - -// class ReminderAlarmTable { -// public: -// /* -// * reminder alarm table name -// */ -// static const std::string TABLE_NAME; - -// /* -// * reminder timer table field -// */ -// static const std::string REMINDER_ID; -// static const std::string ALARM_HOUR; -// static const std::string ALARM_MINUTE; -// static const std::string REPEAT_DAYS_OF_WEEK; - -// public: -// static void InitDbColumns(); - -// public: -// static std::string ADD_COLUMNS; -// static std::string SELECT_COLUMNS; -// }; - -// class ReminderCalendarTable { -// public: -// /* -// * reminder calendar table name -// */ -// static const std::string TABLE_NAME; - -// /* -// * reminder calendar table field -// */ -// static const std::string REMINDER_ID; -// static const std::string FIRST_DESIGNATE_YEAR; -// static const std::string FIRST_DESIGNATE_MONTH; -// static const std::string FIRST_DESIGNATE_DAY; -// static const std::string CALENDAR_DATE_TIME; -// static const std::string CALENDAR_END_DATE_TIME; -// static const std::string REPEAT_DAYS; -// static const std::string REPEAT_MONTHS; -// static const std::string REPEAT_DAYS_OF_WEEK; -// static const std::string RRULE_WANT_AGENT; -// static const std::string EXCLUDE_DATES; -// static const std::string CALENDAR_LAST_DATE_TIME; - -// public: -// static void InitDbColumns(); - -// public: -// static std::string ADD_COLUMNS; -// static std::string SELECT_COLUMNS; -// }; - -// class ReminderTimerTable { -// public: -// /* -// * reminder timer table name -// */ -// static const std::string TABLE_NAME; - -// /* -// * reminder timer table field -// */ -// static const std::string REMINDER_ID; -// static const std::string TRIGGER_SECOND; -// static const std::string START_DATE_TIME; -// static const std::string END_DATE_TIME; - -// public: -// static void InitDbColumns(); - -// public: -// static std::string ADD_COLUMNS; -// static std::string SELECT_COLUMNS; -// }; -// } // namespace Notification -// } // namespace OHOS -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H diff --git a/services/ans/include/reminder_table_old.h b/services/ans/include/reminder_table_old.h deleted file mode 100644 index 3ab69aea2..000000000 --- a/services/ans/include/reminder_table_old.h +++ /dev/null @@ -1,239 +0,0 @@ -// /* -// * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H - -// #include -// #include - -// namespace OHOS { -// namespace Notification { -// class ReminderTable { -// public: -// static void InitDbColumns(); - -// static const std::string TABLE_NAME; - -// // Reminder Table Basic Columns. - -// /* -// * reminder id -// */ -// static const std::string REMINDER_ID; - -// /* -// * package name -// */ -// static const std::string PKG_NAME; - -// /* -// * user id -// */ -// static const std::string USER_ID; - -// /* -// * uid -// */ -// static const std::string UID; - -// /* -// * systerm app flag -// */ -// static const std::string SYS_APP; - -// /* -// * app label -// */ -// static const std::string APP_LABEL; - -// /* -// * reminder type: Timer/Calendar/Alarm -// */ -// static const std::string REMINDER_TYPE; - -// /* -// * reminder time -// */ -// static const std::string REMINDER_TIME; - -// /* -// * trigger time -// */ -// static const std::string TRIGGER_TIME; - -// /* -// * RTC trigger time -// */ -// static const std::string RTC_TRIGGER_TIME; - -// /* -// * time interval -// */ -// static const std::string TIME_INTERVAL; - -// /* -// * snooze times -// */ -// static const std::string SNOOZE_TIMES; - -// /* -// * dynamic snooze times -// */ -// static const std::string DYNAMIC_SNOOZE_TIMES; - -// /* -// * ring duration -// */ -// static const std::string RING_DURATION; - -// /* -// * expired flag -// */ -// static const std::string IS_EXPIRED; - -// /* -// * active flag -// */ -// static const std::string IS_ACTIVE; - -// /* -// * reminder state -// */ -// static const std::string STATE; - -// /* -// * zone id -// */ -// static const std::string ZONE_ID; - -// /* -// * scheduled timeout flag -// */ -// static const std::string HAS_SCHEDULED_TIMEOUT; - -// /* -// * action button information -// */ -// static const std::string ACTION_BUTTON_INFO; - -// /* -// * custom button uri -// */ -// static const std::string CUSTOM_BUTTON_URI; - -// /* -// * slot type -// */ -// static const std::string SLOT_ID; - -// /* -// * snoozeslot type -// */ -// static const std::string SNOOZE_SLOT_ID; - -// /* -// * notification id -// */ -// static const std::string NOTIFICATION_ID; - -// /* -// * notification title -// */ -// static const std::string TITLE; - -// /* -// * notification content -// */ -// static const std::string CONTENT; - -// /* -// * notification snooze content -// */ -// static const std::string SNOOZE_CONTENT; - -// /* -// * notification expired content -// */ -// static const std::string EXPIRED_CONTENT; - -// /* -// * agent information -// */ -// static const std::string AGENT; - -// /* -// * max screen agent information -// */ -// static const std::string MAX_SCREEN_AGENT; - -// /* -// * tap dismissed flag -// */ -// static const std::string TAP_DISMISSED; - -// /* -// * auto deleted time -// */ -// static const std::string AUTO_DELETED_TIME; - -// /* -// * repeat days of week -// */ -// static const std::string REPEAT_DAYS_OF_WEEK; - -// /* -// * reminder group id -// */ -// static const std::string GROUP_ID; - -// /* -// * reminder ring uri -// */ -// static const std::string CUSTOM_RING_URI; - -// /* -// * reminder creator bundle name -// */ -// static const std::string CREATOR_BUNDLE_NAME; - -// // Reminder Table Calendar Columns. -// static const std::string REPEAT_DAYS; -// static const std::string REPEAT_MONTHS; -// static const std::string FIRST_DESIGNATE_YEAR; -// static const std::string FIRST_DESIGNATE_MONTH; -// static const std::string FIRST_DESIGNATE_DAY; -// static const std::string CALENDAR_YEAR; -// static const std::string CALENDAR_MONTH; -// static const std::string CALENDAR_DAY; -// static const std::string CALENDAR_HOUR; -// static const std::string CALENDAR_MINUTE; - -// // Reminder Table Alarm Columns. -// static const std::string ALARM_HOUR; -// static const std::string ALARM_MINUTE; - -// static std::string ADD_COLUMNS; -// static std::string SELECT_COLUMNS; - -// private: -// static void InitBasicColumns(); -// static void InitCalendarColumns(); -// static void InitAlarmColumns(); -// static void AddColumn(const std::string& name, const std::string& type, bool isEnd = false); -// }; -// } // namespace Notification -// } // namespace OHOS -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H -- Gitee From b7846c7f49b1198c8d26db658856e69cc7514f19 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 18 Nov 2024 14:56:49 +0800 Subject: [PATCH 08/29] push Signed-off-by: fengyang --- frameworks/reminder/BUILD.gn | 2 +- services/reminder/BUILD.gn | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index f33735e04..055727821 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -13,7 +13,7 @@ import("//build/ohos.gni") import("//base/notification/distributed_notification_service/notification.gni") -import("//foundation/ability/idl_tool/idl_config.gni") +import("//build/config/components/idl_tool/idl.gni") group("reminder_client") { deps = [ ":reminder_innerkits" ] diff --git a/services/reminder/BUILD.gn b/services/reminder/BUILD.gn index ba726c81f..7074a6bbb 100644 --- a/services/reminder/BUILD.gn +++ b/services/reminder/BUILD.gn @@ -207,8 +207,6 @@ ohos_shared_library("libreminder") { deps = [ "${services_path}/reminder:reminder_service_sources", - "//third_party/icu/icu4c:shared_icuuc", - "//third_party/libxml2:libxml2", ] if (distributed_notification_supported) { -- Gitee From 0809f553b6336bae8d99f59dcf05699482366874 Mon Sep 17 00:00:00 2001 From: fengyang Date: Tue, 19 Nov 2024 14:37:40 +0800 Subject: [PATCH 09/29] push Signed-off-by: fengyang --- bundle.json | 1 + .../reminder/src/reminder_request_client.cpp | 8 +- .../inner_api}/reminder_request_client.h | 0 .../include/reminder_service_ability.h | 120 ++++++----- services/reminder/sa_profile/1930.json | 13 ++ services/reminder/sa_profile/BUILD.gn | 19 ++ .../reminder/src/reminder_service_ability.cpp | 192 +++++------------- 7 files changed, 151 insertions(+), 202 deletions(-) rename {frameworks/reminder/src => interfaces/inner_api}/reminder_request_client.h (100%) create mode 100644 services/reminder/sa_profile/1930.json create mode 100644 services/reminder/sa_profile/BUILD.gn diff --git a/bundle.json b/bundle.json index b896cc607..1aa4d63dc 100644 --- a/bundle.json +++ b/bundle.json @@ -112,6 +112,7 @@ "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", "//base/notification/distributed_notification_service/services:ans_service", + "//base/notification/distributed_notification_service/services/reminder/sa_profile:reminder_service", "//base/notification/distributed_notification_service/services/reminder:reminder_service", "//base/notification/distributed_notification_service/tools:tools_shell" ] diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index 9fbf265ae..dcf691e23 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -184,15 +184,13 @@ sptr ReminderRequestClient::GetAnsManagerProxy() sptr ReminderRequestClient::GetReminderManagerProxy() { - sptr systemAbilityManager = - SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!systemAbilityManager) { + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (!samgr) { ANS_LOGE("Failed to get system ability mgr."); return nullptr; } - sptr remoteObject = - systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + sptr remoteObject = samgr->GetSystemAbility(1930); if (!remoteObject) { ANS_LOGE("Failed to get notification Manager."); return nullptr; diff --git a/frameworks/reminder/src/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h similarity index 100% rename from frameworks/reminder/src/reminder_request_client.h rename to interfaces/inner_api/reminder_request_client.h diff --git a/services/reminder/include/reminder_service_ability.h b/services/reminder/include/reminder_service_ability.h index 9734960da..2582e4983 100644 --- a/services/reminder/include/reminder_service_ability.h +++ b/services/reminder/include/reminder_service_ability.h @@ -1,61 +1,59 @@ -// /* -// * 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H - -// #include "system_ability.h" - -// #include "reminder_service.h" -// #include "reminder_data_manager.h" -// #include "system_ability_definition.h" -// // #include "notification_extension_wrapper.h" - -// namespace OHOS { -// namespace Notification { -// class ReminderServiceAbility final : public SystemAbility { -// public: -// /** -// * @brief The constructor of service ability. -// * -// * @param systemAbilityId Indicates the system ability id. -// * @param runOnCreate Run the system ability on created. -// */ -// ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate); - -// /** -// * @brief The deconstructor. -// */ -// ~ReminderServiceAbility() final; - -// DISALLOW_COPY_AND_MOVE(ReminderServiceAbility); -// DECLARE_SYSTEM_ABILITY(ReminderServiceAbility); - -// private: -// void OnStart() final; -// void OnStop() final; -// void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; -// void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; -// // void OnReceiveEvent(const EventFwk::CommonEventData &data); -// int32_t OnExtension(const std::string& extension, MessageParcel& data, MessageParcel& reply) override; - -// private: -// sptr service_; -// std::shared_ptr reminderAgent_; -// }; -// } // namespace Notification -// } // namespace OHOS - -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H +/* + * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H + +#include "system_ability.h" + +#include "reminder_service.h" +#include "reminder_data_manager.h" +#include "system_ability_definition.h" +// #include "notification_extension_wrapper.h" + +namespace OHOS { +namespace Notification { +class ReminderServiceAbility final : public SystemAbility { +public: + /** + * @brief The constructor of service ability. + * + * @param systemAbilityId Indicates the system ability id. + * @param runOnCreate Run the system ability on created. + */ + ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate); + + /** + * @brief The deconstructor. + */ + ~ReminderServiceAbility() final; + + DISALLOW_COPY_AND_MOVE(ReminderServiceAbility); + DECLARE_SYSTEM_ABILITY(ReminderServiceAbility); + +private: + void OnStart() final; + void OnStop() final; + // void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + // void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; + +private: + sptr service_; + std::shared_ptr reminderAgent_; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H diff --git a/services/reminder/sa_profile/1930.json b/services/reminder/sa_profile/1930.json new file mode 100644 index 000000000..289b0e338 --- /dev/null +++ b/services/reminder/sa_profile/1930.json @@ -0,0 +1,13 @@ +{ + "process": "foundation", + "systemability": [ + { + "name": 1930, + "libpath": "libreminder.z.so", + "run-on-create": true, + "depend_time_out": 60000, + "distributed": false, + "dump_level": 1 + } + ] +} diff --git a/services/reminder/sa_profile/BUILD.gn b/services/reminder/sa_profile/BUILD.gn new file mode 100644 index 000000000..bd8f445ce --- /dev/null +++ b/services/reminder/sa_profile/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. +import("//build/ohos/sa_profile/sa_profile.gni") + +ohos_sa_profile("reminder_sa_profile") { + sources = [ "1930.json" ] + + part_name = "distributed_notification_service" +} diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp index a91662f04..51c14c125 100644 --- a/services/reminder/src/reminder_service_ability.cpp +++ b/services/reminder/src/reminder_service_ability.cpp @@ -1,136 +1,56 @@ -// /* -// * 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 "reminder_service_ability.h" -// // #include "system_event_observer.h" -// // #include "common_event_manager.h" - -// namespace OHOS { -// namespace Notification { -// namespace { -// REGISTER_SYSTEM_ABILITY_BY_ID(ReminderServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); -// } - -// const std::string EXTENSION_BACKUP = "backup"; -// const std::string EXTENSION_RESTORE = "restore"; - -// ReminderServiceAbility::ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate) -// : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) -// {} - -// ReminderServiceAbility::~ReminderServiceAbility() -// {} - -// void ReminderServiceAbility::OnStart() -// { -// if (service_ != nullptr) { -// return; -// } - -// service_ = ReminderService::GetInstance(); -// if (!Publish(service_)) { -// return; -// } -// // service_->CreateDialogManager(); -// // service_->InitPublishProcess(); -// reminderAgent_ = ReminderDataManager::InitInstance(service_); - -// // #ifdef ENABLE_ANS_EXT_WRAPPER -// // EXTENTION_WRAPPER->InitExtentionWrapper(); -// // AddSystemAbilityListener(DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID); -// // AddSystemAbilityListener(COMMON_EVENT_SERVICE_ID); -// // #else -// ANS_LOGI("Not enabled ans_ext"); -// #endif - -// // #ifdef ENABLE_ANS_TELEPHONY_CUST_WRAPPER -// // TEL_EXTENTION_WRAPPER->InitTelExtentionWrapper(); -// // #endif -// } - -// void ReminderServiceAbility::OnStop() -// { -// service_ = nullptr; -// reminderAgent_ = nullptr; -// } - -// void ReminderServiceAbility::OnAddSystemAbility(int32_t systemAbilityId, const std::string &deviceId) -// { -// ANS_LOGD("SubSystemAbilityListener::OnAddSystemAbility enter !"); -// if (systemAbilityId == DISTRIBUTED_KV_DATA_SERVICE_ABILITY_ID) { -// if (AdvancedDatashareObserver::GetInstance().CheckIfSettingsDataReady()) { -// if (isDatashaReready_) { -// return; -// } -// EXTENTION_WRAPPER->CheckIfSetlocalSwitch(); -// isDatashaReready_ = true; -// } -// } else if (systemAbilityId == COMMON_EVENT_SERVICE_ID) { -// if (isDatashaReready_) { -// return; -// } -// EventFwk::MatchingSkills matchingSkills; -// matchingSkills.AddEvent("usual.event.DATA_SHARE_READY"); -// EventFwk::CommonEventSubscribeInfo subscribeInfo(matchingSkills); -// subscriber_ = std::make_shared( -// subscribeInfo, std::bind(&ReminderServiceAbility::OnReceiveEvent, this, std::placeholders::_1)); -// if (subscriber_ == nullptr) { -// ANS_LOGD("subscriber_ is nullptr"); -// return; -// } -// EventFwk::CommonEventManager::SubscribeCommonEvent(subscriber_); -// } -// } - -// // void ReminderServiceAbility::OnReceiveEvent(const EventFwk::CommonEventData &data) -// // { -// // ANS_LOGI("CheckIfSettingsDataReady() ok!"); -// // if (isDatashaReready_) { -// // return; -// // } -// // auto const &want = data.GetWant(); -// // std::string action = want.GetAction(); -// // if (action == "usual.event.DATA_SHARE_READY") { -// // isDatashaReready_ = true; -// // ANS_LOGI("COMMON_EVENT_SERVICE_ID OnReceiveEvent ok!"); -// // EXTENTION_WRAPPER->CheckIfSetlocalSwitch(); -// // } -// // } - -// void ReminderServiceAbility::OnRemoveSystemAbility(int32_t systemAbilityId, const std::string &deviceId) -// { -// if (systemAbilityId != COMMON_EVENT_SERVICE_ID) { -// return; -// } -// } - -// int32_t ReminderServiceAbility::OnExtension(const std::string& extension, -// MessageParcel& data, MessageParcel& reply) -// { -// ANS_LOGI("extension is %{public}s.", extension.c_str()); -// auto notificationService = ReminderService::GetInstance(); -// if (notificationService == nullptr) { -// ANS_LOGW("notification service is not initial."); -// return ERR_OK; -// } -// if (extension == EXTENSION_BACKUP) { -// return notificationService->OnBackup(data, reply); -// } else if (extension == EXTENSION_RESTORE) { -// return notificationService->OnRestore(data, reply); -// } -// return ERR_OK; -// } -// } // namespace Notification -// } // namespace OHOS +/* + * 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 "reminder_service_ability.h" +// #include "system_event_observer.h" +// #include "common_event_manager.h" + +namespace OHOS { +namespace Notification { +namespace { +REGISTER_SYSTEM_ABILITY_BY_ID(ReminderServiceAbility, 1930, true); +} + +const std::string EXTENSION_BACKUP = "backup"; +const std::string EXTENSION_RESTORE = "restore"; + +ReminderServiceAbility::ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate) + : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) +{} + +ReminderServiceAbility::~ReminderServiceAbility() +{} + +void ReminderServiceAbility::OnStart() +{ + if (service_ != nullptr) { + return; + } + + service_ = ReminderService::GetInstance(); + if (!Publish(service_)) { + return; + } + reminderAgent_ = ReminderDataManager::InitInstance(service_); +} + +void ReminderServiceAbility::OnStop() +{ + service_ = nullptr; + reminderAgent_ = nullptr; +} + +} // namespace Notification +} // namespace OHOS -- Gitee From 23bfca32c73a3b952496fec621a071fc201a6bbf Mon Sep 17 00:00:00 2001 From: fengyang Date: Tue, 19 Nov 2024 16:05:21 +0800 Subject: [PATCH 10/29] push Signed-off-by: fengyang --- bundle.json | 2 +- services/reminder/include/reminder_service.h | 16 +--- .../reminder_os_account_manager_helper.cpp | 4 + services/reminder/src/reminder_service.cpp | 88 ++++--------------- .../reminder/src/reminder_service_ability.cpp | 2 +- 5 files changed, 26 insertions(+), 86 deletions(-) diff --git a/bundle.json b/bundle.json index 1aa4d63dc..9dfbd5f73 100644 --- a/bundle.json +++ b/bundle.json @@ -112,7 +112,7 @@ "service_group": [ "//base/notification/distributed_notification_service/sa_profile:ans_sa_profile", "//base/notification/distributed_notification_service/services:ans_service", - "//base/notification/distributed_notification_service/services/reminder/sa_profile:reminder_service", + "//base/notification/distributed_notification_service/services/reminder/sa_profile:reminder_sa_profile", "//base/notification/distributed_notification_service/services/reminder:reminder_service", "//base/notification/distributed_notification_service/tools:tools_shell" ] diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h index 5a733ce44..496d97512 100644 --- a/services/reminder/include/reminder_service.h +++ b/services/reminder/include/reminder_service.h @@ -55,19 +55,8 @@ static const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 class ReminderService final : public ReminderManagerStub, public std::enable_shared_from_this { public: - // struct NotificationRequestDb { - // sptr request {nullptr}; - // sptr bundleOption {nullptr}; - // }; - // struct RecentNotification { - // sptr notification = nullptr; - // bool isActive = false; - // int32_t deleteReason = 0; - // int64_t deleteTime = 0; - // }; - - ~ReminderService() override; + ~ReminderService() override = default; DISALLOW_COPY_AND_MOVE(ReminderService); @@ -140,9 +129,10 @@ public: */ ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; private: - ReminderService(); + ReminderService() = default; private: static sptr instance_; + static std::mutex instanceMutex_; }; } // namespace Notification } // namespace OHOS diff --git a/services/reminder/src/reminder_os_account_manager_helper.cpp b/services/reminder/src/reminder_os_account_manager_helper.cpp index a7a46f38e..87646810e 100644 --- a/services/reminder/src/reminder_os_account_manager_helper.cpp +++ b/services/reminder/src/reminder_os_account_manager_helper.cpp @@ -26,6 +26,10 @@ namespace OHOS { namespace Notification { +ReminderOsAccountManagerHelper &ReminderOsAccountManagerHelper::GetInstance() +{ + return DelayedRefSingleton::GetInstance(); +} ErrCode ReminderOsAccountManagerHelper::GetOsAccountLocalIdFromUid(const int32_t uid, int32_t &userId) { int32_t ret = AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index d37c81378..51f8cddaf 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -46,6 +46,23 @@ namespace OHOS { namespace Notification { +sptr ReminderService::instance_; +std::mutex ReminderService::instanceMutex_; +sptr ReminderService::GetInstance() +{ + std::lock_guard lock(instanceMutex_); + + if (instance_ == nullptr) { + instance_ = new (std::nothrow) ReminderService(); + if (instance_ == nullptr) { + ANS_LOGE("Failed to create AdvancedNotificationService instance"); + return nullptr; + } + } + + return instance_; +} + inline bool ReminderService::CheckReminderPermission() { Security::AccessToken::AccessTokenID callerToken = IPCSkeleton::GetCallingTokenID(); @@ -250,76 +267,5 @@ ErrCode ReminderService::GetExcludeDates(const int32_t reminderId, std::vectorGetExcludeDates(reminderId, callingUid, dates); } - -// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -// NotificationConstant::RemindType ReminderService::GetRemindType() -// { -// bool remind = localScreenOn_; -// if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DEFAULT) { -// bool remoteUsing = false; -// ErrCode result = DistributedScreenStatusManager::GetInstance()->CheckRemoteDevicesIsUsing(remoteUsing); -// if (result != ERR_OK) { -// remind = true; -// } -// if (!localScreenOn_ && !remoteUsing) { -// remind = true; -// } -// } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::ALWAYS_REMIND) { -// remind = true; -// } else if (distributedReminderPolicy_ == NotificationConstant::DistributedReminderPolicy::DO_NOT_REMIND) { -// remind = false; -// } - -// if (localScreenOn_) { -// if (remind) { -// return NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; -// } else { -// return NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND; -// } -// } else { -// if (remind) { -// return NotificationConstant::RemindType::DEVICE_IDLE_REMIND; -// } else { -// return NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND; -// } -// } -// } -// #endif - -// ErrCode ReminderService::GetDeviceRemindType(NotificationConstant::RemindType &remindType) -// { -// ANS_LOGD("%{public}s", __FUNCTION__); - -// bool isSubsystem = ReminderAccessTokenHelper::VerifyNativeToken(IPCSkeleton::GetCallingTokenID()); -// if (!isSubsystem && !ReminderAccessTokenHelper::IsSystemApp()) { -// return ERR_ANS_NON_SYSTEM_APP; -// } - -// if (!ReminderAccessTokenHelper::CheckPermission(OHOS_PERMISSION_NOTIFICATION_CONTROLLER)) { -// return ERR_ANS_PERMISSION_DENIED; -// } - -// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -// if (notificationSvrQueue_ == nullptr) { -// ANS_LOGE("Serial queue is invalid."); -// return ERR_ANS_INVALID_PARAM; -// } -// ffrt::task_handle handler = notificationSvrQueue_->submit_h(std::bind([&]() { remindType = GetRemindType(); })); -// notificationSvrQueue_->wait(handler); -// return ERR_OK; -// #else -// return ERR_INVALID_OPERATION; -// #endif -// } - -// ErrCode ReminderService::SetNotificationRemindType(sptr notification, bool isLocal) -// { -// #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -// notification->SetRemindType(GetRemindType()); -// #else -// notification->SetRemindType(NotificationConstant::RemindType::NONE); -// #endif -// return ERR_OK; -// } } // namespace Notification } // namespace OHOS diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp index 51c14c125..89407e4a8 100644 --- a/services/reminder/src/reminder_service_ability.cpp +++ b/services/reminder/src/reminder_service_ability.cpp @@ -43,7 +43,7 @@ void ReminderServiceAbility::OnStart() if (!Publish(service_)) { return; } - reminderAgent_ = ReminderDataManager::InitInstance(service_); + reminderAgent_ = ReminderDataManager::InitInstance(); } void ReminderServiceAbility::OnStop() -- Gitee From 04cf6e7158d87287d3591764f626ed55520b5ce8 Mon Sep 17 00:00:00 2001 From: fengyang Date: Wed, 20 Nov 2024 09:34:23 +0800 Subject: [PATCH 11/29] push Signed-off-by: fengyang --- frameworks/reminder/BUILD.gn | 1 + frameworks/reminder/src/reminder_request.cpp | 29 +++++----- .../reminder/src/reminder_request_factory.cpp | 57 +++++++++++++++++++ .../inner_api/reminder_request_factory.h | 33 +++++++++++ .../include/reminder_service_ability.h | 2 - 5 files changed, 106 insertions(+), 16 deletions(-) create mode 100644 frameworks/reminder/src/reminder_request_factory.cpp create mode 100644 interfaces/inner_api/reminder_request_factory.h diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index 055727821..82581eb23 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -58,6 +58,7 @@ ohos_shared_library("reminder_innerkits") { public_configs = [ ":reminder_innerkits_public_config" ] output_values = get_target_outputs(":reminder_manager_interface") sources = [ + "${frameworks_module_reminder_path}/src/reminder_request_factory.cpp", "${frameworks_module_reminder_path}/src/reminder_request_client.cpp", "${frameworks_module_reminder_path}/src/reminder_helper.cpp", "${frameworks_module_reminder_path}/src/reminder_request.cpp", diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index 859cbc092..c8aa7bf5e 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -14,6 +14,7 @@ */ #include "reminder_request.h" +#include "reminder_request_factory.h" #include "ans_const_define.h" #include "ans_log_wrapper.h" @@ -1100,6 +1101,9 @@ bool ReminderRequest::MarshallingWantParameters(Parcel& parcel, const AAFwk::Wan bool ReminderRequest::Marshalling(Parcel &parcel) const { + // write enum + uint8_t reminderType = static_cast(reminderType_); + WRITE_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType"); // write string WRITE_STRING_RETURN_FALSE_LOG(parcel, content_, "content"); WRITE_STRING_RETURN_FALSE_LOG(parcel, expiredContent_, "expiredContent"); @@ -1136,10 +1140,6 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const WRITE_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimesDynamic_, "snoozeTimesDynamic"); WRITE_UINT8_RETURN_FALSE_LOG(parcel, state_, "state"); - // write enum - uint8_t reminderType = static_cast(reminderType_); - WRITE_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType"); - int32_t slotType = static_cast(slotType_); WRITE_INT32_RETURN_FALSE_LOG(parcel, slotType, "slotType"); @@ -1154,16 +1154,19 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) { - auto objptr = new (std::nothrow) ReminderRequest(); - if (objptr == nullptr) { + uint8_t reminderType = static_cast(ReminderType::INVALID); + READ_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType"); + reminderType_ = static_cast(reminderType); + auto reminderRequest = ReminderRequestFactory::CreateReminderRequest(reminderType_); + if (reminderRequest == nullptr) { ANSR_LOGE("Failed to create reminder due to no memory."); - return objptr; + return reminderRequest; } - if (!objptr->ReadFromParcel(parcel)) { - delete objptr; - objptr = nullptr; + if (!reminderRequest->ReadFromParcel(parcel)) { + delete reminderRequest; + reminderRequest = nullptr; } - return objptr; + return reminderRequest; } bool ReminderRequest::ReadActionButtonFromParcel(Parcel& parcel) @@ -1263,9 +1266,7 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) READ_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimesDynamic_, "snoozeTimesDynamic"); READ_UINT8_RETURN_FALSE_LOG(parcel, state_, "state"); - uint8_t reminderType = static_cast(ReminderType::INVALID); - READ_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType"); - reminderType_ = static_cast(reminderType); + int32_t slotType = static_cast(NotificationConstant::SlotType::OTHER); READ_INT32_RETURN_FALSE_LOG(parcel, slotType, "slotType"); diff --git a/frameworks/reminder/src/reminder_request_factory.cpp b/frameworks/reminder/src/reminder_request_factory.cpp new file mode 100644 index 000000000..d17259e94 --- /dev/null +++ b/frameworks/reminder/src/reminder_request_factory.cpp @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2021-2024 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 "reminder_request_factory.h" + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" + + +#include +#include + +namespace OHOS { +namespace Notification { +ReminderRequest* ReminderRequestFactory::CreateReminderRequest(uint8_t reminderType) +{ + ReminderRequest* reminderRequest = nullptr; + switch (reminderType) { + case (ReminderRequest::ReminderType::TIMER): { + ANSR_LOGI("Create timer"); + reminderRequest = new (std::nothrow) ReminderRequestTimer(); + break; + } + case (ReminderRequest::ReminderType::ALARM): { + reminderRequest = new (std::nothrow) ReminderRequestAlarm(); + break; + } + case (ReminderRequest::ReminderType::CALENDAR): { + ANSR_LOGI("Create calendar"); + reminderRequest = new (std::nothrow) ReminderRequestCalendar(); + break; + } + default: { + ANSR_LOGW("PublishReminder fail."); + return ERR_ANS_INVALID_PARAM; + } + } + return reminderRequest; +} + +} // namespace Notification +} // namespace OHOS diff --git a/interfaces/inner_api/reminder_request_factory.h b/interfaces/inner_api/reminder_request_factory.h new file mode 100644 index 000000000..000c345e3 --- /dev/null +++ b/interfaces/inner_api/reminder_request_factory.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021-2022 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_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H + + + +#include "reminder_request.h" +#include "string" + + +namespace OHOS { +namespace Notification { + class ReminderRequestFactory { + static ReminderRequest* CreateReminderRequest(uint8_t reminderType); + } +}; +} // namespace Reminder +} // namespace OHOS +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H \ No newline at end of file diff --git a/services/reminder/include/reminder_service_ability.h b/services/reminder/include/reminder_service_ability.h index 2582e4983..43adb153d 100644 --- a/services/reminder/include/reminder_service_ability.h +++ b/services/reminder/include/reminder_service_ability.h @@ -46,8 +46,6 @@ public: private: void OnStart() final; void OnStop() final; - // void OnAddSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; - // void OnRemoveSystemAbility(int32_t systemAbilityId, const std::string& deviceId) override; private: sptr service_; -- Gitee From 03d5c6fea06a996ee1eec8e4766bc06a92edb1da Mon Sep 17 00:00:00 2001 From: fengyang Date: Thu, 21 Nov 2024 09:17:19 +0800 Subject: [PATCH 12/29] push Signed-off-by: fengyang --- frameworks/ans/test/unittest/BUILD.gn | 72 +- frameworks/reminder/src/reminder_helper.cpp | 2 +- frameworks/reminder/src/reminder_request.cpp | 16 +- .../reminder/src/reminder_request_alarm.cpp | 2 +- .../src/reminder_request_calendar.cpp | 2 +- .../reminder/src/reminder_request_client.cpp | 2 +- .../reminder/src/reminder_request_factory.cpp | 8 +- .../reminder/src/reminder_request_timer.cpp | 2 +- .../reminder/src/test/unittest/BUILD.gn | 159 + .../test/unittest/reminder_helper_test.cpp | 0 .../unittest/reminder_request_alarm_test.cpp | 0 .../mock_reminder_request.cpp | 0 .../reminder_request_branch_test.cpp | 0 .../reminder_request_calendar_test.cpp | 0 .../test/unittest/reminder_request_test.cpp | 0 .../unittest/reminder_request_timer_test.cpp | 0 .../test/unittest/reminder_store_test.cpp | 0 interfaces/inner_api/reminder_request.h | 4 +- .../inner_api/reminder_request_client.h | 4 +- .../inner_api/reminder_request_factory.h | 13 +- .../ans/include/reminder_store_strategy.h | 193 - .../advanced_notification_service_test.cpp | 79 - ...nced_notification_service_publish_test.cpp | 42 - .../include/reminder_access_token_helper.h | 6 +- .../include/reminder_bundle_manager_helper.h | 6 +- .../reminder/include/reminder_data_manager.h | 6 +- .../reminder/include/reminder_event_manager.h | 6 +- .../reminder_os_account_manager_helper.h | 6 +- services/reminder/include/reminder_service.h | 24 +- .../include/reminder_service_ability.h | 6 +- services/reminder/include/reminder_store.h | 6 +- .../include/reminder_store_strategy.h | 6 +- services/reminder/include/reminder_table.h | 6 +- .../reminder/include/reminder_table_old.h | 6 +- .../reminder/include/reminder_timer_info.h | 6 +- .../reminder/include/remote_death_recipient.h | 6 +- .../reminder/src/reminder_data_manager.cpp | 3 +- services/reminder/test/unittest/BUILD.gn | 647 +++ .../access_token_helper_test.cpp | 147 + ...nced_notification_publish_service_test.cpp | 1119 +++++ ...nced_notification_service_ability_test.cpp | 76 + ...anced_notification_service_branch_test.cpp | 1226 ++++++ .../advanced_notification_service_test.cpp | 3774 +++++++++++++++++ ...nced_notification_service_publish_test.cpp | 198 + .../bundle_manager_helper_branch_test.cpp | 245 ++ .../mock_service_registry.cpp | 43 + .../unittest/bundle_manager_helper_test.cpp | 160 + services/reminder/test/unittest/mock/blob.cpp | 195 + .../mock/distributed_kv_data_manager.cpp | 61 + .../mock/include/mock_ans_subscriber.h | 61 + .../unittest/mock/include/mock_bundle_mgr.h | 40 + .../unittest/mock/include/mock_ipc_skeleton.h | 139 + .../mock/include/mock_push_callback_stub.h | 33 + .../mock/include/mock_single_kv_store.h | 338 ++ .../mock/include/mock_swing_callback_stub.h | 33 + .../mock/mock_access_token_helper.cpp | 47 + .../unittest/mock/mock_accesstoken_kit.cpp | 78 + .../mock_advanced_notification_service.cpp | 51 + .../mock/mock_bundle_manager_helper.cpp | 82 + .../test/unittest/mock/mock_bundle_mgr.cpp | 72 + .../test/unittest/mock/mock_event_handler.cpp | 107 + .../reminder/test/unittest/mock/mock_ipc.cpp | 50 + .../mock/mock_notification_analytics_util.cpp | 141 + .../unittest/mock/mock_push_callback_stub.cpp | 26 + .../unittest/mock/mock_single_kv_store.cpp | 187 + .../mock/mock_swing_callback_stub.cpp | 26 + .../os_account_manager_helper_test.cpp | 134 + .../unittest/reminder_data_manager_test.cpp | 0 68 files changed, 9770 insertions(+), 465 deletions(-) create mode 100644 frameworks/reminder/src/test/unittest/BUILD.gn rename frameworks/{ans => reminder/src}/test/unittest/reminder_helper_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_alarm_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_calendar_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_request_timer_test.cpp (100%) rename frameworks/{ans => reminder/src}/test/unittest/reminder_store_test.cpp (100%) delete mode 100644 services/ans/include/reminder_store_strategy.h create mode 100644 services/reminder/test/unittest/BUILD.gn create mode 100644 services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp create mode 100644 services/reminder/test/unittest/advanced_notification_publish_service_test.cpp create mode 100644 services/reminder/test/unittest/advanced_notification_service_ability_test.cpp create mode 100644 services/reminder/test/unittest/advanced_notification_service_branch_test.cpp create mode 100644 services/reminder/test/unittest/advanced_notification_service_test.cpp create mode 100644 services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp create mode 100755 services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp create mode 100755 services/reminder/test/unittest/bundle_manager_helper_branch_test/mock_service_registry.cpp create mode 100644 services/reminder/test/unittest/bundle_manager_helper_test.cpp create mode 100644 services/reminder/test/unittest/mock/blob.cpp create mode 100644 services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp create mode 100644 services/reminder/test/unittest/mock/include/mock_ans_subscriber.h create mode 100644 services/reminder/test/unittest/mock/include/mock_bundle_mgr.h create mode 100644 services/reminder/test/unittest/mock/include/mock_ipc_skeleton.h create mode 100644 services/reminder/test/unittest/mock/include/mock_push_callback_stub.h create mode 100644 services/reminder/test/unittest/mock/include/mock_single_kv_store.h create mode 100644 services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h create mode 100644 services/reminder/test/unittest/mock/mock_access_token_helper.cpp create mode 100644 services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp create mode 100644 services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp create mode 100644 services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp create mode 100644 services/reminder/test/unittest/mock/mock_bundle_mgr.cpp create mode 100644 services/reminder/test/unittest/mock/mock_event_handler.cpp create mode 100644 services/reminder/test/unittest/mock/mock_ipc.cpp create mode 100644 services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp create mode 100644 services/reminder/test/unittest/mock/mock_push_callback_stub.cpp create mode 100644 services/reminder/test/unittest/mock/mock_single_kv_store.cpp create mode 100644 services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp create mode 100644 services/reminder/test/unittest/os_account_manager_helper_test.cpp rename services/{ans => reminder}/test/unittest/reminder_data_manager_test.cpp (100%) diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index d6a5b2f1e..beea27297 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -65,11 +65,6 @@ ohos_unittest("ans_reminder_unit_test") { "${frameworks_module_ans_path}/test/unittest/notification_unified_group_info_test.cpp", "${frameworks_module_ans_path}/test/unittest/notification_user_input_test.cpp", "${frameworks_module_ans_path}/test/unittest/push_promise_callback_test.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_helper_test.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_alarm_test.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_calendar_test.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_timer_test.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_store_test.cpp", ] deps = [ @@ -117,74 +112,9 @@ ohos_unittest("ans_reminder_unit_test") { branch_protector_ret = "pac_ret" } -ohos_unittest("reminder_request_test") { - module_out_path = module_output_path - - include_dirs = [ - ".", - "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - ] - - sources = [ - "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_test.cpp", - ] - - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gtest_main", - ] - - external_deps = [ - "ability_base:base", - "ability_base:want", - "ability_base:zuri", - "c_utils:utils", - "relational_store:native_rdb", - ] - - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - -ohos_unittest("reminder_request_branch_test") { - module_out_path = module_output_path - - include_dirs = [ - ".", - "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - ] - - sources = [ - "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp", - ] - - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gtest_main", - ] - - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "c_utils:utils", - "relational_store:native_rdb", - ] - - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - group("unittest") { testonly = true deps = [ - ":ans_reminder_unit_test", - ":reminder_request_branch_test", - ":reminder_request_test", + ":ans_unit_test", ] } diff --git a/frameworks/reminder/src/reminder_helper.cpp b/frameworks/reminder/src/reminder_helper.cpp index a38f7a4fa..b82b35a37 100644 --- a/frameworks/reminder/src/reminder_helper.cpp +++ b/frameworks/reminder/src/reminder_helper.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index c8aa7bf5e..a5fbc34ef 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 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 @@ -1152,12 +1152,20 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const return true; } -ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) +bool ReminderRequest::ReadReminderTypeFormParcel(Parcel &parcel, ReminderType& tarReminderType) { uint8_t reminderType = static_cast(ReminderType::INVALID); READ_UINT8_RETURN_FALSE_LOG(parcel, reminderType, "reminderType"); - reminderType_ = static_cast(reminderType); - auto reminderRequest = ReminderRequestFactory::CreateReminderRequest(reminderType_); + tarReminderType = static_cast(reminderType); + return true; +} + +ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) +{ + ReminderType tarReminderType = ReminderType::INVALID; + ReadReminderTypeFormParcel(tarReminderType); + auto reminderRequest = ReminderRequestFactory::CreateReminderRequest(tarReminderType); + if (reminderRequest == nullptr) { ANSR_LOGE("Failed to create reminder due to no memory."); return reminderRequest; diff --git a/frameworks/reminder/src/reminder_request_alarm.cpp b/frameworks/reminder/src/reminder_request_alarm.cpp index 8fd928b2b..3a384fc22 100644 --- a/frameworks/reminder/src/reminder_request_alarm.cpp +++ b/frameworks/reminder/src/reminder_request_alarm.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/reminder/src/reminder_request_calendar.cpp b/frameworks/reminder/src/reminder_request_calendar.cpp index 23ed023c7..f6aff4d92 100644 --- a/frameworks/reminder/src/reminder_request_calendar.cpp +++ b/frameworks/reminder/src/reminder_request_calendar.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index dcf691e23..379b2cf74 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/reminder/src/reminder_request_factory.cpp b/frameworks/reminder/src/reminder_request_factory.cpp index d17259e94..5e580f44d 100644 --- a/frameworks/reminder/src/reminder_request_factory.cpp +++ b/frameworks/reminder/src/reminder_request_factory.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2024 Huawei Device Co., Ltd. + * Copyright (c) 2024 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 @@ -27,7 +27,7 @@ namespace OHOS { namespace Notification { -ReminderRequest* ReminderRequestFactory::CreateReminderRequest(uint8_t reminderType) +ReminderRequest* ReminderRequestFactory::CreateReminderRequest(ReminderRequest::ReminderType reminderType) { ReminderRequest* reminderRequest = nullptr; switch (reminderType) { @@ -37,6 +37,7 @@ ReminderRequest* ReminderRequestFactory::CreateReminderRequest(uint8_t reminderT break; } case (ReminderRequest::ReminderType::ALARM): { + ANSR_LOGI("Create alarm"); reminderRequest = new (std::nothrow) ReminderRequestAlarm(); break; } @@ -47,9 +48,10 @@ ReminderRequest* ReminderRequestFactory::CreateReminderRequest(uint8_t reminderT } default: { ANSR_LOGW("PublishReminder fail."); - return ERR_ANS_INVALID_PARAM; + return nullptr; } } + reminderRequest->SetReminderType(reminderType); return reminderRequest; } diff --git a/frameworks/reminder/src/reminder_request_timer.cpp b/frameworks/reminder/src/reminder_request_timer.cpp index 867f26ae9..621c6681a 100644 --- a/frameworks/reminder/src/reminder_request_timer.cpp +++ b/frameworks/reminder/src/reminder_request_timer.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021-2022 Huawei Device Co., Ltd. + * Copyright (c) 2024 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at diff --git a/frameworks/reminder/src/test/unittest/BUILD.gn b/frameworks/reminder/src/test/unittest/BUILD.gn new file mode 100644 index 000000000..edddb02d8 --- /dev/null +++ b/frameworks/reminder/src/test/unittest/BUILD.gn @@ -0,0 +1,159 @@ +# Copyright (c) 2021-2024 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/distributed_notification_service/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "${component_name}/unittest" + +ohos_unittest("reminder_unit_test") { + module_out_path = module_output_path + + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "/${services_path}/reminder/include", + "${services_path}/ans/test/unittest/mock/include", + "${ffrt_path}/interfaces/kits", + ] + + sources = [ + "${frameworks_module_reminder_path}/test/unittest/reminder_helper_test.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_alarm_test.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_calendar_test.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_timer_test.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_store_test.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", + "//third_party/googletest:gtest_main", + ] + + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:wantagent_innerkits", + "access_token:libnativetoken", + "access_token:libtoken_setproc", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + ] + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" + + sanitize = { + cfi = true + cfi_cross_dso = true + debug = false + } + branch_protector_ret = "pac_ret" +} + +ohos_unittest("reminder_request_test") { + module_out_path = module_output_path + + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "/${services_path}/reminder/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ + "${frameworks_module_reminder_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_test.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "c_utils:utils", + "relational_store:native_rdb", + ] + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("reminder_request_branch_test") { + module_out_path = module_output_path + + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ + "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", + "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "c_utils:utils", + "relational_store:native_rdb", + ] + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +group("unittest") { + testonly = true + deps = [ + ":ans_reminder_unit_test", + ":reminder_request_branch_test", + ":reminder_request_test", + ] +} diff --git a/frameworks/ans/test/unittest/reminder_helper_test.cpp b/frameworks/reminder/src/test/unittest/reminder_helper_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_helper_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_helper_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_alarm_test.cpp b/frameworks/reminder/src/test/unittest/reminder_request_alarm_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_alarm_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_alarm_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp b/frameworks/reminder/src/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/reminder/src/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_calendar_test.cpp b/frameworks/reminder/src/test/unittest/reminder_request_calendar_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_calendar_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_calendar_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_test.cpp b/frameworks/reminder/src/test/unittest/reminder_request_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_request_timer_test.cpp b/frameworks/reminder/src/test/unittest/reminder_request_timer_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_request_timer_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_request_timer_test.cpp diff --git a/frameworks/ans/test/unittest/reminder_store_test.cpp b/frameworks/reminder/src/test/unittest/reminder_store_test.cpp similarity index 100% rename from frameworks/ans/test/unittest/reminder_store_test.cpp rename to frameworks/reminder/src/test/unittest/reminder_store_test.cpp diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index eb5c2de54..badd5a103 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -947,6 +947,8 @@ public: static uint64_t GetDurationSinceEpochInMilli(const time_t target); static std::vector StringSplit(std::string source, const std::string &split); + static bool ReadReminderTypeFormParcel(Parcel &parcel, ReminderType& tarReminderType); + static int32_t GLOBAL_ID; static const uint64_t INVALID_LONG_LONG_VALUE; static const uint16_t INVALID_U16_VALUE; @@ -1147,6 +1149,6 @@ private: sptr notificationOption_ {nullptr}; }; -} // namespace Reminder +} // namespace Notification } // namespace OHOS #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H \ No newline at end of file diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index 2ed9d113f..42a7d726f 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -12,7 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_CLIENT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_CLIENT_H #include #include @@ -126,4 +127,5 @@ private: }; } // namespace Notification } // namespace OHOS +#endif BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_CLIENT_H diff --git a/interfaces/inner_api/reminder_request_factory.h b/interfaces/inner_api/reminder_request_factory.h index 000c345e3..26a26cea5 100644 --- a/interfaces/inner_api/reminder_request_factory.h +++ b/interfaces/inner_api/reminder_request_factory.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_FACTORY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_FACTORY_H @@ -24,10 +24,9 @@ namespace OHOS { namespace Notification { - class ReminderRequestFactory { - static ReminderRequest* CreateReminderRequest(uint8_t reminderType); - } +class ReminderRequestFactory { + static ReminderRequest* CreateReminderRequest(ReminderRequest::ReminderType reminderType); }; -} // namespace Reminder +} // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_FACTORY_H \ No newline at end of file diff --git a/services/ans/include/reminder_store_strategy.h b/services/ans/include/reminder_store_strategy.h deleted file mode 100644 index 57555341d..000000000 --- a/services/ans/include/reminder_store_strategy.h +++ /dev/null @@ -1,193 +0,0 @@ -// /* -// * Copyright (c) 2024 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_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H -// #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H - -// #include -// #include - -// #include "reminder_request.h" -// #include "rdb_store.h" - -// namespace OHOS { -// namespace Notification { -// class ReminderStrategy { -// public: -// /** -// * @brief Gets the value from rdb result. -// * -// * @param resultSet the rdb result. -// * @param name the column name in rdb. -// * @param value the column value in rdb. -// */ -// template -// static void GetRdbValue(const std::shared_ptr& resultSet, -// const std::string& name, T& value); - -// public: -// /** -// * @brief Persist the reminder to the database. -// */ -// static void AppendValuesBucket(const sptr& reminder, -// NativeRdb::ValuesBucket &values, const bool oldVersion = false); - -// /** -// * @brief Restore the reminder from the database(old version rdb). -// */ -// static void RecoverFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); - -// /** -// * @brief Restore the reminder from the database. -// */ -// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& resultSet); - -// private: -// /** -// * @brief Recovery time related fields from the database(old version rdb). -// */ -// static void RecoverTimeFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); -// /** -// * @brief Recovery id related fields from the database(old version rdb). -// */ -// static void RecoverIdFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); -// /** -// * @brief Recovery context related from the database(old version rdb). -// */ -// static void RecoverContextFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); - -// /** -// * @brief Recovery time related fields from the database. -// */ -// static void RecoverTimeFromDb(sptr& reminder, -// const std::shared_ptr& resultSet); -// /** -// * @brief Recovery id related fields from the database. -// */ -// static void RecoverIdFromDb(sptr& reminder, -// const std::shared_ptr& resultSet); -// /** -// * @brief Recovery context related from the database. -// */ -// static void RecoverContextFromDb(sptr& reminder, -// const std::shared_ptr& resultSet); -// }; - -// class ReminderTimerStrategy { -// public: -// /** -// * @brief Persist the reminder to the database. -// */ -// static void AppendValuesBucket(const sptr& reminder, -// NativeRdb::ValuesBucket& values); - -// /** -// * @brief Restore the reminder from the database(old version rdb). -// */ -// static void RecoverFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); - -// /** -// * @brief Restore the reminder from the database. -// */ -// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, -// const std::shared_ptr& resultSet); -// }; - -// class ReminderAlarmStrategy { -// public: -// /** -// * @brief Persist the reminder to the database. -// */ -// static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); - -// /** -// * @brief Restore the reminder from the database(old version rdb). -// */ -// static void RecoverFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); - -// /** -// * @brief Restore the reminder from the database. -// */ -// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, -// const std::shared_ptr& resultSet); -// }; - -// class ReminderCalendarStrategy { -// public: -// /** -// * @brief Persist the reminder to the database. -// */ -// static void AppendValuesBucket(const sptr &reminder, NativeRdb::ValuesBucket &values); - -// /** -// * @brief Restore the reminder from the database(old version rdb). -// */ -// static void RecoverFromOldVersion(sptr& reminder, -// const std::shared_ptr& resultSet); - -// /** -// * @brief Restore the reminder from the database. -// */ -// static void RecoverFromDb(sptr& reminder, const std::shared_ptr& baseResult, -// const std::shared_ptr& resultSet); - -// private: -// static void RecoverTime(sptr& reminder, const std::shared_ptr& resultSet); -// }; - -// template -// void ReminderStrategy::GetRdbValue(const std::shared_ptr& resultSet, -// const std::string& name, T& value) -// { -// value = T(); -// int32_t columnIndex = -1; -// resultSet->GetColumnIndex(name, columnIndex); -// if (columnIndex == -1) { -// ANSR_LOGE("the column %{public}s does not exsit.", name.c_str()); -// return; -// } - -// if constexpr (std::is_same_v) { -// resultSet->GetString(columnIndex, value); -// } else if constexpr (std::is_same_v) { -// resultSet->GetLong(columnIndex, value); -// } else if constexpr (std::is_same_v) { -// int64_t t = 0; -// resultSet->GetLong(columnIndex, t); -// value = static_cast(t); -// } else if constexpr (std::is_same_v) { -// resultSet->GetInt(columnIndex, value); -// } else if constexpr (std::is_same_v) { -// int32_t t = 0; -// resultSet->GetInt(columnIndex, t); -// value = static_cast(t); -// } else if constexpr (std::is_same_v) { -// int32_t t = 0; -// resultSet->GetInt(columnIndex, t); -// value = static_cast(t); -// } else if constexpr (std::is_same_v) { -// int32_t t = 0; -// resultSet->GetInt(columnIndex, t); -// value = static_cast(t); -// } -// } -// } // namespace Notification -// } // namespace OHOS -// #endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 849e0379a..a7f0d5700 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -993,18 +993,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13100, (int)ERR_ANS_INVALID_PARAM); } -/** - * @tc.number : AdvancedNotificationServiceTest_13500 - * @tc.name : ANS_GetValidReminders_0100 - * @tc.desc : Test GetValidReminders function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13500, Function | SmallTest | Level1) -{ - std::vector> reminders; - ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), (int)ERR_NO_INIT); -} - /** * @tc.number : AdvancedNotificationServiceTest_13600 * @tc.name : ANS_ActiveNotificationDump_0100 @@ -1429,14 +1417,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16900, ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, bundleOption), ERR_ANS_INVALID_BUNDLE); - int32_t reminderId = 1; - ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), ERR_ANS_INVALID_BUNDLE); - - ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), ERR_ANS_INVALID_BUNDLE); - - std::vector> reminders; - ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), ERR_ANS_INVALID_BUNDLE); - ASSERT_EQ(advancedNotificationService_->RemoveAllSlots(), ERR_ANS_INVALID_BUNDLE); ASSERT_EQ(advancedNotificationService_->AddSlotByType(NotificationConstant::SlotType::OTHER), @@ -3686,65 +3666,6 @@ HWTEST_F(AdvancedNotificationServiceTest, RegisterSwingCallback_00002, Function } #endif -/** - * @tc.number : AddExcludeDate_00001 - * @tc.name : Test AddExcludeDate - * @tc.desc : Test AddExcludeDate function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - uint64_t time = 124325; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - -/** - * @tc.number : DelExcludeDates_00002 - * @tc.name : Test DelExcludeDates - * @tc.desc : Test DelExcludeDates function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - -/** - * @tc.number : GetExcludeDates_00001 - * @tc.name : Test GetExcludeDates - * @tc.desc : Test GetExcludeDates function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - std::vector times; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - /** * @tc.number : PublishFlowControl_00001 * @tc.name : Test PublishFlowControl diff --git a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp index a25c5be83..a6ef039d2 100644 --- a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp @@ -1319,48 +1319,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_12800, ASSERT_EQ(advancedNotificationService_->PublishAsBundle(notification, representativeBundle), result); } - -/** - * @tc.number : AdvancedNotificationServiceTest_13200 - * @tc.name : ANS_PublishReminder_0100 - * @tc.desc : Test PublishReminder function - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13200, Function | SmallTest | Level1) -{ - sptr reminder = nullptr; - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13300 - * @tc.name : ANS_CancelReminder_0100 - * @tc.desc : Test CancelReminder function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - int32_t reminderId = 1; - ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), (int)ERR_NO_INIT); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13400 - * @tc.name : ANS_CancelAllReminders_0100 - * @tc.desc : Test CancelAllReminders function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13400, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), (int)ERR_NO_INIT); -} - /** * @tc.number : AdvancedNotificationServiceTest_21500 * @tc.name : PublishPreparedNotification_1000 diff --git a/services/reminder/include/reminder_access_token_helper.h b/services/reminder/include/reminder_access_token_helper.h index e2359d28e..ea0afa225 100644 --- a/services/reminder/include/reminder_access_token_helper.h +++ b/services/reminder/include/reminder_access_token_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_ACCESS_TOKEN_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_ACCESS_TOKEN_HELPER_H #include #include "refbase.h" @@ -31,4 +31,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ACCESS_TOKEN_HELPER_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_ACCESS_TOKEN_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_bundle_manager_helper.h b/services/reminder/include/reminder_bundle_manager_helper.h index af57b395b..25be9747b 100644 --- a/services/reminder/include/reminder_bundle_manager_helper.h +++ b/services/reminder/include/reminder_bundle_manager_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H #include #include @@ -82,4 +82,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_BUNDLE_MANAGER_HELPER_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index a52c4d84b..027dd2429 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_DATA_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_DATA_MANAGER_H #include #include @@ -749,4 +749,4 @@ private: }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_DATA_MANAGER_H diff --git a/services/reminder/include/reminder_event_manager.h b/services/reminder/include/reminder_event_manager.h index 654bcca95..b6e875d42 100644 --- a/services/reminder/include/reminder_event_manager.h +++ b/services/reminder/include/reminder_event_manager.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_EVENT_MANAGER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_EVENT_MANAGER_H #include "reminder_service.h" #include "common_event_subscriber.h" @@ -99,4 +99,4 @@ private: }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_EVENT_MANAGER_H diff --git a/services/reminder/include/reminder_os_account_manager_helper.h b/services/reminder/include/reminder_os_account_manager_helper.h index 55a2c1e27..557cfda78 100644 --- a/services/reminder/include/reminder_os_account_manager_helper.h +++ b/services/reminder/include/reminder_os_account_manager_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_OS_ACCOUNT_MANAGER_HELPER_H -#define BASE_NOTIFICATION_OS_ACCOUNT_MANAGER_HELPER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H #include "errors.h" #include "singleton.h" @@ -52,4 +52,4 @@ public: }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h index 496d97512..ed81520b0 100644 --- a/services/reminder/include/reminder_service.h +++ b/services/reminder/include/reminder_service.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_H #include #include @@ -29,24 +29,6 @@ #include "ans_const_define.h" #include "reminder_manager_stub.h" -// #include "common_notification_publish_process.h" -// #include "distributed_kv_data_manager.h" -// #include "distributed_kvstore_death_recipient.h" -// #include "live_publish_process.h" -// #include "notification.h" -// #include "notification_dialog_manager.h" -// #include "notification_do_not_disturb_profile.h" -// #include "notification_record.h" -// #include "notification_slot_filter.h" -// #include "notification_sorting_map.h" -// #include "permission_filter.h" -// #include "push_callback_interface.h" -// #include "system_event_observer.h" -// #include "notification_subscriber_manager.h" -// #include "distributed_device_status.h" -// #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED -// #include "reminder_swing_decision_center.h" -// #endif namespace OHOS { namespace Notification { @@ -137,4 +119,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_ADVANCED_NOTIFICATION_SERVICE_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_H diff --git a/services/reminder/include/reminder_service_ability.h b/services/reminder/include/reminder_service_ability.h index 43adb153d..36111f397 100644 --- a/services/reminder/include/reminder_service_ability.h +++ b/services/reminder/include/reminder_service_ability.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_ABILITY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_ABILITY_H #include "system_ability.h" @@ -54,4 +54,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_NOTIFICATION_SERVICE_ABILITY_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_SERVICE_ABILITY_H diff --git a/services/reminder/include/reminder_store.h b/services/reminder/include/reminder_store.h index a71f1bd08..864674164 100644 --- a/services/reminder/include/reminder_store.h +++ b/services/reminder/include/reminder_store.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_H #include @@ -106,4 +106,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_STORE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_H \ No newline at end of file diff --git a/services/reminder/include/reminder_store_strategy.h b/services/reminder/include/reminder_store_strategy.h index 0d0ccefb6..daadfdd92 100644 --- a/services/reminder/include/reminder_store_strategy.h +++ b/services/reminder/include/reminder_store_strategy.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_STRATEGY_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_STRATEGY_H #include #include @@ -190,4 +190,4 @@ void ReminderStrategy::GetRdbValue(const std::shared_ptr& } } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_STORE_STRATEGY_H \ No newline at end of file diff --git a/services/reminder/include/reminder_table.h b/services/reminder/include/reminder_table.h index 4542000cd..7a174f87b 100644 --- a/services/reminder/include/reminder_table.h +++ b/services/reminder/include/reminder_table.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_H #include #include @@ -269,4 +269,4 @@ public: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_H diff --git a/services/reminder/include/reminder_table_old.h b/services/reminder/include/reminder_table_old.h index 172541b49..77c228fd1 100644 --- a/services/reminder/include/reminder_table_old.h +++ b/services/reminder/include/reminder_table_old.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_OLD_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_OLD_H #include #include @@ -236,4 +236,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_TABLE_OLD_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TABLE_OLD_H diff --git a/services/reminder/include/reminder_timer_info.h b/services/reminder/include/reminder_timer_info.h index 1ac0c35d4..28c05a7ba 100644 --- a/services/reminder/include/reminder_timer_info.h +++ b/services/reminder/include/reminder_timer_info.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TIMER_INFO_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TIMER_INFO_H #include "reminder_service.h" #include "itimer_info.h" @@ -85,4 +85,4 @@ private: } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/reminder/include/remote_death_recipient.h b/services/reminder/include/remote_death_recipient.h index da1b9563b..4c7cddcbe 100644 --- a/services/reminder/include/remote_death_recipient.h +++ b/services/reminder/include/remote_death_recipient.h @@ -12,8 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMOTE_DEATH_RECIPIENT_H #include @@ -58,4 +58,4 @@ private: } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H \ No newline at end of file +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMOTE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 5a75a336a..7b817d834 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -15,8 +15,7 @@ #include "reminder_data_manager.h" -#include "ability_manager_client.h" -// #include "access_token_helper.h" +#include "ability_manager_client.h"" #include "ans_log_wrapper.h" #include "ans_const_define.h" #include "common_event_support.h" diff --git a/services/reminder/test/unittest/BUILD.gn b/services/reminder/test/unittest/BUILD.gn new file mode 100644 index 000000000..30c94feaa --- /dev/null +++ b/services/reminder/test/unittest/BUILD.gn @@ -0,0 +1,647 @@ +# Copyright (c) 2022-2023 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/distributed_notification_service/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "${component_name}/unittest" + +ohos_unittest("reminder_unit_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", + ] + + defines = [] + + sources = [ + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "mock/mock_single_kv_store.cpp", + "reminder_data_manager_test.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", + "//third_party/googletest:gtest_main", + ] + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "data_share:datashare_common", + "data_share:datashare_consumer", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + cflags = [] + if (hisysevent_usage) { + external_deps += [ "hisysevent:libhisysevent" ] + cflags += [ "-DHAS_HISYSEVENT_PART" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("notification_service_test") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + defines = [] + + sources = [ + "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_service_test.cpp", + "advanced_notification_slot_service_test.cpp", + "advanced_notification_utils_test.cpp", + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", + "mock/mock_accesstoken_kit.cpp", + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_bundle_mgr.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "mock/mock_push_callback_stub.cpp", + "mock/mock_single_kv_store.cpp", + "notification_dialog_test/mock_os_account_manager_annex.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + cflags = [] + if (hisysevent_usage) { + external_deps += [ "hisysevent:libhisysevent" ] + cflags += [ "-DHAS_HISYSEVENT_PART" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("notification_publish_service_test") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + defines = [] + + sources = [ + "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_publish_service_test.cpp", + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", + "mock/mock_accesstoken_kit.cpp", + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_bundle_mgr.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "mock/mock_push_callback_stub.cpp", + "mock/mock_single_kv_store.cpp", + "notification_dialog_test/mock_os_account_manager_annex.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + cflags = [] + if (hisysevent_usage) { + external_deps += [ "hisysevent:libhisysevent" ] + cflags += [ "-DHAS_HISYSEVENT_PART" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("notification_service_publish_test") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + defines = [] + + sources = [ + "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_service_test/advanced_notification_service_publish_test.cpp", + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_access_token_helper.cpp", + "mock/mock_accesstoken_kit.cpp", + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_bundle_mgr.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "mock/mock_push_callback_stub.cpp", + "mock/mock_single_kv_store.cpp", + "notification_dialog_test/mock_os_account_manager_annex.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_base:base", + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "device_manager:devicemanagersdk", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + cflags = [] + if (hisysevent_usage) { + external_deps += [ "hisysevent:libhisysevent" ] + cflags += [ "-DHAS_HISYSEVENT_PART" ] + } + + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("access_token_helper_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ + "${services_path}/ans/src/access_token_helper.cpp", + "${services_path}/ans/test/unittest/mock/mock_accesstoken_kit.cpp", + "${services_path}/ans/test/unittest/mock/mock_notification_analytics_util.cpp", + "${test_path}/mock/mock_tokenid_kit.cpp", + "access_token_helper_test/access_token_helper_test.cpp", + ] + + deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "init:libbegetutil", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines = [ "PLAYER_FRAMEWORK_ENABLE" ] + } + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("bundle_manager_helper_branch_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ + "bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp", + "bundle_manager_helper_branch_test/mock_service_registry.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines = [ "PLAYER_FRAMEWORK_ENABLE" ] + } + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("advanced_notification_service_branch_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + "${ffrt_path}/interfaces/kits", + ] + + defines = [] + + sources = [ + "${test_path}/mock/mock_tokenid_kit.cpp", + "advanced_notification_service_branch_test.cpp", + "mock/blob.cpp", + "mock/distributed_kv_data_manager.cpp", + "mock/mock_accesstoken_kit.cpp", + "mock/mock_advanced_notification_service.cpp", + "mock/mock_bundle_manager_helper.cpp", + "mock/mock_bundle_mgr.cpp", + "mock/mock_event_handler.cpp", + "mock/mock_ipc.cpp", + "mock/mock_single_kv_store.cpp", + "notification_dialog_test/mock_os_account_manager_annex.cpp", + "notification_subscriber_manager_branch_test/mock_access_token_helper.cpp", + ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "ffrt:libffrt", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +ohos_unittest("os_account_manager_helper_test") { + module_out_path = module_output_path + include_dirs = [ + ".", + "include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ "os_account_manager_helper_test.cpp" ] + + deps = [ + "${frameworks_module_ans_path}:ans_innerkits", + "${services_path}/ans:libans", + "//third_party/googletest:gtest_main", + ] + + external_deps = [ + "ability_base:want", + "ability_base:zuri", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "eventhandler:libeventhandler", + "hilog:libhilog", + "hitrace:hitrace_meter", + "hitrace:libhitracechain", + "image_framework:image_native", + "ipc:ipc_core", + "kv_store:distributeddata_inner", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "safwk:system_ability_fwk", + "samgr:samgr_proxy", + "time_service:time_client", + ] + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines = [ "PLAYER_FRAMEWORK_ENABLE" ] + } + subsystem_name = "${subsystem_name}" + part_name = "${component_name}" +} + +group("unittest") { + testonly = true + deps = [ + ":access_token_helper_test", + ":advanced_notification_service_branch_test", + ":ans_unit_test", + ":bundle_manager_helper_branch_test", + ":notification_config_parse_test", + ":notification_dialog_test", + ":notification_preferences_database_branch_test", + ":notification_preferences_database_test", + ":notification_preferences_test", + ":notification_publish_service_test", + ":notification_rdb_data_mgr_test", + ":notification_service_publish_test", + ":notification_service_test", + ":notification_subscriber_manager_branch_test", + ":notification_subscriber_manager_test", + ":os_account_manager_helper_test", + ":push_callback_stub_test", + ":reminder_unit_test", + ] +} diff --git a/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp b/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp new file mode 100644 index 000000000..7cd61c13c --- /dev/null +++ b/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp @@ -0,0 +1,147 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include "accesstoken_kit.h" +#define private public +#define protected public +#include "access_token_helper.h" +#include "ans_log_wrapper.h" +#include "ipc_skeleton.h" +#undef private +#undef protected +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace Notification { + +extern void MockGetTokenTypeFlag(ATokenTypeEnum mockRet); +extern void MockDlpType(DlpType mockRet); +extern void MockApl(ATokenAplEnum mockRet); +class AccessTokenHelperTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp() override; + void TearDown() override; + + std::shared_ptr stub_; +}; + +void AccessTokenHelperTest::SetUpTestCase() +{ +} + +void AccessTokenHelperTest::TearDownTestCase() +{ +} + +void AccessTokenHelperTest::SetUp() +{ + stub_ = std::make_shared(); +} + +void AccessTokenHelperTest::TearDown() +{ +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : VerifyCallerPermission_00100 + * @tc.desc : VerifyCallerPermission success + */ +HWTEST_F(AccessTokenHelperTest, VerifyCallerPermission_00100, Function | SmallTest | Level1) +{ + AccessTokenID tokenID = 0; + string permission; + EXPECT_TRUE(stub_->VerifyCallerPermission(tokenID, permission)); +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : VerifyNativeToken_00100 + * @tc.desc : VerifyNativeToken success + */ +HWTEST_F(AccessTokenHelperTest, VerifyNativeToken_00100, Function | SmallTest | Level1) +{ + AccessTokenID tokenID = 0; + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); + EXPECT_TRUE(stub_->VerifyNativeToken(tokenID)); +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : IsSystemApp_00100 + * @tc.desc : IsSystemApp Token Type TOKEN_NATIVE + */ +HWTEST_F(AccessTokenHelperTest, IsSystemApp_00100, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); + EXPECT_FALSE(stub_->IsSystemApp()); +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : IsSystemApp_00200 + * @tc.desc : IsSystemApp Token Type TOKEN_HAP + */ +HWTEST_F(AccessTokenHelperTest, IsSystemApp_00200, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + EXPECT_TRUE(stub_->IsSystemApp()); +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : IsDlpHap_00100 + * @tc.desc : IsDlpHap Token Type TOKEN_HAP + */ +HWTEST_F(AccessTokenHelperTest, IsDlpHap_00100, Function | SmallTest | Level1) +{ + AccessTokenID tokenID = 0; + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockDlpType(DlpType::DLP_READ); + EXPECT_TRUE(stub_->IsDlpHap(tokenID)); +} + +/** + * @tc.number : AccessTokenHelperTest + * @tc.name : IsDlpHap_00200 + * @tc.desc : IsDlpHap Token Type TOKEN_NATIVE + */ +HWTEST_F(AccessTokenHelperTest, IsDlpHap_00200, Function | SmallTest | Level1) +{ + AccessTokenID tokenID = 0; + MockDlpType(DlpType::DLP_COMMON); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); + EXPECT_FALSE(stub_->IsDlpHap(tokenID)); +} + + +/** + * @tc.number : AdvancedNotificationService_01300 + * @tc.name : AdvancedNotificationService_01300 + * @tc.desc : Test CheckPermission function and result is false + */ +HWTEST_F(AccessTokenHelperTest, CheckPermission_00100, Function | SmallTest | Level1) +{ + std::string permission = ""; + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + ASSERT_EQ(stub_->CheckPermission(permission), true); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp b/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp new file mode 100644 index 000000000..6512c10ee --- /dev/null +++ b/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp @@ -0,0 +1,1119 @@ +/* + * Copyright (c) 2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include + +#include "gtest/gtest.h" + +#define private public +#include "advanced_notification_service.h" +#include "ability_manager_errors.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "accesstoken_kit.h" +#include "notification_preferences.h" +#include "notification_constant.h" +#include "ans_ut_constant.h" +#include "ans_dialog_host_client.h" +#include "mock_push_callback_stub.h" + +extern void MockIsOsAccountExists(bool exists); + +using namespace testing::ext; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace Notification { +extern void MockIsVerfyPermisson(bool isVerify); +extern void MockGetTokenTypeFlag(ATokenTypeEnum mockRet); +extern void MockIsSystemApp(bool isSystemApp); +class AnsPublishServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +private: + void TestAddNotification(int notificationId, const sptr &bundle); + void RegisterPushCheck(); + +private: + static sptr advancedNotificationService_; +}; + +sptr AnsPublishServiceTest::advancedNotificationService_ = nullptr; + +void AnsPublishServiceTest::SetUpTestCase() {} + +void AnsPublishServiceTest::TearDownTestCase() {} + +void AnsPublishServiceTest::SetUp() +{ + GTEST_LOG_(INFO) << "SetUp start"; + + advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); + NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); + advancedNotificationService_->CancelAll(0); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + MockIsSystemApp(true); + GTEST_LOG_(INFO) << "SetUp end"; +} + +void AnsPublishServiceTest::TearDown() +{ + delete advancedNotificationService_; + advancedNotificationService_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +void AnsPublishServiceTest::TestAddNotification(int notificationId, const sptr &bundle) +{ + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(slotType); + request->SetOwnerUserId(1); + request->SetCreatorUserId(1); + request->SetOwnerBundleName("test"); + request->SetOwnerUid(0); + request->SetNotificationId(notificationId); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + auto ret = advancedNotificationService_->AssignToNotificationList(record); +} + +void AnsPublishServiceTest::RegisterPushCheck() +{ + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + checkRequest->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), ERR_OK); +} + +/** + * @tc.name: Publish_00001 + * @tc.desc: Test Publish + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + auto localLiveContent = std::make_shared(); + auto content = std::make_shared(localLiveContent); + request->SetContent(content); + request->SetCreatorUid(1); + request->SetOwnerUid(1); + MockIsOsAccountExists(true); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.name: Publish_00002 + * @tc.desc: Test Publish + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00002, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + request->SetRemoveAllowed(false); + request->SetInProgress(true); + auto normalContent = std::make_shared(); + auto content = std::make_shared(normalContent); + request->SetContent(content); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERR_OK); +} + + +/** + * @tc.name: Publish_00003 + * @tc.desc: Publish live_view notification once + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00003, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + request->SetNotificationId(1); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + RegisterPushCheck(); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERR_OK); + + sptr slot; + NotificationConstant::SlotType slotType = NotificationConstant::SlotType::LIVE_VIEW; + ret = advancedNotificationService_->GetSlotByType(slotType, slot); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(1, slot->GetAuthorizedStatus()); + ASSERT_EQ(1, slot->GetAuthHintCnt()); +} + +/** + * @tc.name: Publish_00004 + * @tc.desc: Publish live_view notification twice + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00004, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + request->SetNotificationId(1); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + RegisterPushCheck(); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERR_OK); + + sptr request2 = new (std::nothrow) NotificationRequest(); + request2->SetNotificationId(2); + request2->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + request2->SetContent(content); + ret = advancedNotificationService_->Publish(label, request2); + ASSERT_EQ(ret, (int)ERR_OK); + + sptr slot; + NotificationConstant::SlotType slotType = NotificationConstant::SlotType::LIVE_VIEW; + ret = advancedNotificationService_->GetSlotByType(slotType, slot); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(0, slot->GetAuthorizedStatus()); + ASSERT_EQ(2, slot->GetAuthHintCnt()); +} + +/** + * @tc.name: Publish_00005 + * @tc.desc: Publish test receiver user and checkUserExists is true + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00005, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + request->SetNotificationId(1); + request->SetReceiverUserId(101); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + RegisterPushCheck(); + MockIsOsAccountExists(true); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: Publish_00006 + * @tc.desc: Publish test receiver user and checkUserExists is false + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, Publish_00006, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + std::string label = ""; + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + request->SetNotificationId(1); + request->SetReceiverUserId(101); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + MockIsOsAccountExists(false); + + auto ret = advancedNotificationService_->Publish(label, request); + ASSERT_EQ(ret, (int)ERROR_USER_NOT_EXIST); +} + +/** + * @tc.name: DeleteByBundle_00001 + * @tc.desc: Test DeleteByBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00001, Function | SmallTest | Level1) +{ + sptr bundleOption = nullptr; + auto ret = advancedNotificationService_->DeleteByBundle(bundleOption); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: DeleteByBundle_00002 + * @tc.desc: Test DeleteByBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00002, Function | SmallTest | Level1) +{ + sptr bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto ret = advancedNotificationService_->DeleteByBundle(bundle); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: DeleteByBundle_00003 + * @tc.desc: Test DeleteByBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00003, Function | SmallTest | Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + TestAddNotification(1, bundle); + auto ret = advancedNotificationService_->DeleteByBundle(bundle); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 0); +} + +/** + * @tc.name: DeleteAll_00001 + * @tc.desc: Test DeleteAll + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DeleteAll_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto ret = advancedNotificationService_->DeleteAll(); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: SetShowBadgeEnabledForBundle_00001 + * @tc.desc: Test SetShowBadgeEnabledForBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, SetShowBadgeEnabledForBundle_00001, Function | SmallTest | Level1) +{ + sptr bundleOption = nullptr; + auto ret = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, true); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); + + bool enabled = false; + ret = advancedNotificationService_->GetShowBadgeEnabledForBundle(bundleOption, enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: SetShowBadgeEnabledForBundle_00002 + * @tc.desc: Test SetShowBadgeEnabledForBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, SetShowBadgeEnabledForBundle_00002, Function | SmallTest | Level1) +{ + sptr bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto ret = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundle, true); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + bool enabled = false; + ret = advancedNotificationService_->GetShowBadgeEnabledForBundle(bundle, enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: GetShowBadgeEnabled_00001 + * @tc.desc: Test GetShowBadgeEnabled + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + bool enabled = false; + auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: GetShowBadgeEnabled_00002 + * @tc.desc: Test GetShowBadgeEnabled + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00002, Function | SmallTest | Level1) +{ + bool enabled = true; + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(enabled, true); +} + +/** + * @tc.name: RequestEnableNotification_00001 + * @tc.desc: Test RequestEnableNotification + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00001, Function | SmallTest | Level1) +{ + std::string deviceId = "deviceId"; + sptr client = nullptr; + AnsDialogHostClient::CreateIfNullptr(client); + client = AnsDialogHostClient::GetInstance(); + sptr callerToken = nullptr; + + auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), false); + ASSERT_EQ(ret, (int)ERR_OK); + + ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); + ASSERT_EQ(ret, (int)ERROR_INTERNAL_ERROR); +} + +/** + * @tc.name: RequestEnableNotification_00002 + * @tc.desc: Test RequestEnableNotification + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00002, Function | SmallTest | Level1) +{ + std::string deviceId = "deviceId"; + sptr client = nullptr; + AnsDialogHostClient::CreateIfNullptr(client); + client = AnsDialogHostClient::GetInstance(); + sptr callerToken = nullptr; + + auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true); + ASSERT_EQ(ret, (int)ERR_OK); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: RequestEnableNotification_00003 + * @tc.desc: Test RequestEnableNotification + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00003, Function | SmallTest | Level1) +{ + std::string deviceId = "deviceId"; + sptr client = nullptr; + AnsDialogHostClient::CreateIfNullptr(client); + client = AnsDialogHostClient::GetInstance(); + sptr callerToken = nullptr; + + auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), false); + ASSERT_EQ(ret, (int)ERR_OK); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + + auto bundle = advancedNotificationService_->GenerateBundleOption(); + NotificationPreferences::GetInstance()->SetHasPoppedDialog(bundle, true); + + ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); + ASSERT_EQ(ret, (int)ERR_ANS_NOT_ALLOWED); + + NotificationPreferences::GetInstance()->SetHasPoppedDialog(bundle, false); + ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: SetNotificationsEnabledForAllBundles_00001 + * @tc.desc: Test SetNotificationsEnabledForAllBundles + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, SetNotificationsEnabledForAllBundles_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + bool enabled = false; + auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles("", enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: SetNotificationsEnabledForSpecialBundle_00001 + * @tc.desc: Test SetNotificationsEnabledForSpecialBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, SetNotificationsEnabledForSpecialBundle_00001, Function | SmallTest | Level1) +{ + sptr bundle = nullptr; + bool enabled = false; + std::string deviceId = "deviceId"; + auto ret = advancedNotificationService_->SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: IsAllowedNotify_00001 + * @tc.desc: Test IsAllowedNotify + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, IsAllowedNotify_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + bool allowed = false; + auto ret = advancedNotificationService_->IsAllowedNotify(allowed); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: IsAllowedNotifyForBundle_00001 + * @tc.desc: Test IsAllowedNotifyForBundle + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, IsAllowedNotifyForBundle_00001, Function | SmallTest | Level1) +{ + bool allowed = false; + sptr bundle = nullptr; + auto ret = advancedNotificationService_->IsAllowedNotifyForBundle(bundle, allowed); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: TriggerLocalLiveView_00001 + * @tc.desc: Test TriggerLocalLiveView + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, TriggerLocalLiveView_00001, Function | SmallTest | Level1) +{ + int notificationId = 1; + sptr bundle = nullptr; + sptr buttonOption = nullptr; + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + MockIsVerfyPermisson(false); + + auto ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); + ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); + + MockIsSystemApp(true); + ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); + + MockIsVerfyPermisson(true); + ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: RemoveNotification_00001 + * @tc.desc: Test RemoveNotification + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveNotification_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + std::string label = "label"; + int notificationId = 1; + auto ret = advancedNotificationService_->RemoveNotification(bundle, notificationId, label, 0); + + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: RemoveNotifications_00001 + * @tc.desc: Test RemoveNotifications + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveNotifications_00001, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + std::vector keys; + int removeReason = 1; + auto ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); + ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); + + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); + + advancedNotificationService_->notificationSvrQueue_ = nullptr; + MockIsVerfyPermisson(true); + ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: RemoveNotifications_00002 + * @tc.desc: Test RemoveNotifications + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveNotifications_00002, Function | SmallTest | Level1) +{ + std::vector keys; + int removeReason = 1; + + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + sptr req = new (std::nothrow) NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + req->SetOwnerUserId(1); + req->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); + req->SetNotificationId(1); + auto record = advancedNotificationService_->MakeNotificationRecord(req, bundle); + auto ret = advancedNotificationService_->AssignToNotificationList(record); + keys.emplace_back(record->notification->GetKey()); + + ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: RemoveNotificationBySlot_00001 + * @tc.desc: Test RemoveNotificationBySlot + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + sptr bundle = nullptr; + sptr slot = nullptr; + auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); + ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); + + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.name: RemoveNotificationBySlot_00002 + * @tc.desc: Test RemoveNotificationBySlot + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | SmallTest | Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + sptr req = new (std::nothrow) NotificationRequest(); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + req->SetOwnerUserId(1); + req->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); + req->SetNotificationId(1); + auto multiLineContent = std::make_shared(); + auto content = std::make_shared(multiLineContent); + req->SetContent(content); + auto record = advancedNotificationService_->MakeNotificationRecord(req, bundle); + auto ret = advancedNotificationService_->AssignToNotificationList(record); + auto slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, + NotificationConstant::DEFAULT_REASON_DELETE); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: NotificationSvrQueue_00001 + * @tc.desc: Test notificationSvrQueue is nullptr + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + + auto ret = advancedNotificationService_->CancelAll(0); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->Delete("", 1); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->CancelGroup("group", 0); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->RemoveGroupByBundle(bundle, "group"); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + bool allowed = false; + ret = advancedNotificationService_->IsSpecialUserAllowedNotify(1, allowed); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->SetNotificationsEnabledByUser(1, false); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->SetBadgeNumber(1, 0); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->SubscribeLocalLiveView(nullptr, nullptr, true); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/* + * @tc.name: SetDistributedEnabledByBundle_0100 + * @tc.desc: test SetDistributedEnabledByBundle with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0100, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType"; + + ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); + ASSERT_EQ(res, ERR_OK); +} + +/* + * @tc.name: SetDistributedEnabledByBundle_0200 + * @tc.desc: test SetDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0200, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType"; + + ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); + ASSERT_EQ(res, ERR_ANS_NON_SYSTEM_APP); +} + +/* + * @tc.name: SetDistributedEnabledByBundle_0300 + * @tc.desc: test SetDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0300, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType"; + + ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); + ASSERT_EQ(res, ERR_ANS_PERMISSION_DENIED); +} + + +/** + * @tc.name: IsDistributedEnabledByBundle_0100 + * @tc.desc: test IsDistributedEnabledByBundle with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType1111"; + bool enable = true; + ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); + ASSERT_EQ(result, ERR_OK); +} + +/** + * @tc.name: IsDistributedEnabledByBundle_0200 + * @tc.desc: test IsDistributedEnabledByBundle with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0200, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType"; + + ErrCode ret = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); + ASSERT_EQ(ret, ERR_OK); + bool enable = false; + ret = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); + ASSERT_EQ(ret, ERR_OK); + ASSERT_EQ(enable, true); +} + +/** + * @tc.name: IsDistributedEnabledByBundle_0300 + * @tc.desc: test IsDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0300, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType1111"; + bool enable = true; + ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); + ASSERT_EQ(result, ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.name: IsDistributedEnabledByBundle_0400 + * @tc.desc: test IsDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0400, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + sptr bundleOption(new NotificationBundleOption("bundleName", 1)); + std::string deviceType = "testDeviceType1111"; + bool enable = true; + ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); + ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.name: DuplicateMsgControl_00001 + * @tc.desc: Test DuplicateMsgControl + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + auto liveViewContent = std::make_shared(); + auto content = std::make_shared(liveViewContent); + request->SetContent(content); + + auto ret = advancedNotificationService_->DuplicateMsgControl(request); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: DuplicateMsgControl_00002 + * @tc.desc: Test DuplicateMsgControl + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00002, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test1"); + auto uniqueKey = request->GenerateUniqueKey(); + advancedNotificationService_->uniqueKeyList_.emplace_back( + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); + + auto ret = advancedNotificationService_->DuplicateMsgControl(request); + ASSERT_EQ(ret, (int)ERR_ANS_DUPLICATE_MSG); +} + +/** + * @tc.name: DuplicateMsgControl_00003 + * @tc.desc: Test DuplicateMsgControl + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00003, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + + auto ret = advancedNotificationService_->DuplicateMsgControl(request); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); +} + +/** + * @tc.name: IsDuplicateMsg_00001 + * @tc.desc: Test IsDuplicateMsg + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + auto uniqueKey = request->GenerateUniqueKey(); + + auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); + ASSERT_EQ(ret, false); +} + +/** + * @tc.name: IsDuplicateMsg_00002 + * @tc.desc: Test IsDuplicateMsg + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00002, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + auto uniqueKey = request->GenerateUniqueKey(); + advancedNotificationService_->uniqueKeyList_.emplace_back( + std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); + + auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); + ASSERT_EQ(ret, true); +} + +/** + * @tc.name: RemoveExpiredUniqueKey_00001 + * @tc.desc: Test RemoveExpiredUniqueKey + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + auto uniqueKey = request->GenerateUniqueKey(); + advancedNotificationService_->uniqueKeyList_.emplace_back( + std::make_pair(std::chrono::steady_clock::now() - std::chrono::hours(24), uniqueKey)); + + sleep(1); + ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); + advancedNotificationService_->RemoveExpiredUniqueKey(); + ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 0); +} + +/* + * @tc.name: SetSmartReminderEnabled_0100 + * @tc.desc: test SetSmartReminderEnabled with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0100, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); + ASSERT_EQ(res, ERR_OK); +} + +/* + * @tc.name: SetSmartReminderEnabled_0200 + * @tc.desc: test SetSmartReminderEnabled with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0200, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); + ASSERT_EQ(res, ERR_ANS_NON_SYSTEM_APP); +} + +/* + * @tc.name: SetSmartReminderEnabled_0300 + * @tc.desc: test SetSmartReminderEnabled with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0300, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); + ASSERT_EQ(res, ERR_ANS_PERMISSION_DENIED); +} + + +/** + * @tc.name: IsSmartReminderEnabled_0100 + * @tc.desc: test IsSmartReminderEnabled with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + bool enable = true; + ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); + ASSERT_EQ(result, ERR_OK); +} + +/** + * @tc.name: IsSmartReminderEnabled_0200 + * @tc.desc: test IsSmartReminderEnabled with parameters + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0200, TestSize.Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + ErrCode ret = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); + ASSERT_EQ(ret, ERR_OK); + bool enable = false; + ret = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType", enable); + ASSERT_EQ(ret, ERR_OK); + ASSERT_EQ(enable, true); +} + +/** + * @tc.name: IsSmartReminderEnabled_0300 + * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0300, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + bool enable = true; + ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); + ASSERT_EQ(result, ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.name: IsSmartReminderEnabled_0400 + * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. + * @tc.type: FUNC + */ +HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0400, TestSize.Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + bool enable = true; + ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); + ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.name: PublishRemoveDuplicateEvent_00001 + * @tc.desc: Test PublishRemoveDuplicateEvent + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + request->SetNotificationId(1); + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + + auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: PublishRemoveDuplicateEvent_00002 + * @tc.desc: Test PublishRemoveDuplicateEvent + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00002, Function | SmallTest | Level1) +{ + std::shared_ptr record= nullptr; + auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: PublishRemoveDuplicateEvent_00003 + * @tc.desc: Test PublishRemoveDuplicateEvent + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00003, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + request->SetAppMessageId("test2"); + request->SetNotificationId(1); + request->SetIsAgentNotification(true); + auto normalContent = std::make_shared(); + auto content = std::make_shared(normalContent); + request->SetContent(content); + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + + auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: CanPopEnableNotificationDialog_001 + * @tc.desc: Test CanPopEnableNotificationDialog + * @tc.type: FUNC + * @tc.require: issue + */ +HWTEST_F(AnsPublishServiceTest, CanPopEnableNotificationDialog_001, Function | SmallTest | Level1) +{ + sptr callback = nullptr; + bool canPop = false; + std::string bundleName = ""; + ErrCode result = advancedNotificationService_->CanPopEnableNotificationDialog(callback, canPop, bundleName); + ASSERT_EQ(result, ERROR_INTERNAL_ERROR); +} + +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp b/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp new file mode 100644 index 000000000..106779549 --- /dev/null +++ b/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp @@ -0,0 +1,76 @@ +/* + * 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 +#define private public +#define protected public +#include "advanced_notification_service_ability.h" + +using namespace testing::ext; + +namespace OHOS { +namespace Notification { +class AdvancedNotificationServiceAbilityTest : public testing::Test { +public: + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.number : AdvancedNotificationServiceAbilityTest_00100 + * @tc.name : ANS_AdvancedNotificationServiceAbility_0100 + * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + */ +HWTEST_F( + AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00100, Function | SmallTest | Level1) +{ + int32_t systemAbilityId = 1; + bool runOnCreate = true; + AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); +} + +/** + * @tc.number : AdvancedNotificationServiceAbilityTest_00200 + * @tc.name : ANS_AdvancedNotificationServiceAbility_0200 + * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + */ +HWTEST_F( + AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00200, Function | SmallTest | Level1) +{ + int32_t systemAbilityId = 1; + bool runOnCreate = true; + AdvancedNotificationServiceAbility test(systemAbilityId, runOnCreate); + test.OnStart(); +} + +/** + * @tc.number : AdvancedNotificationServiceAbilityTest_00300 + * @tc.name : ANS_AdvancedNotificationServiceAbility_0300 + * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + */ +HWTEST_F( + AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00300, Function | SmallTest | Level1) +{ + int32_t systemAbilityId = 1; + bool runOnCreate = true; + AdvancedNotificationServiceAbility test(systemAbilityId, runOnCreate); + test.OnStop(); + test.OnStart(); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp b/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp new file mode 100644 index 000000000..4a0d9f06b --- /dev/null +++ b/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp @@ -0,0 +1,1226 @@ +/* + * Copyright (c) 2023-2024 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include "gtest/gtest.h" + +#define private public + +#include "advanced_notification_service.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_subscriber_listener.h" +#include "ans_ut_constant.h" +#include "iremote_object.h" +#include "want_agent_info.h" +#include "want_agent_helper.h" +#include "want_params.h" +#include "mock_ipc_skeleton.h" +#include "notification_preferences.h" +#include "notification_constant.h" +#include "notification_record.h" +#include "notification_subscriber.h" +#include "refbase.h" + +extern void MockVerifyNativeToken(bool mockRet); +extern void MockVerifyShellToken(bool mockRet); +extern void MockGetDistributedEnableInApplicationInfo(bool mockRet, uint8_t mockCase = 0); +extern void MockGetOsAccountLocalIdFromUid(bool mockRet, uint8_t mockCase = 0); + +using namespace testing::ext; +using namespace OHOS::Media; +using namespace OHOS::Security::AccessToken; + +namespace OHOS { +namespace Notification { +extern void MockIsVerfyPermisson(bool isVerify); +extern void MockGetTokenTypeFlag(ATokenTypeEnum mockRet); +extern void MockIsSystemApp(bool isSystemApp); +extern void MockDistributedNotificationEnabled(bool isEnable); +extern void MockIsNonBundleName(bool isNonBundleName); + +class AnsBranchTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + static void InitNotificationRecord(std::shared_ptr &record, + const NotificationLiveViewContent::LiveViewStatus &status); +private: + void TestAddSlot(NotificationConstant::SlotType type); + +private: + static sptr advancedNotificationService_; +}; + +sptr AnsBranchTest::advancedNotificationService_ = nullptr; + +void AnsBranchTest::SetUpTestCase() {} + +void AnsBranchTest::TearDownTestCase() {} + +void AnsBranchTest::SetUp() +{ + GTEST_LOG_(INFO) << "SetUp start"; + + advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_->CancelAll(0); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + MockIsSystemApp(true); + GTEST_LOG_(INFO) << "SetUp end"; +} + +void AnsBranchTest::TearDown() +{ + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +inline void SleepForFC() +{ + // For ANS Flow Control + std::this_thread::sleep_for(std::chrono::seconds(1)); +} + +class TestAnsSubscriber : public NotificationSubscriber { +public: + void OnDied() override + {} + void OnConnected() override + {} + void OnDisconnected() override + {} + void OnUpdate(const std::shared_ptr &sortingMap) override + {} + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override + {} + void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int32_t deleteReason) override + {} + void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override + {} + void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} + void OnBadgeChanged(const std::shared_ptr &badgeData) override + {} + void OnBadgeEnabledChanged(const sptr &callbackData) override + {} + void OnBatchCanceled(const std::vector> + &requestList, const std::shared_ptr &sortingMap, int32_t deleteReason) override + {} +}; + +void AnsBranchTest::TestAddSlot(NotificationConstant::SlotType type) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + std::vector> slots; + sptr slot = new NotificationSlot(type); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); +} + +/** + * @tc.number : AnsBranchTest_222000 + * @tc.name : PrepareNotificationRequest_1000 + * @tc.desc : Test PrepareNotificationRequest function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_222000, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + + req->SetIsAgentNotification(true); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_223000 + * @tc.name : PrepareNotificationRequest_2000 + * @tc.desc : Test PrepareNotificationRequest function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_223000, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + + req->SetIsAgentNotification(true); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_224000 + * @tc.name : Publish_1000 + * @tc.desc : Test Publish function req is false. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_224000, Function | SmallTest | Level1) +{ + std::string label = "publish's label"; + ASSERT_EQ(advancedNotificationService_->Publish(label, nullptr), ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AnsBranchTest_225000 + * @tc.name : CancelAsBundle_1000 + * @tc.desc : Test CancelAsBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_225000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + int32_t notificationId = 1; + std::string representativeBundle = "RepresentativeBundle"; + int32_t userId = 1; + ASSERT_EQ(advancedNotificationService_->CancelAsBundle( + notificationId, representativeBundle, userId), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_226000 + * @tc.name : CancelAsBundle_2000 + * @tc.desc : Test CancelAsBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_226000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + int32_t notificationId = 1; + std::string representativeBundle = "RepresentativeBundle"; + int32_t userId = 1; + ASSERT_EQ(advancedNotificationService_->CancelAsBundle( + notificationId, representativeBundle, userId), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_227000 + * @tc.name : AddSlots_2000 + * @tc.desc : Test AddSlots function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_227000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_228000 + * @tc.name : Delete_1000 + * @tc.desc : Test Delete function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_228000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + const std::string key = "key"; + ASSERT_EQ(advancedNotificationService_->Delete( + key, NotificationConstant::CANCEL_REASON_DELETE), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_229000 + * @tc.name : DeleteByBundle_1000 + * @tc.desc : Test DeleteByBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_229000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_230000 + * @tc.name : DeleteByBundle_2000 + * @tc.desc : Test DeleteByBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_230000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + ASSERT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_231000 + * @tc.name : DeleteAll_1000 + * @tc.desc : Test DeleteAll function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_231000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_232000 + * @tc.name : GetSlotsByBundle_1000 + * @tc.desc : Test GetSlotsByBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_232000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + std::vector> slots; + ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_233000 + * @tc.name : GetSlotsByBundle_2000 + * @tc.desc : Test GetSlotsByBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_233000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::vector> slots; + ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_234000 + * @tc.name : UpdateSlots_1000 + * @tc.desc : Test UpdateSlots function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_234000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ(advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_235000 + * @tc.name : UpdateSlots_1000 + * @tc.desc : Test UpdateSlots function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_235000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ(advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_236000 + * @tc.name : SetShowBadgeEnabledForBundle_1000 + * @tc.desc : Test SetShowBadgeEnabledForBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_236000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_237000 + * @tc.name : GetShowBadgeEnabledForBundle_1000 + * @tc.desc : Test GetShowBadgeEnabledForBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_237000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + bool allow = false; + ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_238000 + * @tc.name : GetShowBadgeEnabledForBundle_2000 + * @tc.desc : Test GetShowBadgeEnabledForBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_238000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool allow = false; + ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_239000 + * @tc.name : Subscribe_1000 + * @tc.desc : Test Subscribe function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_239000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + ASSERT_EQ(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_240000 + * @tc.name : Subscribe_1000 + * @tc.desc : Test Subscribe function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_240000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + ASSERT_EQ(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_241000 + * @tc.name : Unsubscribe_1000 + * @tc.desc : Test Unsubscribe function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_241000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + ASSERT_EQ(advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), info), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_242000 + * @tc.name : GetAllActiveNotifications_1000 + * @tc.desc : Test GetAllActiveNotifications function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_242000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::vector> allNotifications; + ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(allNotifications), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_243000 + * @tc.name : GetSpecialActiveNotifications_1000 + * @tc.desc : Test GetSpecialActiveNotifications function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_243000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + std::vector keys; + std::vector> specialActiveNotifications; + ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications( + keys, specialActiveNotifications), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_244000 + * @tc.name : GetSpecialActiveNotifications_2000 + * @tc.desc : Test GetSpecialActiveNotifications function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_244000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::vector keys; + std::vector> specialActiveNotifications; + ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications( + keys, specialActiveNotifications), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_245000 + * @tc.name : SetNotificationsEnabledForAllBundles_2000 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_245000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles( + std::string(), true), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_246000 + * @tc.name : SetNotificationsEnabledForAllBundles_1000 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_246000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles( + std::string(), true), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_247000 + * @tc.name : SetNotificationsEnabledForSpecialBundle_1000 + * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_247000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), false), + ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_248000 + * @tc.name : IsAllowedNotify_1000 + * @tc.desc : Test IsAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_248000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + bool allowed = false; + ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(allowed), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_249000 + * @tc.name : IsAllowedNotify_2000 + * @tc.desc : Test IsAllowedNotify function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_249000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool allowed = false; + ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(allowed), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_250000 + * @tc.name : GetAppTargetBundle_1000 + * @tc.desc : Test GetAppTargetBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_250000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + sptr targetBundle(nullptr); + bundleOption->SetBundleName("test"); + ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_251000 + * @tc.name : IsSpecialBundleAllowedNotify_1000 + * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_251000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + bool allowed = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_252000 + * @tc.name : IsSpecialBundleAllowedNotify_2000 + * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_252000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool allowed = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_254000 + * @tc.name : IsSpecialBundleAllowedNotify_4000 + * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_254000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(true); + + MockIsNonBundleName(true); + bool allowed = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_INVALID_BUNDLE); +} + +/** + * @tc.number : AnsBranchTest_255000 + * @tc.name : RemoveNotification_1000 + * @tc.desc : Test RemoveNotification function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_255000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + int32_t notificationId = 1; + std::string label = "testRemove"; + auto result = advancedNotificationService_->RemoveNotification( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), + notificationId, label, NotificationConstant::CANCEL_REASON_DELETE); + ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_256000 + * @tc.name : RemoveAllNotifications_1000 + * @tc.desc : Test RemoveAllNotifications function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_256000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->RemoveAllNotifications(bundleOption), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_257000 + * @tc.name : GetSlotNumAsBundle_1000 + * @tc.desc : Test GetSlotNumAsBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_257000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + uint64_t num = 1; + ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_258000 + * @tc.name : GetSlotNumAsBundle_2000 + * @tc.desc : Test GetSlotNumAsBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_258000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + uint64_t num = 1; + ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_259000 + * @tc.name : RemoveGroupByBundle_2000 + * @tc.desc : Test RemoveGroupByBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_259000, Function | SmallTest | Level1) +{ + MockVerifyNativeToken(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + std::string groupName = "group"; + ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_260000 + * @tc.name : SetDoNotDisturbDate_1000 + * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_260000, Function | SmallTest | Level1) +{ + MockVerifyNativeToken(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_261000 + * @tc.name : SetDoNotDisturbDate_2000 + * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_261000, Function | SmallTest | Level1) +{ + MockVerifyNativeToken(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_262000 + * @tc.name : DoesSupportDoNotDisturbMode_1000 + * @tc.desc : Test DoesSupportDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_262000, Function | SmallTest | Level1) +{ + MockIsSystemApp(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + + bool doesSupport = true; + ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_263000 + * @tc.name : DoesSupportDoNotDisturbMode_2000 + * @tc.desc : Test DoesSupportDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_263000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool doesSupport = true; + ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_264000 + * @tc.name : EnableDistributed_1000 + * @tc.desc : Test EnableDistributed function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_264000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + bool enabled = true; + sptr bundleOption = + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_284000 + * @tc.name : EnableDistributed_2000 + * @tc.desc : Test EnableDistributed function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_284000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool enabled = true; + sptr bundleOption = + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle( + bundleOption, enabled), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle( + bundleOption, enabled), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_265000 + * @tc.name : GetDeviceRemindType_1000 + * @tc.desc : Test GetDeviceRemindType function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_265000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; + ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_266000 + * @tc.name : GetDeviceRemindType_2000 + * @tc.desc : Test GetDeviceRemindType function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_266000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; + ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_267000 + * @tc.name : IsSpecialUserAllowedNotify_1000 + * @tc.desc : Test IsSpecialUserAllowedNotify function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_267000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + int32_t userId = 3; + bool allowed = true; + bool enable = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify( + userId, allowed), (int)ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser( + userId, enable), (int)ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_267100 + * @tc.name : IsSpecialUserAllowedNotify_1000 + * @tc.desc : Test IsSpecialUserAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_267100, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + int32_t userId = 3; + bool allowed = true; + bool enable = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify( + userId, allowed), (int)ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser( + userId, enable), (int)ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_268000 + * @tc.name : SetDoNotDisturbDate_1000 + * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_268000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + int32_t userId = 3; + sptr date = nullptr; + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_269000 + * @tc.name : SetDoNotDisturbDate_2000 + * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_269000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + int32_t userId = 3; + sptr date = nullptr; + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_270000 + * @tc.name : SetEnabledForBundleSlot_1000 + * @tc.desc : Test SetEnabledForBundleSlot function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_270000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + bool enabled = false; + bool isForceControl = false; + auto result = advancedNotificationService_->SetEnabledForBundleSlot( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), + NotificationConstant::SlotType::SOCIAL_COMMUNICATION, enabled, false); + + ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); + auto result1 = advancedNotificationService_->GetEnabledForBundleSlot( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), + NotificationConstant::SlotType::SOCIAL_COMMUNICATION, enabled); + ASSERT_EQ(result1, ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_271000 + * @tc.name : SetEnabledForBundleSlot_1000 + * @tc.desc : Test SetEnabledForBundleSlot function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_271000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockVerifyShellToken(false); + + std::string cmd = "CMD"; + std::string bundle = "Bundle"; + int32_t userId = 4; + std::vector dumpInfo; + ASSERT_EQ(advancedNotificationService_->ShellDump( + cmd, bundle, userId, 0, dumpInfo), (int)ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_272000 + * @tc.name : SetSyncNotificationEnabledWithoutApp_1000 + * @tc.desc : Test SetSyncNotificationEnabledWithoutApp function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_272000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + + int32_t userId = 3; + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp( + userId, enabled), ERR_ANS_NON_SYSTEM_APP); + ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp( + userId, enabled), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_273000 + * @tc.name : SetSyncNotificationEnabledWithoutApp_2000 + * @tc.desc : Test SetSyncNotificationEnabledWithoutApp function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_273000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + int32_t userId = 3; + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp( + userId, enabled), ERR_ANS_PERMISSION_DENIED); + ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp( + userId, enabled), ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_274000 + * @tc.name : EnableDistributedByBundle_3000 + * @tc.desc : Test EnableDistributedByBundle function return ERR_ANS_NON_SYSTEM_APP. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_274000, Function | SmallTest | Level1) +{ + MockGetDistributedEnableInApplicationInfo(false, 2); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + bool enabled = true; + sptr bundleOption = + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle( + bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); +} + +/** + * @tc.number : AnsBranchTest_275000 + * @tc.name : EnableDistributedSelf_2000 + * @tc.desc : Test EnableDistributedSelf function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_275000, Function | SmallTest | Level1) +{ + MockDistributedNotificationEnabled(false); + MockIsNonBundleName(false); + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), (int)ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.number : AnsBranchTest_276000 + * @tc.name : IsDistributedEnableByBundle_3000 + * @tc.desc : Test IsDistributedEnableByBundle function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_276000, Function | SmallTest | Level1) +{ + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + MockVerifyNativeToken(true); + MockGetDistributedEnableInApplicationInfo(true, 2); + sptr bundleOption = new NotificationBundleOption( + TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + bool enabled = false; + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); +} + +/** + * @tc.number : AnsBranchTest_277000 + * @tc.name : DoDistributedPublish_3000 + * @tc.desc : Test DoDistributedPublish function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_277000, Function | SmallTest | Level1) +{ + MockGetDistributedEnableInApplicationInfo(false, 2); + MockGetOsAccountLocalIdFromUid(false, 1); + MockDistributedNotificationEnabled(false); + sptr bundleOption = new NotificationBundleOption( + TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + std::shared_ptr record = nullptr; + ASSERT_EQ(advancedNotificationService_->DoDistributedPublish(bundleOption, record), ERR_OK); +} + +/** + * @tc.number : AnsBranchTest_278000 + * @tc.name : GetDistributedEnableInApplicationInfo_3000 + * @tc.desc : Test GetDistributedEnableInApplicationInfo function return ERR_ANS_PERMISSION_DENIED. + * @tc.require : #I6P8UI + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_278000, Function | SmallTest | Level1) +{ + MockGetOsAccountLocalIdFromUid(false, 3); + sptr bundleOption = new NotificationBundleOption( + TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + bool enabled = false;; + ASSERT_EQ(advancedNotificationService_->GetDistributedEnableInApplicationInfo( + bundleOption, enabled), ERR_ANS_INVALID_PARAM); +} + +void AnsBranchTest::InitNotificationRecord(std::shared_ptr &record, + const NotificationLiveViewContent::LiveViewStatus &status) +{ + NotificationRequest notificationRequest; + notificationRequest.SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + auto liveContent = std::make_shared(); + liveContent->SetLiveViewStatus(status); + auto content = std::make_shared(liveContent); + notificationRequest.SetContent(content); + + record->request = sptr::MakeSptr(notificationRequest); + record->notification = new (std::nothrow) Notification(record->request); +} + +/** + * @tc.number : AnsBranchTest_279000 + * @tc.name : UpdateNotificationTimerInfo_0001 + * @tc.desc : Check set update and finish timer when create notification request + * @tc.require : issue + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_279000, Function | SmallTest | Level1) +{ + using Status = NotificationLiveViewContent::LiveViewStatus; + auto record = std::make_shared(); + InitNotificationRecord(record, Status::LIVE_VIEW_CREATE); + ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); + ASSERT_EQ(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); + auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); + ASSERT_EQ(result, ERR_OK); + EXPECT_NE(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); + EXPECT_NE(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); +} + +/** + * @tc.number : AnsBranchTest_279001 + * @tc.name : UpdateNotificationTimerInfo_0002 + * @tc.desc : Check set update and finish timer when update notification request + * @tc.require : issue + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_279001, Function | SmallTest | Level1) +{ + using Status = NotificationLiveViewContent::LiveViewStatus; + auto record = std::make_shared(); + InitNotificationRecord(record, Status::LIVE_VIEW_INCREMENTAL_UPDATE); + record->notification->SetUpdateTimer(2); + record->notification->SetFinishTimer(3); + auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); + ASSERT_EQ(result, ERR_OK); + /* finish timer not change, but update timer changed */ + EXPECT_NE(record->notification->GetUpdateTimer(), 2); + ASSERT_EQ(record->notification->GetFinishTimer(), 3); +} + +/** + * @tc.number : AnsBranchTest_279002 + * @tc.name : UpdateNotificationTimerInfo_0003 + * @tc.desc : Check cancel update and finish timer when end notification request + * @tc.require : issue + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_279002, Function | SmallTest | Level1) +{ + using Status = NotificationLiveViewContent::LiveViewStatus; + auto record = std::make_shared(); + InitNotificationRecord(record, Status::LIVE_VIEW_END); + record->notification->SetUpdateTimer(2); + record->notification->SetFinishTimer(3); + + auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); + ASSERT_EQ(result, ERR_OK); + /* finish timer not change, but update timer changed */ + ASSERT_EQ(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); + ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); +} + +/** + * @tc.number : AnsBranchTest_285000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_1000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_285000, Function | SmallTest | Level1) +{ + MockIsSystemApp(false); + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), -1); +} + +/** + * @tc.number : AnsBranchTest_286000 + * @tc.name : IsNeedSilentInDoNotDisturbMode_2000 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. + */ +HWTEST_F(AnsBranchTest, AnsBranchTest_286000, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); + MockIsVerfyPermisson(false); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( + phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_test.cpp b/services/reminder/test/unittest/advanced_notification_service_test.cpp new file mode 100644 index 000000000..849e0379a --- /dev/null +++ b/services/reminder/test/unittest/advanced_notification_service_test.cpp @@ -0,0 +1,3774 @@ +/* + * Copyright (c) 2021-2024 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 "errors.h" +#include "notification_content.h" +#include "notification_record.h" +#include "notification_request.h" +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include + +#define private public + +#include "advanced_notification_service.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_notification.h" +#include "ans_ut_constant.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "iremote_object.h" +#include "mock_ipc_skeleton.h" +#include "notification_preferences.h" +#include "notification_subscriber.h" +#include "notification_subscriber_manager.h" +#include "mock_push_callback_stub.h" +#include "system_event_observer.h" +#include "notification_constant.h" +#include "want_agent_info.h" +#include "want_agent_helper.h" +#include "want_params.h" +#include "bundle_manager_helper.h" + +extern void MockIsOsAccountExists(bool mockRet); + +using namespace testing::ext; +using namespace OHOS::Media; + +namespace OHOS { +namespace Notification { +extern void MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum mockRet); +extern void MockIsSystemApp(bool isSystemApp); +extern void MockIsNonBundleName(bool isNonBundleName); +extern void MockIsVerfyPermisson(bool isVerify); + +class AdvancedNotificationServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +private: + void TestAddSlot(NotificationConstant::SlotType type); + void TestAddLiveViewSlot(bool isForceControl); + void MockSystemApp(); + +private: + static sptr advancedNotificationService_; +}; + +sptr AdvancedNotificationServiceTest::advancedNotificationService_ = nullptr; + +void AdvancedNotificationServiceTest::SetUpTestCase() +{ + MockIsOsAccountExists(true); +} + +void AdvancedNotificationServiceTest::TearDownTestCase() {} + +void AdvancedNotificationServiceTest::SetUp() +{ + GTEST_LOG_(INFO) << "SetUp start"; + + advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); + NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_->CancelAll(0); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + GTEST_LOG_(INFO) << "SetUp end"; +} + +void AdvancedNotificationServiceTest::TearDown() +{ + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +inline void SleepForFC() +{ + // For ANS Flow Control + std::this_thread::sleep_for(std::chrono::seconds(1)); +} + +class TestAnsSubscriber : public NotificationSubscriber { +public: + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override + {} + void OnConnected() override + {} + void OnDisconnected() override + {} + void OnDied() override + {} + void OnUpdate(const std::shared_ptr &sortingMap) override + {} + void OnBadgeChanged(const std::shared_ptr &badgeData) override + {} + void OnBadgeEnabledChanged( + const sptr &callbackData) override + {} + void OnEnabledNotificationChanged( + const std::shared_ptr &callbackData) override + {} + void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int32_t deleteReason) override + {} + void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} + void OnBatchCanceled(const std::vector> + &requestList, const std::shared_ptr &sortingMap, int32_t deleteReason) override + {} +}; + +void AdvancedNotificationServiceTest::TestAddSlot(NotificationConstant::SlotType type) +{ + MockSystemApp(); + std::vector> slots; + sptr slot = new NotificationSlot(type); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); +} + +void AdvancedNotificationServiceTest::MockSystemApp() +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); +} + +void AdvancedNotificationServiceTest::TestAddLiveViewSlot(bool isForceControl) +{ + MockSystemApp(); + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::LIVE_VIEW); + slot->SetForceControl(isForceControl); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); +} + + +/** + * @tc.number : AdvancedNotificationServiceTest_01600 + * @tc.name : ANS_GetSlot_0200 + * @tc.desc : Test GetSlots function when add two identical data + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, Function | SmallTest | Level1) +{ + MockSystemApp(); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + std::vector> slotsResult; + advancedNotificationService_->AddSlots(slots); + advancedNotificationService_->GetSlots(slotsResult); + ASSERT_EQ((int)slots.size(), 2); + ASSERT_EQ((int)slotsResult.size(), 1); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01800 + * @tc.name : ANS_SetNotificationBadgeNum_0100 + * @tc.desc : Test SetNotificationBadgeNum function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_01900 + * @tc.name : ANS_GetBundleImportance_0100 + * @tc.desc : Test GetBundleImportance function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + int importance; + ASSERT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02200 + * @tc.name : ANS_UpdateSlots_0100 + * @tc.desc : Test UpdateSlots function when no slot + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02300 + * @tc.name : ANS_UpdateSlots_0200 + * @tc.desc : Test UpdateSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02700 + * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02800 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test GetShowBadgeEnabledForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); + bool allow = false; + ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_02900 + * @tc.name : ANS_GetActiveNotifications_0100 + * @tc.desc : Test GetActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, Function | SmallTest | Level1) +{ + std::vector> notifications; + ASSERT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications, 0), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03000 + * @tc.name : ANS_SetTargetDeviceStatus_0100 + * @tc.desc : Test SetTargetDeviceStatus function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03000, Function | SmallTest | Level1) +{ + const std::string device = "current"; + const uint32_t status = 1; + ASSERT_EQ((int)advancedNotificationService_->SetTargetDeviceStatus(device, status), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03100 + * @tc.name : ANS_ClearAllNotificationGroupInfo_0100 + * @tc.desc : Test ClearAllNotificationGroupInfo function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, Function | SmallTest | Level1) +{ + const std::string localSwitch = "current"; + advancedNotificationService_->ClearAllNotificationGroupInfo(localSwitch); + EXPECT_TRUE(advancedNotificationService_ != nullptr); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03200 + * @tc.name : ANS_UpdateUnifiedGroupInfo_0100 + * @tc.desc : Test UpdateUnifiedGroupInfo function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, Function | SmallTest | Level1) +{ + const std::string key = "key"; + std::shared_ptr groupInfo; + advancedNotificationService_->UpdateUnifiedGroupInfo(key, groupInfo); + EXPECT_TRUE(advancedNotificationService_ != nullptr); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03300 + * @tc.name : ANS_RemoveSystemLiveViewNotificationsOfSa_0100 + * @tc.desc : Test RemoveSystemLiveViewNotificationsOfSa function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03300, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + int32_t uid = 0; + ASSERT_EQ((int)advancedNotificationService_->RemoveSystemLiveViewNotificationsOfSa(uid), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03400 + * @tc.name : ANS_IsAllowedNotifyForBundle_0100 + * @tc.desc : Test IsAllowedNotifyForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, Function | SmallTest | Level1) +{ + bool allowed = false; + sptr bundleOption = new (std::nothrow) NotificationBundleOption(); + auto ret = advancedNotificationService_->IsAllowedNotifyForBundle(bundleOption, allowed); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03500 + * @tc.name : ANS_CancelAsBundleWithAgent_0100 + * @tc.desc : Test CancelAsBundleWithAgent function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) +{ + int32_t id = 0; + sptr bundleOption = new (std::nothrow) NotificationBundleOption(); + auto ret = advancedNotificationService_->CancelAsBundleWithAgent(bundleOption, id); + ASSERT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03600 + * @tc.name : ANS_AddDoNotDisturbProfiles_0100 + * @tc.desc : Test AddDoNotDisturbProfiles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03600, Function | SmallTest | Level1) +{ + sptr date = nullptr; + std::vector> profiles = { date }; + auto ret = advancedNotificationService_->AddDoNotDisturbProfiles(profiles); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03700 + * @tc.name : ANS_Delete_0100 + * @tc.desc : Test Delete function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, Function | SmallTest | Level1) +{ + const std::string key = "key"; + ASSERT_EQ((int)advancedNotificationService_->Delete(key, NotificationConstant::CANCEL_REASON_DELETE), + (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03800 + * @tc.name : ANS_DeleteByBundle_0100 + * @tc.desc : Test DeleteByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), + ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_03900 + * @tc.name : ANS_DeleteAll_0100 + * @tc.desc : Test DeleteAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04000 + * @tc.name : ANS_GetSlotsByBundle_0100 + * @tc.desc : Test GetSlotsByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::vector> slots; + ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + ERR_OK); + ASSERT_EQ(slots.size(), (size_t)1); +} + + +/** + * @tc.number : AdvancedNotificationServiceTest_04200 + * @tc.name : ANS_AddDoNotDisturbProfiles_0100 + * @tc.desc : Test AddDoNotDisturbProfiles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04200, Function | SmallTest | Level1) +{ + sptr date = nullptr; + std::vector> profiles = { date }; + auto ret = advancedNotificationService_->RemoveDoNotDisturbProfiles(profiles); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04300 + * @tc.name : ANS_AddDoNotDisturbProfiles_0100 + * @tc.desc : Test AddDoNotDisturbProfiles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, Function | SmallTest | Level1) +{ + sptr request(new NotificationRequest()); + std::string bundleName = "bundleName"; + advancedNotificationService_->SetAgentNotification(request, bundleName); + EXPECT_TRUE(advancedNotificationService_ != nullptr); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_04400 + * @tc.name : ANS_AddDoNotDisturbProfiles_0100 + * @tc.desc : Test AddDoNotDisturbProfiles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04400, Function | SmallTest | Level1) +{ + std::string enable = "enable"; + auto ret = advancedNotificationService_->GetUnifiedGroupInfoFromDb(enable); + ASSERT_EQ(ret, -1); +} + + +/** + * @tc.number : AdvancedNotificationServiceTest_05100 + * @tc.name : ANS_AddSlots_0100 + * @tc.desc : Test AddSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) +{ + MockSystemApp(); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + slots.push_back(slot1); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05200 + * @tc.name : ANS_RemoveSlotByType_0100 + * @tc.desc : Test RemoveSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ(advancedNotificationService_->RemoveSlotByType(NotificationConstant::OTHER), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05300 + * @tc.name : ANS_RemoveSlotByType_0200 + * @tc.desc : Test RemoveSlotByType function when no type + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ((int)advancedNotificationService_->RemoveSlotByType(NotificationConstant::CUSTOM), 0); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05600 + * @tc.name : ANS_GetSlot_0100 + * @tc.desc : Test GetSlot function for data + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) +{ + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + advancedNotificationService_->AddSlots(slots); + ASSERT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), ERR_OK); + ASSERT_EQ(slot->GetName(), slot0->GetName()); + ASSERT_EQ(slot->GetId(), slot0->GetId()); + ASSERT_EQ(slot->GetLevel(), slot0->GetLevel()); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_05900 + * @tc.name : ANS_SetNotificationBadgeNum_0100 + * @tc.desc : Test SetNotificationBadgeNum function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05900, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06000 + * @tc.name : ANS_GetBundleImportance_0100 + * @tc.desc : Test GetBundleImportance function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06000, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + int importance = 0; + ASSERT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06300 + * @tc.name : ANS_UpdateSlots_0100 + * @tc.desc : Test UpdateSlots function when no slot + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06400 + * @tc.name : ANS_UpdateSlots_0200 + * @tc.desc : Test UpdateSlots function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06400, Function | SmallTest | Level1) +{ + std::vector> slots; + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); + slots.push_back(slot0); + ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06800 + * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06800, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption("", SYSTEM_APP_UID), true), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_06900 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, Function | SmallTest | Level1) +{ + bool allow = false; + ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07000 + * @tc.name : ANS_GetActiveNotifications_0100 + * @tc.desc : Test GetActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07000, Function | SmallTest | Level1) +{ + std::vector> notifications; + ASSERT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications, 0), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07800 + * @tc.name : ANS_Delete_0100 + * @tc.desc : Test Delete function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07800, Function | SmallTest | Level1) +{ + const std::string key = "key"; + ASSERT_EQ((int)advancedNotificationService_->Delete(key, NotificationConstant::CANCEL_REASON_DELETE), + (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_07900 + * @tc.name : ANS_DeleteByBundle_0100 + * @tc.desc : Test DeleteByBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07900, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->DeleteByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), + ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08000 + * @tc.name : ANS_DeleteAll_0100 + * @tc.desc : Test DeleteAll function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08000, Function | SmallTest | Level1) +{ + ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08300 + * @tc.name : ANS_Subscribe_0100 + * @tc.desc : Test Subscribe function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08300, Function | SmallTest | Level1) +{ + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_NE((int)advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); + ASSERT_EQ((int)advancedNotificationService_->Subscribe(nullptr, info), (int)ERR_ANS_INVALID_PARAM); + EXPECT_NE((int)advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), nullptr), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08600 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0200 + * @tc.desc : Test GetShowBadgeEnabledForBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ((int)advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); + bool allow = false; + ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), + (int)ERR_OK); + EXPECT_TRUE(allow); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_08700 + * @tc.name : ANS_GetSlotByType_0100 + * @tc.desc : Test GetSlotByType function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08700, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + ASSERT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), (int)ERR_OK); + ASSERT_EQ(slot->GetType(), NotificationConstant::SlotType::OTHER); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09000 + * @tc.name : ANS_GetAllActiveNotifications_0100 + * @tc.desc : Test GetAllActiveNotifications function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09000, Function | SmallTest | Level1) +{ + std::vector> notifications; + ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(notifications), ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09200 + * @tc.name : ANS_SetNotificationsEnabledForAllBundles_0200 + * @tc.desc : Test SetNotificationsEnabledForAllBundles function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09200, Function | SmallTest | Level1) +{ + ASSERT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09300 + * @tc.name : ANS_SetNotificationsEnabledForSpecialBundle_0100 + * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::OTHER); + std::vector> notifications; + ASSERT_EQ((int)advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09500 + * @tc.name : ANS_IsAllowedNotify_0100 + * @tc.desc : Test IsAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09500, Function | SmallTest | Level1) +{ + ASSERT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); + bool allowed = false; + ASSERT_EQ((int)advancedNotificationService_->IsAllowedNotify(allowed), (int)ERR_OK); + EXPECT_TRUE(allowed); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09600 + * @tc.name : ANS_IsAllowedNotifySelf_0100 + * @tc.desc : Test IsAllowedNotifySelf function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, Function | SmallTest | Level1) +{ + MockSystemApp(); + ASSERT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); + bool allowed = false; + ASSERT_EQ((int)advancedNotificationService_->IsAllowedNotifySelf(allowed), (int)ERR_OK); + EXPECT_FALSE(allowed); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09700 + * @tc.name : ANS_IsSpecialBundleAllowedNotify_0100 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09700, Function | SmallTest | Level1) +{ + ASSERT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); + TestAddSlot(NotificationConstant::SlotType::OTHER); + bool allowed = true; + ASSERT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09800 + * @tc.name : ANS_IsSpecialBundleAllowedNotify_0200 + * @tc.desc : Test IsSpecialBundleAllowedNotify function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, Function | SmallTest | Level1) +{ + ASSERT_EQ( + (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); + std::vector> notifications; + bool allowed = true; + ASSERT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), + (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_09900 + * @tc.name : ANS_GetSlotsByBundle_0200 + * @tc.desc : Test GetSlotsByBundle function when no bundle + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, Function | SmallTest | Level1) +{ + std::vector> slots; + ASSERT_EQ((int)advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), + (int)ERR_OK); +} + + +/** + * @tc.number : AdvancedNotificationServiceTest_10500 + * @tc.name : ANS_SetDisturbMode_10500 + * @tc.desc : Test SetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10500, Function | SmallTest | Level1) +{ + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); + auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t endDate = endDuration.count(); + date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + timePoint = std::chrono::system_clock::now(); + beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + endDate = endDuration.count(); + date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + timePoint = std::chrono::system_clock::now(); + beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + endDate = endDuration.count(); + date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10600 + * @tc.name : ANS_GetDisturbMode_10600 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10600, Function | SmallTest | Level1) +{ + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::NONE); + ASSERT_EQ(result->GetBeginDate(), 0); + ASSERT_EQ(result->GetEndDate(), 0); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10700 + * @tc.name : ANS_GetDisturbMode_10700 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10700, Function | SmallTest | Level1) +{ + std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); + timePoint = std::chrono::time_point_cast(timePoint); + timePoint += std::chrono::hours(1); + auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t endDate = endDuration.count(); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::ONCE); + ASSERT_EQ(result->GetBeginDate(), beginDate); + ASSERT_EQ(result->GetEndDate(), endDate); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10800 + * @tc.name : ANS_GetDisturbMode_10800 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10800, Function | SmallTest | Level1) +{ + std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); + timePoint = std::chrono::time_point_cast(timePoint); + timePoint += std::chrono::hours(1); + auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t endDate = endDuration.count(); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + sptr result = nullptr; + ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + ASSERT_EQ(result->GetBeginDate(), beginDate); + ASSERT_EQ(result->GetEndDate(), endDate); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10900 + * @tc.name : ANS_GetDisturbMode_10900 + * @tc.desc : Test GetDisturbMode function + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10900, Function | SmallTest | Level1) +{ + std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); + timePoint = std::chrono::time_point_cast(timePoint); + timePoint += std::chrono::hours(1); + auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t beginDate = beginDuration.count(); + timePoint += std::chrono::hours(1); + auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); + int64_t endDate = endDuration.count(); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); + ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::CLEARLY); + ASSERT_EQ(result->GetBeginDate(), beginDate); + ASSERT_EQ(result->GetEndDate(), endDate); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_12900 + * @tc.name : ANS_HasNotificationPolicyAccessPermission_0100 + * @tc.desc : Test HasNotificationPolicyAccessPermission function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_12900, Function | SmallTest | Level1) +{ + bool granted = true; + ASSERT_EQ(advancedNotificationService_->HasNotificationPolicyAccessPermission(granted), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13000 + * @tc.name : ANS_GetShowBadgeEnabled_0100 + * @tc.desc : Test GetShowBadgeEnabled function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13000, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + bool enabled = false; + ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabled(enabled), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13100 + * @tc.name : ANS_RequestEnableNotification_0100 + * @tc.desc : Test whether to pop dialog + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13100, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + std::string deviceId = "DeviceId"; + sptr callback = nullptr; + sptr callerToken = nullptr; + ASSERT_EQ(advancedNotificationService_->RequestEnableNotification(deviceId, callback, callerToken), + (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13500 + * @tc.name : ANS_GetValidReminders_0100 + * @tc.desc : Test GetValidReminders function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13500, Function | SmallTest | Level1) +{ + std::vector> reminders; + ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), (int)ERR_NO_INIT); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13600 + * @tc.name : ANS_ActiveNotificationDump_0100 + * @tc.desc : Test ActiveNotificationDump function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13600, Function | SmallTest | Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 2; + std::vector dumpInfo; + ASSERT_EQ(advancedNotificationService_->ActiveNotificationDump(bundle, userId, 0, dumpInfo), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13700 + * @tc.name : ANS_RecentNotificationDump_0100 + * @tc.desc : Test RecentNotificationDump function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13700, Function | SmallTest | Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 3; + std::vector dumpInfo; + ASSERT_EQ(advancedNotificationService_->RecentNotificationDump(bundle, userId, 0, dumpInfo), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13800 + * @tc.name : ANS_SetRecentNotificationCount_0100 + * @tc.desc : Test SetRecentNotificationCount function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13800, Function | SmallTest | Level1) +{ + std::string arg = "Arg"; + ASSERT_EQ(advancedNotificationService_->SetRecentNotificationCount(arg), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13900 + * @tc.name : ANS_RemoveAllSlots_0100 + * @tc.desc : Test RemoveAllSlots function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13900, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + ASSERT_EQ(advancedNotificationService_->RemoveAllSlots(), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14200 + * @tc.name : ANS_DoesSupportDoNotDisturbMode_0100 + * @tc.desc : Test DoesSupportDoNotDisturbMode function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14200, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + bool doesSupport = true; + ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14300 + * @tc.name : ANS_IsDistributedEnabled_0100 + * @tc.desc : Test IsDistributedEnabled function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->IsDistributedEnabled(enabled), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14400 + * @tc.name : ANS_EnableDistributed_0100 + * @tc.desc : Test EnableDistributed function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14400, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14600 + * @tc.name : ANS_EnableDistributedSelf_0100 + * @tc.desc : Test EnableDistributedSelf function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14800 + * @tc.name : ANS_IsSpecialUserAllowedNotify_0100 + * @tc.desc : Test IsSpecialUserAllowedNotify function when the result is ERR_ANS_INVALID_PARAM + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14800, Function | SmallTest | Level1) +{ + int32_t userId = 3; + bool allowed = true; + ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify(userId, allowed), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_14900 + * @tc.name : ANS_SetNotificationsEnabledByUser_0100 + * @tc.desc : Test SetNotificationsEnabledByUser function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14900, Function | SmallTest | Level1) +{ + int32_t userId = 3; + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser(userId, enabled), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15000 + * @tc.name : ANS_GetDoNotDisturbDate_0100 + * @tc.desc : Test GetDoNotDisturbDate function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15000, Function | SmallTest | Level1) +{ + int32_t userId = 3; + sptr date = nullptr; + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15200 + * @tc.name : ANS_GetHasPoppedDialog_0100 + * @tc.desc : Test GetHasPoppedDialog function when the result is ERR_ANS_INVALID_PARAM + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15200, Function | SmallTest | Level1) +{ + sptr bundleOption = nullptr; + bool hasPopped = true; + ASSERT_EQ(advancedNotificationService_->GetHasPoppedDialog(bundleOption, hasPopped), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15300 + * @tc.name : ANS_ShellDump_0100 + * @tc.desc : Test ShellDump function when the result is ERR_ANS_INVALID_PARAM + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15300, Function | SmallTest | Level1) +{ + std::string cmd = "CMD"; + std::string bundle = "Bundle"; + int32_t userId = 4; + std::vector dumpInfo; + ASSERT_EQ(advancedNotificationService_->ShellDump(cmd, bundle, userId, 0, dumpInfo), (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15400 + * @tc.name : ANS_Dump_0100 + * @tc.desc : Test Dump function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15400, Function | SmallTest | Level1) +{ + int fd = 1; + std::vector args; + ASSERT_EQ(advancedNotificationService_->Dump(fd, args), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15700 + * @tc.name : PrepareNotificationRequest_0100 + * @tc.desc : Test PrepareNotificationRequest function when notification is agent. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "PrepareNotificationRequest_0100 test start"; + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + std::string label = "publish's label"; + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + + req->SetContent(content); + req->SetIsAgentNotification(true); + ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_OK); + GTEST_LOG_(INFO) << "PrepareNotificationRequest_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_15800 + * @tc.name : GenerateBundleOption_0100 + * @tc.desc : Test GenerateBundleOption function when bundle name is null. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GenerateBundleOption_0100 test start"; + MockSystemApp(); + MockIsNonBundleName(true); + ASSERT_EQ(advancedNotificationService_->GenerateBundleOption(), nullptr); + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "GenerateBundleOption_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16000 + * @tc.name : CancelPreparedNotification_1000 + * @tc.desc : Test CancelPreparedNotification function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test start"; + + int32_t notificationId = 0; + std::string label = "testLabel"; + sptr bundleOption = nullptr; + ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption, 8), + ERR_ANS_INVALID_BUNDLE); + + GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test end"; +} + + +/** + * @tc.number : AdvancedNotificationServiceTest_16200 + * @tc.name : ANS_CancelAsBundle_0200 + * @tc.desc : Test CancelAsBundle function + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16200, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0200 test start"; + + TestAddSlot(NotificationConstant::SlotType::OTHER); + int32_t notificationId = 1; + std::string representativeBundle = "RepresentativeBundle"; + int32_t userId = 1; + int result = ERR_ANS_NOTIFICATION_NOT_EXISTS; + ASSERT_EQ(advancedNotificationService_->CancelAsBundle(notificationId, representativeBundle, userId), result); + + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16300 + * @tc.name : ANS_CancelAsBundle_0300 + * @tc.desc : Test CancelAsBundle function when uid is less than 0. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0300 test start"; + + TestAddSlot(NotificationConstant::SlotType::OTHER); + int32_t notificationId = 1; + std::string representativeBundle = "RepresentativeBundle"; + int32_t userId = 0; + int result = ERR_ANS_INVALID_UID; + ASSERT_EQ(advancedNotificationService_->CancelAsBundle(notificationId, representativeBundle, userId), result); + + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0300 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16500 + * @tc.name : ANS_CancelAsBundle_0400 + * @tc.desc : Test CancelAsBundle function + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0400 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + int32_t notificationId = 1; + + int result = ERR_ANS_NOTIFICATION_NOT_EXISTS; + ASSERT_EQ(advancedNotificationService_->CancelAsBundle(bundleOption, notificationId), result); + + GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0400 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16400 + * @tc.name : ANS_AddSlots_0100 + * @tc.desc : Test AddSlots function whith not system app + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16400, Function | SmallTest | Level1) +{ + MockSystemApp(); + GTEST_LOG_(INFO) << "ANS_AddSlots_0100 test start"; + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_AddSlots_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16600 + * @tc.name : ANS_AddSlots_0300 + * @tc.desc : Test AddSlots function with bundle option is null + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_AddSlots_0300 test start"; + MockIsNonBundleName(true); + MockSystemApp(); + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "ANS_AddSlots_0300 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16700 + * @tc.name : ANS_AddSlots_0400 + * @tc.desc : Test AddSlots function with invalid bundle option + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_AddSlots_0400 test start"; + + std::vector> slots; + ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "ANS_AddSlots_0400 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16800 + * @tc.name : ANS_GetSlots_0100 + * @tc.desc : Test GetSlots function with bundle option is null + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_GetSlots_0100 test start"; + MockIsNonBundleName(true); + MockSystemApp(); + std::vector> slots; + sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slots.push_back(slot); + ASSERT_EQ(advancedNotificationService_->GetSlots(slots), ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "ANS_GetSlots_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_16900 + * @tc.name : ANS_GetActiveNotifications_0100 + * @tc.desc : Test function with bundle option is null + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test start"; + + MockIsNonBundleName(true); + MockSystemApp(); + std::vector> notifications; + ASSERT_EQ(advancedNotificationService_->GetActiveNotifications(notifications, 0), ERR_ANS_INVALID_BUNDLE); + uint64_t num = 1; + ASSERT_EQ(advancedNotificationService_->GetActiveNotificationNums(num), ERR_ANS_INVALID_BUNDLE); + ASSERT_EQ(advancedNotificationService_->SetNotificationBadgeNum(num), ERR_ANS_INVALID_BUNDLE); + int32_t importance = 2; + ASSERT_EQ(advancedNotificationService_->GetBundleImportance(importance), ERR_ANS_INVALID_BUNDLE); + bool allow = true; + ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabled(allow), ERR_ANS_INVALID_BUNDLE); + + sptr slot = new NotificationSlot(NotificationConstant::OTHER); + ASSERT_EQ(advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), ERR_ANS_INVALID_BUNDLE); + ASSERT_EQ(advancedNotificationService_->RemoveSlotByType(NotificationConstant::OTHER), ERR_ANS_INVALID_BUNDLE); + + std::string deviceId = "DeviceId"; + bool needPop = false; + ASSERT_EQ(advancedNotificationService_->IsAllowedNotifySelf(needPop), ERR_ANS_INVALID_BUNDLE); + sptr bundleOption; + ASSERT_EQ(advancedNotificationService_->IsAllowedNotifySelf(bundleOption, needPop), ERR_ANS_INVALID_BUNDLE); + + ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, bundleOption), ERR_ANS_INVALID_BUNDLE); + + int32_t reminderId = 1; + ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), ERR_ANS_INVALID_BUNDLE); + + ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), ERR_ANS_INVALID_BUNDLE); + + std::vector> reminders; + ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), ERR_ANS_INVALID_BUNDLE); + + ASSERT_EQ(advancedNotificationService_->RemoveAllSlots(), ERR_ANS_INVALID_BUNDLE); + + ASSERT_EQ(advancedNotificationService_->AddSlotByType(NotificationConstant::SlotType::OTHER), + ERR_ANS_INVALID_BUNDLE); + + std::string groupName = "name"; + ASSERT_EQ(advancedNotificationService_->CancelGroup(groupName, 0), ERR_ANS_INVALID_BUNDLE); + + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17100 + * @tc.name : ANS_GetSetActiveNotifications_0100 + * @tc.desc : Test function with NON_SYSTEM_APP_UID + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test start"; + + std::string key = "key"; + int32_t removeReason = 0; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->Delete(key, removeReason), ERR_ANS_NOTIFICATION_NOT_EXISTS); + + ASSERT_EQ(advancedNotificationService_->DeleteByBundle(bundleOption), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); + + bool enable = true; + bool isForceControl = false; + ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle(bundleOption, enable), ERR_OK); + + std::vector> notifications; + ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(notifications), ERR_OK); + + std::vector keys; + ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications(keys, notifications), + ERR_OK); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles(key, enable), + ERR_OK); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( + std::string(), bundleOption, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(enable), ERR_ANS_INVALID_PARAM); + + int32_t notificationId = 1; + ASSERT_EQ(advancedNotificationService_->RemoveNotification(bundleOption, notificationId, + key, removeReason), ERR_ANS_NOTIFICATION_NOT_EXISTS); + + ASSERT_EQ(advancedNotificationService_->RemoveAllNotifications(bundleOption), ERR_OK); + + uint64_t num = 1; + ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_OK); + + std::string groupName = "group"; + ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_OK); + + sptr date = nullptr; + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_INVALID_PARAM); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->EnableDistributed(enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); + + NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; + ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_OK); + + int32_t userId = 1; + ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify(userId, enable), ERR_ANS_INVALID_PARAM); + + ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser(userId, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->DeleteAllByUser(userId), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->SetEnabledForBundleSlot(bundleOption, + NotificationConstant::SlotType::OTHER, enable, false), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->GetEnabledForBundleSlot(bundleOption, + NotificationConstant::SlotType::OTHER, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); + + ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); + + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); + + GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17300 + * @tc.name : ANS_GetSlotsByBundle_0100 + * @tc.desc : Test GetSlotsByBundle function + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_GetSlotsByBundle_0100 test start"; + std::vector> slots; + ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), + ERR_OK); + + ASSERT_EQ(advancedNotificationService_->UpdateSlots( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), + ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "ANS_GetSlotsByBundle_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17400 + * @tc.name : Subscribe_1000 + * @tc.desc : Test Subscribe function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17400, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "Subscribe_1000 test start"; + + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_NE(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_OK); + EXPECT_NE(advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), info), ERR_OK); + + GTEST_LOG_(INFO) << "Subscribe_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17500 + * @tc.name : Unsubscribe_1000 + * @tc.desc : Test Subscribe function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "Unsubscribe_1000 test start"; + + auto subscriber = new TestAnsSubscriber(); + sptr info = new NotificationSubscribeInfo(); + EXPECT_NE(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_OK); + ASSERT_EQ(advancedNotificationService_->Unsubscribe(nullptr, info), ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "Unsubscribe_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17600 + * @tc.name : GetAppTargetBundle_1000 + * @tc.desc : Test GetAppTargetBundle function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; + + sptr bundleOption = nullptr; + + ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, bundleOption), ERR_OK); + + GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17700 + * @tc.name : GetAppTargetBundle_2000 + * @tc.desc : Test GetAppTargetBundle function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test start"; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); + sptr targetBundle = nullptr; + bundleOption->SetBundleName("test"); + ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_OK); + + GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17800 + * @tc.name : GetAppTargetBundle_3000 + * @tc.desc : Test GetAppTargetBundle function. + * @tc.require : #I60KYN + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAppTargetBundle_3000 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + sptr targetBundle = nullptr; + bundleOption->SetBundleName("test"); + ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_OK); + + GTEST_LOG_(INFO) << "GetAppTargetBundle_3000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18100 + * @tc.name : ActiveNotificationDump_1000 + * @tc.desc : Test ActiveNotificationDump function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ActiveNotificationDump_1000 test start"; + + std::string bundle = "Bundle"; + int32_t userId = -1; + std::vector dumpInfo; + + ASSERT_EQ(advancedNotificationService_->ActiveNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); + + GTEST_LOG_(INFO) << "ActiveNotificationDump_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18200 + * @tc.name : RecentNotificationDump_1000 + * @tc.desc : Test RecentNotificationDump function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18200, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RecentNotificationDump_1000 test start"; + + std::string bundle = "Bundle"; + int32_t userId = -1; + std::vector dumpInfo; + + ASSERT_EQ(advancedNotificationService_->RecentNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); + + GTEST_LOG_(INFO) << "RecentNotificationDump_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18300 + * @tc.name : DistributedNotificationDump_1000 + * @tc.desc : Test DistributedNotificationDump function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "DistributedNotificationDump_1000 test start"; + + std::string bundle = "Bundle"; + int32_t userId = -1; + std::vector dumpInfo; + + ASSERT_EQ(advancedNotificationService_->DistributedNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); + + GTEST_LOG_(INFO) << "DistributedNotificationDump_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18400 + * @tc.name : SetRecentNotificationCount_1000 + * @tc.desc : Test SetRecentNotificationCount function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18400, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "SetRecentNotificationCount_1000 test start"; + + std::string arg = "1100"; + ASSERT_EQ(advancedNotificationService_->SetRecentNotificationCount(arg), ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "SetRecentNotificationCount_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18500 + * @tc.name : OnBundleRemoved_1000 + * @tc.desc : Test OnBundleRemoved function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnBundleRemoved_1000 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnBundleRemoved(bundleOption); + + GTEST_LOG_(INFO) << "OnBundleRemoved_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18600 + * @tc.name : OnScreenOn_1000 + * @tc.desc : Test OnScreenOn function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnScreenOn_1000 test start"; + + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnScreenOn(); + advancedNotificationService_->OnScreenOff(); + + GTEST_LOG_(INFO) << "OnScreenOn_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18700 + * @tc.name : AddSlotByType_1000 + * @tc.desc : Test AddSlotByType function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AddSlotByType_1000 test start"; + MockSystemApp(); + ASSERT_EQ(advancedNotificationService_->AddSlotByType(NotificationConstant::SlotType::SERVICE_REMINDER), + ERR_OK); + + GTEST_LOG_(INFO) << "AddSlotByType_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18800 + * @tc.name : GetSlotNumAsBundle_1000 + * @tc.desc : Test GetSlotNumAsBundle function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetSlotNumAsBundle_1000 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + uint64_t num = 1; + ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_OK); + + GTEST_LOG_(INFO) << "GetSlotNumAsBundle_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18900 + * @tc.name : CancelGroup_1000 + * @tc.desc : Test CancelGroup function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CancelGroup_1000 test start"; + + std::string groupName = ""; + ASSERT_EQ(advancedNotificationService_->CancelGroup(groupName, 0), ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "CancelGroup_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19000 + * @tc.name : RemoveGroupByBundle_1000 + * @tc.desc : Test RemoveGroupByBundle function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RemoveGroupByBundle_1000 test start"; + + std::string groupName = "group"; + sptr bundleOption = nullptr; + ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_ANS_INVALID_PARAM); + + GTEST_LOG_(INFO) << "RemoveGroupByBundle_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19100 + * @tc.name : ANS_IsDistributedEnabled_0100 + * @tc.desc : Test IsDistributedEnabled function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "ANS_IsDistributedEnabled_0100 test start"; + + bool enabled = false; + ASSERT_EQ(advancedNotificationService_->IsDistributedEnabled(enabled), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_IsDistributedEnabled_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19200 + * @tc.name : EnableDistributedByBundle_0100 + * @tc.desc : Test EnableDistributedByBundle function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19200, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "EnableDistributedByBundle_0100 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + bool enabled = false; + ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enabled), ERR_OK); + + GTEST_LOG_(INFO) << "EnableDistributedByBundle_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19300 + * @tc.name : IsDistributedEnableByBundle_0100 + * @tc.desc : Test IsDistributedEnableByBundle function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0100 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + bool enabled = true; + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); + + GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19400 + * @tc.name : IsDistributedEnableByBundle_0200 + * @tc.desc : Test IsDistributedEnableByBundle function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19400, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0200 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + bool enabled = false; + ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); + + GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19500 + * @tc.name : GetDeviceRemindType_0100 + * @tc.desc : Test GetDeviceRemindType function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetDeviceRemindType_0100 test start"; + + NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; + ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_OK); + + GTEST_LOG_(INFO) << "GetDeviceRemindType_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19600 + * @tc.name : GetLocalNotificationKeys_0100 + * @tc.desc : Test GetLocalNotificationKeys function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetLocalNotificationKeys_0100 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->GetLocalNotificationKeys(bundleOption); + + GTEST_LOG_(INFO) << "GetLocalNotificationKeys_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19700 + * @tc.name : CheckDistributedNotificationType_0100 + * @tc.desc : Test CheckDistributedNotificationType function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test start"; + + sptr req = new NotificationRequest(); + ASSERT_EQ(advancedNotificationService_->CheckDistributedNotificationType(req), true); + + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19800 + * @tc.name : CheckDistributedNotificationType_0200 + * @tc.desc : Test CheckDistributedNotificationType function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0200 test start"; + + sptr req = new NotificationRequest(); + std::vector devices; + devices.push_back("a"); + devices.push_back("b"); + devices.push_back("c"); + req->GetNotificationDistributedOptions().SetDevicesSupportDisplay(devices); + ASSERT_EQ(advancedNotificationService_->CheckDistributedNotificationType(req), true); + + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_19900 + * @tc.name : OnDistributedPublish_0100 + * @tc.desc : Test OnDistributedPublish function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test start"; + + std::string deviceId = "DeviceId"; + std::string bundleName = "BundleName"; + sptr request = new NotificationRequest(); + + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnDistributedPublish(deviceId, bundleName, request); + + GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20000 + * @tc.name : OnDistributedUpdate_0100 + * @tc.desc : Test OnDistributedUpdate function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnDistributedUpdate_0100 test start"; + + std::string deviceId = "DeviceId"; + std::string bundleName = "BundleName"; + sptr request = new NotificationRequest(); + + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnDistributedUpdate(deviceId, bundleName, request); + + GTEST_LOG_(INFO) << "OnDistributedUpdate_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20100 + * @tc.name : OnDistributedDelete_0100 + * @tc.desc : Test OnDistributedDelete function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnDistributedDelete_0100 test start"; + + std::string deviceId = "DeviceId"; + std::string bundleName = "BundleName"; + std::string label = "testLabel"; + int32_t id = 1; + + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnDistributedDelete(deviceId, bundleName, label, id); + + GTEST_LOG_(INFO) << "OnDistributedDelete_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20200 + * @tc.name : CheckPublishWithoutApp_0100 + * @tc.desc : Test CheckPublishWithoutApp function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20200, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0100 test start"; + + int32_t userId = 1; + sptr request = new NotificationRequest(); + ASSERT_EQ(advancedNotificationService_->CheckPublishWithoutApp(userId, request), false); + + GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20300 + * @tc.name : CheckPublishWithoutApp_0200 + * @tc.desc : Test CheckPublishWithoutApp function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0200 test start"; + + int32_t userId = SYSTEM_APP_UID; + sptr request = new NotificationRequest(); + ASSERT_EQ(advancedNotificationService_->CheckPublishWithoutApp(userId, request), false); + + GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20400 + * @tc.name : TriggerRemoveWantAgent_0100 + * @tc.desc : Test TriggerRemoveWantAgent function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20400, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "TriggerRemoveWantAgent_0100 test start"; + + sptr request = new NotificationRequest(); + AbilityRuntime::WantAgent::WantAgentInfo paramsInfo; + std::shared_ptr wantAgent = + AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + + request->SetRemovalWantAgent(wantAgent); + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->TriggerRemoveWantAgent(request); + + GTEST_LOG_(INFO) << "TriggerRemoveWantAgent_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20500 + * @tc.name : DeleteAllByUser_0100 + * @tc.desc : Test DeleteAllByUser function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "DeleteAllByUser_0100 test start"; + + int32_t userId = -2; + ASSERT_EQ(advancedNotificationService_->DeleteAllByUser(userId), ERR_ANS_INVALID_PARAM); + + sptr date = nullptr; + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); + ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); + ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDateByUser(userId, date), ERR_ANS_INVALID_PARAM); + GTEST_LOG_(INFO) << "DeleteAllByUser_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20600 + * @tc.name : OnResourceRemove_0100 + * @tc.desc : Test OnResourceRemove function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnResourceRemove_0100 test start"; + + int32_t userId = -2; + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnResourceRemove(userId); + + GTEST_LOG_(INFO) << "OnResourceRemove_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20700 + * @tc.name : OnBundleDataCleared_0100 + * @tc.desc : Test OnBundleDataCleared function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "OnBundleDataCleared_0100 test start"; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->OnBundleDataCleared(bundleOption); + + GTEST_LOG_(INFO) << "OnBundleDataCleared_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_20900 + * @tc.name : GetDumpInfo_0100 + * @tc.desc : Test GetDumpInfo function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetDumpInfo_0100 test start"; + + std::vector args; + args.push_back(Str8ToStr16("args")); + std::string result = "result"; + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->GetDumpInfo(args, result); + + GTEST_LOG_(INFO) << "GetDumpInfo_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21000 + * @tc.name : GetDumpInfo_0200 + * @tc.desc : Test GetDumpInfo function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetDumpInfo_0200 test start"; + + std::vector args; + args.push_back(Str8ToStr16("-h")); + std::string result = "result"; + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->GetDumpInfo(args, result); + + GTEST_LOG_(INFO) << "GetDumpInfo_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21100 + * @tc.name : SendFlowControlOccurHiSysEvent_0100 + * @tc.desc : Test SendFlowControlOccurHiSysEvent function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0100 test start"; + + std::shared_ptr record = nullptr; + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->SendFlowControlOccurHiSysEvent(record); + + GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21200 + * @tc.name : SendFlowControlOccurHiSysEvent_0200 + * @tc.desc : Test SendFlowControlOccurHiSysEvent function + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21200, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0200 test start"; + + std::shared_ptr record = std::make_shared(); + record->request = new NotificationRequest(); + record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_NE(nullptr, advancedNotificationService_); + advancedNotificationService_->SendFlowControlOccurHiSysEvent(record); + + GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21300 + * @tc.name : PrepareNotificationRequest_0200 + * @tc.desc : Test PrepareNotificationRequest function when uid < 0. + * @tc.require : issueI62D8C + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21300, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "PrepareNotificationRequest_0200 test start"; + sptr req = new NotificationRequest(); + int32_t myNotificationId = 10; + bool isAgentTrue = true; + NotificationRequest notificationRequest(myNotificationId); + notificationRequest.SetIsAgentNotification(isAgentTrue); + + std::shared_ptr bundleManager = nullptr; + + ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_OK); + GTEST_LOG_(INFO) << "PrepareNotificationRequest_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21400 + * @tc.name : PrepareNotificationInfo_2000 + * @tc.desc : Test PrepareNotificationInfo function. + * @tc.require : issueI62D8C + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21400, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "PrepareNotificationInfo_2000 test start"; + + sptr req = new (std::nothrow) NotificationRequest(1); + EXPECT_NE(req, nullptr); + sptr bundleOption = nullptr; + + ASSERT_EQ(advancedNotificationService_->PrepareNotificationInfo(req, bundleOption), ERR_OK); + + GTEST_LOG_(INFO) << "PrepareNotificationInfo_2000 test end"; +} + + + +/** + * @tc.number : AdvancedNotificationServiceTest_21600 + * @tc.name : RegisterPushCallback_0100 + * @tc.desc : Test RegisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21600, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RegisterPushCallback_0100 test start"; + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), ERR_OK); + + advancedNotificationService_->UnregisterPushCallback(); + + GTEST_LOG_(INFO) << "RegisterPushCallback_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21700 + * @tc.name : RegisterPushCallback_0200 + * @tc.desc : Test RegisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21700, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test start"; + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), + (int)ERR_OK); + advancedNotificationService_->UnregisterPushCallback(); + + + GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21800 + * @tc.name : RegisterPushCallback_0200 + * @tc.desc : Test RegisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21800, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RegisterPushCallback_0300 test start"; + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr pushCallBack = iface_cast(pushCallback); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + + advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); + + ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), (int)ERR_OK); + + advancedNotificationService_->UnregisterPushCallback(); + + GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_21900 + * @tc.name : UnregisterPushCallback_0100 + * @tc.desc : Test UnregisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "UnregisterPushCallback_0100 test start"; + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr pushCallBack = iface_cast(pushCallback); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + + advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); + + ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), ERR_OK); + + GTEST_LOG_(INFO) << "UnregisterPushCallback_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_22000 + * @tc.name : UnregisterPushCallback_0200 + * @tc.desc : Test UnregisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "UnregisterPushCallback_0200 test start"; + ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), (int)ERR_ANS_NON_SYSTEM_APP); + + GTEST_LOG_(INFO) << "UnregisterPushCallback_0200 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_22100 + * @tc.name : UnregisterPushCallback_0300 + * @tc.desc : Test UnregisterPushCallback function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22100, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "UnregisterPushCallback_0300 test start"; + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), (int)ERR_INVALID_OPERATION); + + GTEST_LOG_(INFO) << "UnregisterPushCallback_0300 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_22500 + * @tc.name : PushCheck_0100 + * @tc.desc : Test PushCheck function. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22500, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "PushCheck_0100 test start"; + + sptr req = new (std::nothrow) NotificationRequest(); + ASSERT_EQ(advancedNotificationService_->PushCheck(req), ERR_ANS_PUSH_CHECK_UNREGISTERED); + + GTEST_LOG_(INFO) << "PushCheck_0100 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_220000 + * @tc.name : TimeToString_1000 + * @tc.desc : Test TimeToString function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_220000, Function | SmallTest | Level1) +{ + int64_t time = 60; + int64_t ret = 20; + std::string result = advancedNotificationService_->TimeToString(time); + ASSERT_EQ(result.size(), ret); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_22600 + * @tc.name : ANS_IsNeedSilentInDoNotDisturbMode_0100 + * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function when the result is ERR_OK + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22600, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + std::string phoneNumber = "11111111111"; + int32_t callerType = 0; + auto ret = advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); + ASSERT_EQ(ret, -1); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00001 + * @tc.name : PrepareNotificationRequest + * @tc.desc : Test PrepareNotificationRequest function. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00001 test start"; + ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(nullptr), ERR_ANS_INVALID_PARAM); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00001 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00002 + * @tc.name : IsNotificationExists + * @tc.desc : Test IsNotificationExists function. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00002 test start"; + std::string key = "aa"; + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + ASSERT_EQ(advancedNotificationService_->IsNotificationExists(key), false); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00002 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00003 + * @tc.name : UpdateInNotificationList + * @tc.desc : Test UpdateInNotificationList function and notificationList_ is not empty. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00003, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00003 test start"; + std::string key = "aa"; + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + advancedNotificationService_->UpdateInNotificationList(record); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00003 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00004 + * @tc.name : SetBadgeNumber + * @tc.desc : Test SetBadgeNumber function and handler_ is nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00004, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00004 test start"; + int32_t badgeNumber = 1; + ASSERT_EQ(advancedNotificationService_->SetBadgeNumber(badgeNumber, 0), ERR_OK); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00004 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00005 + * @tc.name : SetBadgeNumber + * @tc.desc : Test SetBadgeNumber function and handler_ is not nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00005, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00005 test start"; + int32_t badgeNumber = 1; + advancedNotificationService_->runner_ = OHOS::AppExecFwk::EventRunner::Create("NotificationSvrMain"); + advancedNotificationService_->handler_ = + std::make_shared(advancedNotificationService_->runner_); + ASSERT_EQ(advancedNotificationService_->SetBadgeNumber(badgeNumber, 0), ERR_OK); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00005 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00006 + * @tc.name : ResetPushCallbackProxy + * @tc.desc : Test ResetPushCallbackProxy function and pushCallBack_ is nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00006, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00006 test start"; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->ResetPushCallbackProxy(); + ASSERT_EQ(advancedNotificationService_->pushCallBacks_.empty(), true); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00006 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00007 + * @tc.name : ResetPushCallbackProxy + * @tc.desc : Test ResetPushCallbackProxy function and pushCallBack_ is not nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00007, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00007 test start"; + EXPECT_NE(advancedNotificationService_, nullptr); + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr pushCallBack = iface_cast(pushCallback); + sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); + + advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); + advancedNotificationService_->ResetPushCallbackProxy(); + ASSERT_TRUE(advancedNotificationService_->pushCallBacks_.empty()); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00007 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00008 + * @tc.name : SendEnableNotificationSlotHiSysEvent + * @tc.desc : Test SendEnableNotificationSlotHiSysEvent function and bundleOption is nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00008, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00008 test start"; + sptr bundleOption = nullptr; + NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CONTENT_INFORMATION; + bool enabled = false; + ErrCode errCode = ERR_OK; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00008 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00009 + * @tc.name : SendEnableNotificationSlotHiSysEvent + * @tc.desc : Test SendEnableNotificationSlotHiSysEvent function and errCode != ERR_OK. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00009, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00009 test start"; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CONTENT_INFORMATION; + bool enabled = false; + ErrCode errCode = ERR_ANS_TASK_ERR; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00009 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00010 + * @tc.name : SendRemoveHiSysEvent + * @tc.desc : Test SendRemoveHiSysEvent function and errCode is ERR_OK bundleOption is not nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00010, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00010 test start"; + int32_t notificationId = 1; + std::string label = "aa"; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ErrCode errCode = ERR_OK; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendRemoveHiSysEvent(notificationId, label, bundleOption, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00010 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00011 + * @tc.name : SendEnableNotificationHiSysEvent + * @tc.desc : Test SendEnableNotificationHiSysEvent function andbundleOption is nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00011, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00011 test start"; + sptr bundleOption = nullptr; + bool enabled = false; + ErrCode errCode = ERR_ANS_TASK_ERR; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendEnableNotificationHiSysEvent(bundleOption, enabled, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00011 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00012 + * @tc.name : SendCancelHiSysEvent + * @tc.desc : Test SendCancelHiSysEvent function and errCode is ERR_OK bundleOption is not nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00012, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00012 test start"; + int32_t notificationId = 1; + std::string label = "aa"; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ErrCode errCode = ERR_OK; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendCancelHiSysEvent(notificationId, label, bundleOption, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00012 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00013 + * @tc.name : SendPublishHiSysEvent + * @tc.desc : Test SendPublishHiSysEvent function and request is nullptr. + * @tc.require : #I6Z5I4 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00013, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00013 test start"; + sptr request = nullptr; + ErrCode errCode = ERR_OK; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->SendPublishHiSysEvent(request, errCode); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00013 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00014 + * @tc.name : GetTargetRecordList + * @tc.desc : Test GetTargetRecordList function and get empty. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00014, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00014 test start"; + std::shared_ptr record = std::make_shared(); + record->request = new NotificationRequest(); + record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + const int32_t uid = 0; + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; + advancedNotificationService_->notificationList_.clear(); + std::vector> recordList; + ASSERT_EQ(advancedNotificationService_->GetTargetRecordList(uid, slotType, contentType, recordList), + ERR_ANS_NOTIFICATION_NOT_EXISTS); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00014 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00015 + * @tc.name : GetTargetRecordList + * @tc.desc : Test GetTargetRecordList function and get success. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00015, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00015 test start"; + std::string bundleName = "testBundle"; + const int32_t uid = 0; + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; + + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + request->SetSlotType(slotType); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + request->SetCreatorUid(uid); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + std::vector> recordList; + ASSERT_EQ(advancedNotificationService_->GetTargetRecordList(uid, slotType, contentType, recordList), + ERR_OK); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00015 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00016 + * @tc.name : RemoveNotificationFromRecordList + * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00016, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test start"; + std::string bundleName = "testBundle"; + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; + + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + request->SetSlotType(slotType); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + request->SetOwnerBundleName(bundleName); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + std::vector> recordList; + recordList.push_back(record); + ASSERT_EQ(advancedNotificationService_->RemoveNotificationFromRecordList(recordList), ERR_OK); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00017 + * @tc.name : RemoveSystemLiveViewNotifications + * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00017, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test start"; + std::string bundleName = "testBundle"; + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + request->SetSlotType(slotType); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + request->SetOwnerBundleName(bundleName); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + int32_t uid = 0; + ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), ERR_OK); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00017 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00018 + * @tc.name : RemoveSystemLiveViewNotifications + * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00018, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00018 test start"; + std::string bundleName = "testBundle"; + int32_t uid = 0; + ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), + ERR_ANS_NOTIFICATION_NOT_EXISTS); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00018 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_00019 + * @tc.name : RemoveSystemLiveViewNotifications + * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. + * @tc.require : #I8B8PI + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00019, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00019 test start"; + std::string bundleName = "testBundle"; + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + sptr request = new (std::nothrow) NotificationRequest(); + EXPECT_NE(request, nullptr); + request->SetSlotType(slotType); + auto liveContent = std::make_shared(); + auto content = std::make_shared(liveContent); + request->SetContent(content); + request->SetOwnerBundleName(bundleName); + sptr notification = new (std::nothrow) Notification(request); + EXPECT_NE(notification, nullptr); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + advancedNotificationService_->notificationSvrQueue_ = nullptr; + int32_t uid = 0; + ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), ERR_ANS_INVALID_PARAM); + GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00019 test end"; +} +/** + * @tc.number : IsLiveViewCanRecoverTest_0001 + * @tc.name : IsLiveViewCanRecover + * @tc.desc : Test IsLiveViewCanRecover and liveview is nullptr. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0001 test start"; + ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(nullptr), false); + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0001 test end"; +} + +/** + * @tc.number : IsLiveViewCanRecoverTest_0002 + * @tc.name : IsLiveViewCanRecover + * @tc.desc : Test IsLiveViewCanRecover and liveview status is invalid. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0002 test start"; + sptr request = new NotificationRequest(); + std::shared_ptr liveViewContent = std::make_shared(); + std::shared_ptr content = std::make_shared(liveViewContent); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); + request->SetContent(content); + + ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), false); + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0002 test end"; +} + +/** + * @tc.number : IsLiveViewCanRecoverTest_0003 + * @tc.name : IsLiveViewCanRecover + * @tc.desc : Test IsLiveViewCanRecover and liveview is expired. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0003, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0003 test start"; + sptr request = new NotificationRequest(); + std::shared_ptr liveViewContent = std::make_shared(); + std::shared_ptr content = std::make_shared(liveViewContent); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); + request->SetContent(content); + request->SetFinishDeadLine(0); + + ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), false); + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0003 test end"; +} + +/** + * @tc.number : IsLiveViewCanRecoverTest_0004 + * @tc.name : IsLiveViewCanRecover + * @tc.desc : Test IsLiveViewCanRecover and liveview status is create and not expired. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0004, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0004 test start"; + sptr request = new NotificationRequest(); + std::shared_ptr liveViewContent = std::make_shared(); + std::shared_ptr content = std::make_shared(liveViewContent); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); + request->SetContent(content); + + auto now = std::chrono::system_clock::now(); + auto duration = std::chrono::duration_cast(now.time_since_epoch()); + request->SetFinishDeadLine(duration.count() + NotificationConstant::MAX_FINISH_TIME); + request->SetUpdateDeadLine(duration.count() + NotificationConstant::MAX_UPDATE_TIME); + + ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), true); + GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0004 test end"; +} + +/** + * @tc.number : FillNotificationRecordTest_0001 + * @tc.name : FillNotificationRecord + * @tc.desc : Test FillNotificationRecord and request is nullptr. + */ +HWTEST_F(AdvancedNotificationServiceTest, FillNotificationRecordTest_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "FillNotificationRecordTest_0001 test start"; + AdvancedNotificationService::NotificationRequestDb requestDbObj = { .request = nullptr, .bundleOption = nullptr}; + auto record = std::make_shared(); + + EXPECT_NE(advancedNotificationService_->FillNotificationRecord(requestDbObj, record), ERR_OK); + GTEST_LOG_(INFO) << "FillNotificationRecordTest_0001 test end"; +} + +/** + * @tc.number : FillNotificationRecordTest_0002 + * @tc.name : FillNotificationRecord + * @tc.desc : Test FillNotificationRecord and request/bundleOption is valid. + */ +HWTEST_F(AdvancedNotificationServiceTest, FillNotificationRecordTest_0002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "FillNotificationRecordTest_0002 test start"; + sptr request = new NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + std::string bundleName = "BundleName"; + int32_t uid = 10; + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + AdvancedNotificationService::NotificationRequestDb requestDbObj = + { .request = request, .bundleOption = bundleOption }; + auto record = std::make_shared(); + + ASSERT_EQ(advancedNotificationService_->FillNotificationRecord(requestDbObj, record), ERR_OK); + GTEST_LOG_(INFO) << "FillNotificationRecordTest_0002 test end"; +} + +/** + * @tc.number : RecoverLiveViewFromDb_0002 + * @tc.name : RecoverLiveViewFromDb + * @tc.desc : Test RecoverLiveViewFromDb and liveView can't recover from db. + */ +HWTEST_F(AdvancedNotificationServiceTest, RecoverLiveViewFromDb_0002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "RecoverLiveViewFromDb_0002 test start"; + advancedNotificationService_->notificationList_.clear(); + sptr request = new NotificationRequest(1); + std::shared_ptr liveViewContent = std::make_shared(); + std::shared_ptr content = std::make_shared(liveViewContent); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); + request->SetContent(content); + request->SetCreatorUid(1); + request->SetCreatorUserId(2); + request->SetLabel("test_2"); + + std::string bundleName = "BundleName_02"; + int32_t uid = 11; + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + AdvancedNotificationService::NotificationRequestDb requestDbObj = + { .request = request, .bundleOption = bundleOption }; + auto result = advancedNotificationService_->SetNotificationRequestToDb(requestDbObj); + ASSERT_EQ(result, ERR_OK); + + advancedNotificationService_->RecoverLiveViewFromDb(); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 0); + + result = advancedNotificationService_->DeleteNotificationRequestFromDb(request->GetKey(), 0); + ASSERT_EQ(result, ERR_OK); + + GTEST_LOG_(INFO) << "RecoverLiveViewFromDb_0002 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0001 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test live view notification need pushCheck. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0001 test start"; + sptr request = new NotificationRequest(); + std::shared_ptr liveViewContent = std::make_shared(); + auto status = NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE; + liveViewContent->SetLiveViewStatus(status); + std::shared_ptr content = std::make_shared(liveViewContent); + request->SetContent(content); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), true); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0001 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0002 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test notification except live view registered need push check. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0002 test start"; + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr pushCallBack = iface_cast(pushCallback); + + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + + advancedNotificationService_->pushCallBacks_.clear(); + advancedNotificationService_->checkRequests_.clear(); + sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); + notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::CUSTOM); + notificationCheckRequest->SetContentType(NotificationContent::Type::BASIC_TEXT); + advancedNotificationService_->pushCallBacks_.insert_or_assign( + notificationCheckRequest->GetSlotType(), pushCallBack); + advancedNotificationService_->checkRequests_.insert_or_assign( + notificationCheckRequest->GetSlotType(), notificationCheckRequest); + + sptr request = new NotificationRequest(); + request->SetContent(content); + request->SetSlotType(NotificationConstant::SlotType::CUSTOM); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), true); + advancedNotificationService_->pushCallBacks_.clear(); + advancedNotificationService_->checkRequests_.clear(); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0002 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0003 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test notification except live view unregistered don't need push check. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0003, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0003 test start"; + sptr request = new NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::CUSTOM); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0003 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0004 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test notification published by system app don't need push check. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0004, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0004 test start"; + + sptr request = new NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::CUSTOM); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0004 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0005 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test live view notification except create status don't need pushCheck. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0005, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0005 test start"; + sptr request = new NotificationRequest(); + std::shared_ptr liveViewContent = std::make_shared(); + auto status = NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; + liveViewContent->SetLiveViewStatus(status); + std::shared_ptr content = std::make_shared(liveViewContent); + request->SetContent(content); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0005 test end"; +} + +/** + * @tc.number : IsNeedPushCheckTest_0006 + * @tc.name : IsNeedPushCheckTest + * @tc.desc : Test notification except live view registered but has inconsistent contentType dont't need push check. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0006, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0006 test start"; + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr pushCallBack = iface_cast(pushCallback); + + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + normalContent->SetText("normalContent's text"); + normalContent->SetTitle("normalContent's title"); + std::shared_ptr content = std::make_shared(normalContent); + + sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); + notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::CUSTOM); + notificationCheckRequest->SetContentType(NotificationContent::Type::PICTURE); + advancedNotificationService_->pushCallBacks_.insert_or_assign( + notificationCheckRequest->GetSlotType(), pushCallBack); + advancedNotificationService_->checkRequests_.insert_or_assign( + notificationCheckRequest->GetSlotType(), notificationCheckRequest); + + sptr request = new NotificationRequest(); + request->SetContent(content); + request->SetSlotType(NotificationConstant::SlotType::CUSTOM); + ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); + advancedNotificationService_->pushCallBacks_.clear(); + advancedNotificationService_->checkRequests_.clear(); + + GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0006 test end"; +} +/** + * @tc.number : PushCheckTest_0001 + * @tc.name : PushCheckTest + * @tc.desc : Test registerer of push check is allowed. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, PushCheckTest_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "PushCheckTest_0001 test start"; + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + sptr pushCallback = pushCallbackProxy->AsObject(); + sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); + notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr pushCallBack = iface_cast(pushCallback); + advancedNotificationService_->pushCallBacks_.insert_or_assign( + notificationCheckRequest->GetSlotType(), pushCallBack); + advancedNotificationService_->checkRequests_.insert_or_assign( + notificationCheckRequest->GetSlotType(), notificationCheckRequest); + + sptr request = new NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + ASSERT_EQ(advancedNotificationService_->PushCheck(request), ERR_OK); + + advancedNotificationService_->pushCallBacks_.clear(); + advancedNotificationService_->checkRequests_.clear(); + + GTEST_LOG_(INFO) << "PushCheckTest_0001 test end"; +} + +/** + * @tc.number : GetActiveNotificationByFilter_0001 + * @tc.name : GetActiveNotificationByFilter + * @tc.desc : Test get non-existent live view notification request by filter. + * @tc.require : #I6Z5OV + */ +HWTEST_F(AdvancedNotificationServiceTest, GetActiveNotificationByFilter_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetActiveNotificationByFilter_0001 test start"; + + TestAddSlot(NotificationConstant::SlotType::LIVE_VIEW); + sptr req; + + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + int32_t notificationId = 1; + std::string label = "GetActiveNotificationByFilter's label"; + std::vector extraInfoKeys; + + ASSERT_EQ(advancedNotificationService_->GetActiveNotificationByFilter(bundleOption, notificationId, label, + extraInfoKeys, req), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + + GTEST_LOG_(INFO) << "GetActiveNotificationByFilter_0001 test end"; +} + +/** + * @tc.number : IsAllowedRemoveSlot_0001 + * @tc.name : IsAllowedRemoveSlot + * @tc.desc : Test IsAllowedRemoveSlot and slotType is not liveView. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0001 test start"; + sptr bundleOption = new NotificationBundleOption(); + ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, NotificationConstant::SlotType::OTHER), + (int)ERR_OK); + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0001 test end"; +} + +/** + * @tc.number : IsAllowedRemoveSlot_0002 + * @tc.name : IsAllowedRemoveSlot + * @tc.desc : Test IsAllowedRemoveSlot and slot is not exist. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0002 test start"; + sptr bundleOption = new NotificationBundleOption(); + ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, + NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0002 test end"; +} + +/** + * @tc.number : IsAllowedRemoveSlot_0003 + * @tc.name : IsAllowedRemoveSlot + * @tc.desc : Test IsAllowedRemoveSlot and slot is forcecontrol is false + */ +HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0003, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0003 test start"; + TestAddLiveViewSlot(false); + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, + NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0003 test end"; +} + +/** + * @tc.number : IsAllowedRemoveSlot_0004 + * @tc.name : IsAllowedRemoveSlot + * @tc.desc : Test IsAllowedRemoveSlot and caller not sa or systemapp + */ +HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0004, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0004 test start"; + TestAddLiveViewSlot(true); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, + NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_ANS_NON_SYSTEM_APP); + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0004 test end"; +} + +/** + * @tc.number : IsAllowedRemoveSlot_0005 + * @tc.name : IsAllowedRemoveSlot + * @tc.desc : Test IsAllowedRemoveSlot and caller is systemapp + */ +HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0005, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0005 test start"; + TestAddLiveViewSlot(true); + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, + NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); + GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0005 test end"; +} + +/** + * @tc.name: NotificationSvrQueue_00001 + * @tc.desc: Test notificationSvrQueue is nullptr + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + + auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle, 8); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + std::vector> requests; + ret = advancedNotificationService_->GetActiveNotifications(requests, 0); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + uint64_t num = 0; + ret = advancedNotificationService_->GetActiveNotificationNums(num); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + int importance = 0; + ret = advancedNotificationService_->GetBundleImportance(importance); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + std::vector> notifications; + ret = advancedNotificationService_->GetAllActiveNotifications(notifications); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + std::vector keys; + ret = advancedNotificationService_->GetSpecialActiveNotifications(keys, notifications); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + bool enabled = false; + ret = advancedNotificationService_->IsDistributedEnabled(enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->EnableDistributed(enabled); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: NotificationSvrQueue_00002 + * @tc.desc: Test notificationSvrQueue is nullptr + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | SmallTest | Level1) +{ + advancedNotificationService_->notificationSvrQueue_ = nullptr; + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + sptr bundle1 = nullptr; + auto request = new (std::nothrow) NotificationRequest(); + + auto ret = advancedNotificationService_->EnableDistributedSelf(true); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + bool enable = false; + ret = advancedNotificationService_->IsDistributedEnableByBundle(bundle, enable); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->GetHasPoppedDialog(bundle1, enable); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(1, enable); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + ret = advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(1, enable); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); + + request->SetIsCoverActionButtons(true); + advancedNotificationService_->FillActionButtons(request); +} + +/** + * @tc.name: AssignToNotificationList_00001 + * @tc.desc: Test AssignToNotificationList + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, AssignToNotificationList_00001, Function | SmallTest | Level1) +{ + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + sptr request = new (std::nothrow) NotificationRequest(); + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto liveViewContent = std::make_shared(); + std::shared_ptr content = std::make_shared(liveViewContent); + request->SetContent(content); + request->SetSlotType(slotType); + request->SetNotificationId(1); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + auto ret = advancedNotificationService_->AssignToNotificationList(record); + + ret = advancedNotificationService_->AssignToNotificationList(record); + ASSERT_EQ(ret, (int)ERR_OK); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 1); +} + +/** + * @tc.name: StartArchiveTimer_00001 + * @tc.desc: Test StartArchiveTimer + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, StartArchiveTimer_00001, Function | SmallTest | Level1) +{ + auto slotType = NotificationConstant::SlotType::LIVE_VIEW; + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(slotType); + request->SetAutoDeletedTime(NotificationConstant::NO_DELAY_DELETE_TIME); + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + advancedNotificationService_->StartArchiveTimer(record); + ASSERT_EQ(request->GetAutoDeletedTime(), 0); +} + +/** + * @tc.name: Filter_00001 + * @tc.desc: Test Filter + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, Filter_00001, Function | SmallTest | Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + + advancedNotificationService_->notificationSlotFilter_ = nullptr; + auto ret = advancedNotificationService_->Filter(record, true); + ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: ChangeNotificationByControlFlags_00001 + * @tc.desc: Test ChangeNotificationByControlFlags + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001, Function | SmallTest | Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + uint32_t notificationControlFlags = 0; + notificationControlFlags |= NotificationConstant::ReminderFlag::SOUND_FLAG; + notificationControlFlags |= NotificationConstant::ReminderFlag::LOCKSCREEN_FLAG; + notificationControlFlags |= NotificationConstant::ReminderFlag::BANNER_FLAG; + notificationControlFlags |= NotificationConstant::ReminderFlag::LIGHTSCREEN_FLAG; + notificationControlFlags |= NotificationConstant::ReminderFlag::VIBRATION_FLAG; + notificationControlFlags |= NotificationConstant::ReminderFlag::STATUSBAR_ICON_FLAG; + request->SetNotificationControlFlags(notificationControlFlags); + + std::shared_ptr flags = std::make_shared(); + flags->SetSoundEnabled(NotificationConstant::FlagStatus::OPEN); + flags->SetVibrationEnabled(NotificationConstant::FlagStatus::OPEN); + flags->SetLockScreenVisblenessEnabled(true); + flags->SetBannerEnabled(true); + flags->SetLightScreenEnabled(true); + flags->SetStatusIconEnabled(true); + request->SetFlags(flags); + + bool isAgentController = true; + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); + + u_int32_t reminderFlags = flags->GetReminderFlags(); + ASSERT_EQ(reminderFlags, 0); +} + +/** + * @tc.name: CheckPublishPreparedNotification_00001 + * @tc.desc: Test CheckPublishPreparedNotification + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, CheckPublishPreparedNotification_00001, Function | SmallTest | Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + + auto ret = advancedNotificationService_->CheckPublishPreparedNotification(record, true); + ASSERT_EQ(ret, (int)ERR_OK); +} + +/** + * @tc.name: GetRecordFromNotificationList_00001 + * @tc.desc: Test GetRecordFromNotificationList + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, GetRecordFromNotificationList_00001, Function | SmallTest | Level1) +{ + sptr request = new (std::nothrow) NotificationRequest(); + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + request->SetLabel("label"); + request->SetNotificationId(1); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + auto ret = advancedNotificationService_->AssignToNotificationList(record); + + auto res = advancedNotificationService_->GetRecordFromNotificationList( + 1, SYSTEM_APP_UID, "label", TEST_DEFUALT_BUNDLE); + EXPECT_NE(res, nullptr); +} + +/** + * @tc.name: RegisterPushCallback_00001 + * @tc.desc: Test RegisterPushCallback + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, RegisterPushCallback_00001, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + sptr pushCallback = nullptr; + sptr request = nullptr; + + auto ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); + + MockIsVerfyPermisson(true); + ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); + ASSERT_EQ(ret, (int)ERR_INVALID_VALUE); + + auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); + EXPECT_NE(pushCallbackProxy, nullptr); + pushCallback = pushCallbackProxy->AsObject(); + ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); + ASSERT_EQ(ret, (int)ERR_INVALID_VALUE); +} + +/** + * @tc.name: UnregisterPushCallback_00001 + * @tc.desc: Test UnregisterPushCallback + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, UnregisterPushCallback_00001, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + + auto ret = advancedNotificationService_->UnregisterPushCallback(); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.name: CreateDialogManager_00001 + * @tc.desc: Test CreateDialogManager + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, CreateDialogManager_00001, Function | SmallTest | Level1) +{ + advancedNotificationService_->dialogManager_ = nullptr; + bool ret = advancedNotificationService_->CreateDialogManager(); + ASSERT_EQ(ret, true); + + ret = advancedNotificationService_->CreateDialogManager(); + ASSERT_EQ(ret, true); +} + +/** + * @tc.number : IsNeedNotifyConsumed_00001 + * @tc.name : IsNeedNotifyConsumed + * @tc.desc : Test IsNeedNotifyConsumed function. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00001 test start"; + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), true); + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00001 test end"; +} + +/** + * @tc.number : IsNeedNotifyConsumed_00002 + * @tc.name : IsNeedNotifyConsumed + * @tc.desc : Test IsNeedNotifyConsumed function. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00002, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00002 test start"; + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + auto liveViewContent = std::make_shared(); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); + std::shared_ptr content = std::make_shared(liveViewContent); + request->SetContent(content); + ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), true); + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00002 test end"; +} + +/** + * @tc.number : GetAllNotificationEnabledBundles_0001 + * @tc.name : GetAllNotificationEnabledBundles + * @tc.desc : Test GetAllNotificationEnabledBundles function if not systemapp. + * @tc.require : #I92VGR + */ +HWTEST_F(AdvancedNotificationServiceTest, GetAllNotificationEnabledBundles_0001, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAllNotificationEnabledBundles_0001 test start"; + + std::vector vec; + ASSERT_EQ(advancedNotificationService_->GetAllNotificationEnabledBundles(vec), ERR_ANS_NON_SYSTEM_APP); + + GTEST_LOG_(INFO) << "GetAllNotificationEnabledBundles_0001 test end"; +} + +/** + * @tc.number : IsNeedNotifyConsumed_00003 + * @tc.name : IsNeedNotifyConsumed + * @tc.desc : Test IsNeedNotifyConsumed function. + */ +HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00003, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00003 test start"; + sptr request = new (std::nothrow) NotificationRequest(); + request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); + auto liveViewContent = std::make_shared(); + liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); + std::shared_ptr content = std::make_shared(liveViewContent); + request->SetContent(content); + request->SetAutoDeletedTime(0); + ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), false); + GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00003 test end"; +} + +/** + * @tc.number : SetBadgeNumberByBundle_00001 + * @tc.name : SetBadgeNumberByBundle + * @tc.desc : Test SetBadgeNumberByBundle with valid parameters, expect error code ERR_OK. + */ +HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00001, Function | SmallTest | Level1) +{ + ASSERT_NE(advancedNotificationService_, nullptr); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); + sptr bundleOption = new (std::nothrow) NotificationBundleOption(); + ASSERT_NE(bundleOption, nullptr); + std::string bundleName = "invalidBundleName"; + bundleOption->SetBundleName(bundleName); + int32_t badgeNumber = 1; + ASSERT_EQ(advancedNotificationService_->SetBadgeNumberByBundle(bundleOption, badgeNumber), ERR_OK); +} + +/** + * @tc.number : SetBadgeNumberByBundle_00002 + * @tc.name : SetBadgeNumberByBundle + * @tc.desc : Test SetBadgeNumberByBundle with nullptr bundle option, expect error code ERR_ANS_INVALID_PARAM. + */ +HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00002, Function | SmallTest | Level1) +{ + ASSERT_NE(advancedNotificationService_, nullptr); + MockIsSystemApp(true); + sptr bundleOption = nullptr; + int32_t badgeNumber = 1; + ASSERT_EQ(advancedNotificationService_->SetBadgeNumberByBundle(bundleOption, badgeNumber), ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.name: QueryDoNotDisturbProfile_0100 + * @tc.desc: test QueryDoNotDisturbProfile successfully called + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, QueryDoNotDisturbProfile_0100, TestSize.Level1) +{ + std::string enable; + std::string profileId; + int32_t userId = 100; + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->QueryDoNotDisturbProfile(userId, enable, profileId); +} + +/** + * @tc.name: CheckDoNotDisturbProfile_0100 + * @tc.desc: test CheckDoNotDisturbProfile successfully called + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, CheckDoNotDisturbProfile_0100, TestSize.Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + EXPECT_NE(advancedNotificationService_, nullptr); + advancedNotificationService_->CheckDoNotDisturbProfile(record); +} + +/** + * @tc.name: DoNotDisturbUpdataReminderFlags_0100 + * @tc.desc: test DoNotDisturbUpdataReminderFlags can turn off all reminders. + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, DoNotDisturbUpdataReminderFlags_0100, TestSize.Level1) +{ + auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + auto request = new (std::nothrow) NotificationRequest(); + auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); + std::shared_ptr flagsSet = std::make_shared(); + record->request->SetFlags(flagsSet); + sptr notification = new (std::nothrow) Notification(request); + record->request = request; + record->notification = notification; + advancedNotificationService_->DoNotDisturbUpdataReminderFlags(record); + auto flags = record->request->GetFlags(); + EXPECT_NE(flags, nullptr); + auto res = flags->IsStatusIconEnabled(); + ASSERT_EQ(res, false); +} + +#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED +/** + * @tc.name: RegisterSwingCallback_00001 + * @tc.desc: Test RegisterSwingCallback + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, RegisterSwingCallback_00001, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(false); + sptr swingCallback = nullptr; + auto ret = advancedNotificationService_->RegisterSwingCallback(swingCallback); + ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); +} + +/** + * @tc.name: RegisterSwingCallback_00002 + * @tc.desc: Test RegisterSwingCallback + * @tc.type: FUNC + */ +HWTEST_F(AdvancedNotificationServiceTest, RegisterSwingCallback_00002, Function | SmallTest | Level1) +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(false); + MockIsVerfyPermisson(true); + sptr swingCallback = nullptr; + auto ret = advancedNotificationService_->RegisterSwingCallback(swingCallback); + ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); +} +#endif + +/** + * @tc.number : AddExcludeDate_00001 + * @tc.name : Test AddExcludeDate + * @tc.desc : Test AddExcludeDate function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + uint64_t time = 124325; + MockIsVerfyPermisson(false); + ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} + +/** + * @tc.number : DelExcludeDates_00002 + * @tc.name : Test DelExcludeDates + * @tc.desc : Test DelExcludeDates function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + MockIsVerfyPermisson(false); + ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} + +/** + * @tc.number : GetExcludeDates_00001 + * @tc.name : Test GetExcludeDates + * @tc.desc : Test GetExcludeDates function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + std::vector times; + MockIsVerfyPermisson(false); + ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} + +/** + * @tc.number : PublishFlowControl_00001 + * @tc.name : Test PublishFlowControl + * @tc.desc : Test PublishFlowControl function when the record->slot is nullptr + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, PublishFlowControl_00001, Function | SmallTest | Level1) +{ + for (int i = 0; i < 100; i++) { + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->notificationList_.push_back(record); + } + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); + sptr request = new (std::nothrow) NotificationRequest(); + sptr notification = new (std::nothrow) Notification(request); + auto record = std::make_shared(); + record->request = request; + record->notification = notification; + advancedNotificationService_->PublishFlowControl(record); + ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp new file mode 100644 index 000000000..2b31af2cc --- /dev/null +++ b/services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp @@ -0,0 +1,198 @@ +/* + * Copyright (c) 2021-2024 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 "errors.h" +#include "notification_content.h" +#include "notification_record.h" +#include "notification_request.h" +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include + +#define private public + +#include "advanced_notification_service.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "ans_notification.h" +#include "ans_ut_constant.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "iremote_object.h" +#include "mock_ipc_skeleton.h" +#include "notification_preferences.h" +#include "notification_subscriber.h" +#include "notification_subscriber_manager.h" +#include "mock_push_callback_stub.h" +#include "system_event_observer.h" +#include "notification_constant.h" +#include "want_agent_info.h" +#include "want_agent_helper.h" +#include "want_params.h" +#include "bundle_manager_helper.h" + +extern void MockIsOsAccountExists(bool mockRet); + +using namespace testing::ext; +using namespace OHOS::Media; + +namespace OHOS { +namespace Notification { +extern void MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum mockRet); +extern void MockIsSystemApp(bool isSystemApp); +extern void MockIsNonBundleName(bool isNonBundleName); +extern void MockIsVerfyPermisson(bool isVerify); + +class AdvancedNotificationServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +private: + void TestAddSlot(NotificationConstant::SlotType type); + void TestAddLiveViewSlot(bool isForceControl); + void MockSystemApp(); + +private: + static sptr advancedNotificationService_; +}; + +sptr AdvancedNotificationServiceTest::advancedNotificationService_ = nullptr; + +void AdvancedNotificationServiceTest::SetUpTestCase() +{ + MockIsOsAccountExists(true); +} + +void AdvancedNotificationServiceTest::TearDownTestCase() {} + +void AdvancedNotificationServiceTest::SetUp() +{ + GTEST_LOG_(INFO) << "SetUp start"; + + advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + GTEST_LOG_(INFO) << "SetUp end"; +} + +void AdvancedNotificationServiceTest::TearDown() +{ + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + advancedNotificationService_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +inline void SleepForFC() +{ + // For ANS Flow Control + std::this_thread::sleep_for(std::chrono::seconds(1)); +} + +void AdvancedNotificationServiceTest::MockSystemApp() +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13200 + * @tc.name : ANS_PublishReminder_0100 + * @tc.desc : Test PublishReminder function + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13200, Function | SmallTest | Level1) +{ + sptr reminder = nullptr; + ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_PARAM); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13300 + * @tc.name : ANS_CancelReminder_0100 + * @tc.desc : Test CancelReminder function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13300, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + int32_t reminderId = 1; + ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), (int)ERR_NO_INIT); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_13400 + * @tc.name : ANS_CancelAllReminders_0100 + * @tc.desc : Test CancelAllReminders function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13400, Function | SmallTest | Level1) +{ + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), (int)ERR_NO_INIT); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_17900 + * @tc.name : PublishReminder_1000 + * @tc.desc : Test PublishReminder function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; + + int32_t reminderId = 1; + sptr reminder = new ReminderRequest(reminderId); + reminder->InitNotificationRequest(); + ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); + + GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; +} + +/** + * @tc.number : AdvancedNotificationServiceTest_18000 + * @tc.name : PublishReminder_2000 + * @tc.desc : Test PublishReminder function. + * @tc.require : #I61RF2 + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18000, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test start"; + + MockIsNonBundleName(true); + int32_t reminderId = 1; + sptr reminder = new ReminderRequest(reminderId); + reminder->InitNotificationRequest(); + ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp b/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp new file mode 100755 index 000000000..bfc739cfc --- /dev/null +++ b/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp @@ -0,0 +1,245 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "ans_ut_constant.h" +#define private public +#define protected public +#include "bundle_manager_helper.h" +#undef private +#undef protected + +extern void MockGetSystemAbilityManager(bool mockRet); + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class BundleManagerHelperBranchTest : public testing::Test { +public: + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.number : BundleManagerHelper_00100 + * @tc.name : BundleManagerHelper_00100 + * @tc.desc : test GetBundleNameByUid function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(false); + int32_t uid = 1; + ASSERT_EQ("", bundleManagerHelper.GetBundleNameByUid(uid)); +} + +/** + * @tc.number : BundleManagerHelper_00200 + * @tc.name : BundleManagerHelper_00200 + * @tc.desc : test GetBundleNameByUid function and bundleMgr_ == nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00200, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(true); + int32_t uid = 1; + ASSERT_EQ("", bundleManagerHelper.GetBundleNameByUid(uid)); +} + +/** + * @tc.number : BundleManagerHelper_00300 + * @tc.name : BundleManagerHelper_00300 + * @tc.desc : test IsSystemApp function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00300, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(false); + int32_t uid = 1; + ASSERT_EQ(false, bundleManagerHelper.IsSystemApp(uid)); +} + +/** + * @tc.number : BundleManagerHelper_00400 + * @tc.name : BundleManagerHelper_00400 + * @tc.desc : test IsSystemApp function and bundleMgr_ == nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00400, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(true); + int32_t uid = 1; + ASSERT_EQ(false, bundleManagerHelper.IsSystemApp(uid)); +} + +/** + * @tc.number : BundleManagerHelper_00500 + * @tc.name : BundleManagerHelper_00500 + * @tc.desc : test GetBundleInfoByBundleName function and bundleMgr_ == nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00500, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(true); + bundleManagerHelper.Connect(); + std::string bundle = "aa"; + int32_t userId = 1; + AppExecFwk::BundleInfo bundleInfo; + ASSERT_EQ(false, bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo)); +} + +/** + * @tc.number : BundleManagerHelper_00600 + * @tc.name : BundleManagerHelper_00600 + * @tc.desc : test GetBundleInfoByBundleName function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00600, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(false); + bundleManagerHelper.Connect(); + std::string bundle = "aa"; + int32_t userId = 1; + AppExecFwk::BundleInfo bundleInfo; + ASSERT_EQ(false, bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo)); +} + +/** + * @tc.number : BundleManagerHelper_00700 + * @tc.name : BundleManagerHelper_00700 + * @tc.desc : test CheckApiCompatibility function and GetBundleInfoByBundleName is false + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00700, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + ASSERT_EQ(false, bundleManagerHelper.CheckApiCompatibility(bundleOption)); +} + +/** + * @tc.number : BundleManagerHelper_00800 + * @tc.name : BundleManagerHelper_00800 + * @tc.desc : test Connect function and systemAbilityManager is nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00800, Function | SmallTest | Level1) +{ + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + MockGetSystemAbilityManager(true); + bundleManagerHelper->Connect(); +} + +/** + * @tc.number : BundleManagerHelper_00900 + * @tc.name : BundleManagerHelper_00900 + * @tc.desc : test Connect function and systemAbilityManager is not nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00900, Function | SmallTest | Level1) +{ + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + MockGetSystemAbilityManager(false); + // test Connect and bundleMgr_ == nullptr + bundleManagerHelper->Connect(); +} + +/** + * @tc.number : BundleManagerHelper_01000 + * @tc.name : BundleManagerHelper_01000 + * @tc.desc : test Connect function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01000, Function | SmallTest | Level1) +{ + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + MockGetSystemAbilityManager(false); + bundleManagerHelper->Connect(); + // test Connect and bundleMgr_ != nullptr + bundleManagerHelper->Connect(); +} + +/** + * @tc.number : BundleManagerHelper_01100 + * @tc.name : BundleManagerHelper_01100 + * @tc.desc : test Disconnect function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01100, Function | SmallTest | Level1) +{ + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + MockGetSystemAbilityManager(false); + bundleManagerHelper->Connect(); + bundleManagerHelper->Disconnect(); +} + +/** + * @tc.number : BundleManagerHelper_01200 + * @tc.name : BundleManagerHelper_01200 + * @tc.desc : test Disconnect function and bundleMgr_ == nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01200, Function | SmallTest | Level1) +{ + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + bundleManagerHelper->Disconnect(); +} + +/** + * @tc.number : BundleManagerHelper_01300 + * @tc.name : BundleManagerHelper_01300 + * @tc.desc : test GetDefaultUidByBundleName function and bundleMgr_ == nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01300, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(true); + std::string bundle = "aa"; + int32_t userId = 1; + ASSERT_EQ(-1, bundleManagerHelper.GetDefaultUidByBundleName(bundle, userId)); +} + +/** + * @tc.number : BundleManagerHelper_01400 + * @tc.name : BundleManagerHelper_01400 + * @tc.desc : test GetDefaultUidByBundleName function and bundleMgr_ != nullptr + */ +HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01400, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + MockGetSystemAbilityManager(false); + std::string bundle = "aa"; + int32_t userId = 1; + ASSERT_EQ(-1, bundleManagerHelper.GetDefaultUidByBundleName(bundle, userId)); +} + +/** + * @tc.number : GetBundleInfos_00001 + * @tc.name : GetBundleInfos_00001 + * @tc.desc : test GetBundleInfos + */ +HWTEST_F(BundleManagerHelperBranchTest, GetBundleInfos_00001, Function | SmallTest | Level1) +{ + BundleManagerHelper bundleManagerHelper; + AppExecFwk::BundleFlag flag = AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT; + std::vector bundleInfos; + + ASSERT_EQ(false, bundleManagerHelper.GetBundleInfos(flag, bundleInfos, 1)); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/bundle_manager_helper_branch_test/mock_service_registry.cpp b/services/reminder/test/unittest/bundle_manager_helper_branch_test/mock_service_registry.cpp new file mode 100755 index 000000000..e6d1d346a --- /dev/null +++ b/services/reminder/test/unittest/bundle_manager_helper_branch_test/mock_service_registry.cpp @@ -0,0 +1,43 @@ +/* + * Copyright (c) 2022 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 "iservice_registry.h" + +#include "ipc_skeleton.h" +#include "iremote_object.h" + +namespace { + bool g_mockGetSystemAbilityManagerRet = true; +} + +void MockGetSystemAbilityManager(bool mockRet) +{ + g_mockGetSystemAbilityManagerRet = mockRet; +} + +namespace OHOS { +sptr SystemAbilityManagerClient::GetSystemAbilityManager() +{ + if (false == g_mockGetSystemAbilityManagerRet) { + if (systemAbilityManager_ != nullptr) { + return systemAbilityManager_; + } + sptr registryObject = IPCSkeleton::GetContextObject(); + systemAbilityManager_ = iface_cast(registryObject); + return systemAbilityManager_; + } + return nullptr; +} +} // namespace OHOS diff --git a/services/reminder/test/unittest/bundle_manager_helper_test.cpp b/services/reminder/test/unittest/bundle_manager_helper_test.cpp new file mode 100644 index 000000000..3f9845635 --- /dev/null +++ b/services/reminder/test/unittest/bundle_manager_helper_test.cpp @@ -0,0 +1,160 @@ +/* + * Copyright (c) 2021-2023 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 + +#define private public +#define protected public +#include "bundle_manager_helper.h" +#undef private +#undef protected + +#include "if_system_ability_manager.h" +#include "ipc_skeleton.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" +#include "access_token_helper.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class BundleManagerHelperTest : public testing::Test { +public: + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; +}; + +/** + * @tc.number : BundleManagerHelperTest_00100 + * @tc.name : ANS_GetBundleNameByUid_0100 + * @tc.desc : Test GetBundleNameByUid function + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) +{ + pid_t callingUid = IPCSkeleton::GetCallingUid(); + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + ASSERT_EQ(bundleManager->GetBundleNameByUid(callingUid), "bundleName"); +} + +/** + * @tc.number : BundleManagerHelperTest_00200 + * @tc.name : ANS_IsSystemApp_0100 + * @tc.desc : Test IsSystemApp function + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) +{ + pid_t callingUid = 100; + std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + EXPECT_TRUE(bundleManager->IsSystemApp(callingUid)); +} + +/** + * @tc.number : BundleManagerHelperTest_00300 + * @tc.name : CheckApiCompatibility + * @tc.desc : Test CheckApiCompatibility function when the bundleOption is nullptr,return is true + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00300, Level1) +{ + sptr bundleOption = nullptr; + BundleManagerHelper bundleManagerHelper; + bool result = bundleManagerHelper.CheckApiCompatibility(bundleOption); + ASSERT_EQ(result, true); +} + +/** + * @tc.number : BundleManagerHelperTest_00301 + * @tc.name : CheckApiCompatibility + * @tc.desc : Test CheckApiCompatibility function when the bundleOption is nullptr,return is true + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00301, Level1) +{ + std::string bundleName = "BundleName"; + int32_t uid = 10; + sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); + BundleManagerHelper bundleManagerHelper; + bool result = bundleManagerHelper.CheckApiCompatibility(bundleOption); + ASSERT_EQ(result, true); +} + +/** + * @tc.number : BundleManagerHelperTest_00400 + * @tc.name : GetBundleInfoByBundleName + * @tc.desc : get bundleinfo by bundlename when the parameeter are normal, return is true + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00400, Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 1; + AppExecFwk::BundleInfo bundleInfo; + BundleManagerHelper bundleManagerHelper; + bool result = bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo); + ASSERT_EQ(result, true); +} + +/** + * @tc.number : BundleManagerHelperTest_00500 + * @tc.name : GetDefaultUidByBundleName + * @tc.desc : Test GetDefaultUidByBundleName function when the parameeter are normal + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00500, Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 1; + BundleManagerHelper bundleManagerHelper; + int32_t result = bundleManagerHelper.GetDefaultUidByBundleName(bundle, userId); + ASSERT_EQ(result, 1000); +} + +/** + * @tc.number : GetDistributedNotificationEnabled_00100 + * @tc.name : GetDistributedNotificationEnabled + * @tc.desc : Test GetDistributedNotificationEnabled function when the parameeter are normal + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, GetDistributedNotificationEnabled_00100, Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 1; + BundleManagerHelper bundleManagerHelper; + bool result = bundleManagerHelper.GetDistributedNotificationEnabled(bundle, userId); + ASSERT_EQ(result, true); +} + +/** + * @tc.number : GetDistributedNotificationEnabled_00101 + * @tc.name : GetDistributedNotificationEnabled + * @tc.desc : Test GetDistributedNotificationEnabled function when the parameeter are normal + * @tc.require : issueI5S4VP + */ +HWTEST_F(BundleManagerHelperTest, GetDistributedNotificationEnabled_00101, Level1) +{ + std::string bundle = "Bundle"; + int32_t userId = 1; + std::shared_ptr bundleManagerHelper = std::make_shared(); + ASSERT_NE(nullptr, bundleManagerHelper); + sptr remoteObject; + bundleManagerHelper->bundleMgr_ = iface_cast(remoteObject); + bool result = bundleManagerHelper->GetDistributedNotificationEnabled(bundle, userId); + ASSERT_EQ(result, true); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/blob.cpp b/services/reminder/test/unittest/mock/blob.cpp new file mode 100644 index 000000000..9acb0f99d --- /dev/null +++ b/services/reminder/test/unittest/mock/blob.cpp @@ -0,0 +1,195 @@ +/* + * 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 + +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()) { + 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; +} + +/* 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/reminder/test/unittest/mock/distributed_kv_data_manager.cpp b/services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp new file mode 100644 index 000000000..fd12f6b0a --- /dev/null +++ b/services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp @@ -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. + */ + +#define LOG_TAG "DistributedKvDataManager" + +#include "distributed_kv_data_manager.h" +#include "mock_single_kv_store.h" +#include "types.h" + +namespace OHOS { +namespace DistributedKv { +DistributedKvDataManager::DistributedKvDataManager() +{} + +DistributedKvDataManager::~DistributedKvDataManager() +{} + +Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, + std::shared_ptr &kvStore) +{ + std::string storeIdTmp = storeId.storeId; + kvStore = std::make_shared(); + return Status::SUCCESS; +} + +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr &kvStorePtr) +{ + return Status::SUCCESS; +} + +Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &path) +{ + 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/reminder/test/unittest/mock/include/mock_ans_subscriber.h b/services/reminder/test/unittest/mock/include/mock_ans_subscriber.h new file mode 100644 index 000000000..8914fea6f --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_ans_subscriber.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2023-2024 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_MOCK_ANS_SUBCRIBER_OBJECT_H +#define BASE_NOTIFICATION_MOCK_ANS_SUBCRIBER_OBJECT_H + +#include "gmock/gmock.h" +#include "ans_subscriber_interface.h" + +namespace OHOS { +namespace Notification { +class MockAnsSubscriber : public AnsSubscriberInterface { +public: + MockAnsSubscriber() {} + ~MockAnsSubscriber() {} + + sptr AsObject() override + { + return nullptr; + } + void OnConnected() override {}; + + void OnDisconnected() override {}; + + void OnConsumed( + const sptr ¬ification, const sptr ¬ificationMap) override {}; + + MOCK_METHOD(void, OnConsumedList, (const std::vector> ¬ifications, + const sptr ¬ificationMap)); + + void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, + int32_t deleteReason) override {}; + + void OnCanceledList(const std::vector> ¬ifications, + const sptr ¬ificationMap, int32_t deleteReason) override {}; + + void OnUpdated(const sptr ¬ificationMap) override {}; + + void OnDoNotDisturbDateChange(const sptr &date) override {}; + + void OnEnabledNotificationChanged(const sptr &callbackData) override {}; + + void OnBadgeChanged(const sptr &badgeData) override {}; + + void OnBadgeEnabledChanged(const sptr &callbackData) override {}; +}; +} // namespace Notification +} // namespace OHOS +#endif diff --git a/services/reminder/test/unittest/mock/include/mock_bundle_mgr.h b/services/reminder/test/unittest/mock/include/mock_bundle_mgr.h new file mode 100644 index 000000000..c29406682 --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_bundle_mgr.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2023-2023 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_MOCK_BUNDLE_MANAGER_H +#define BASE_NOTIFICATION_MOCK_BUNDLE_MANAGER_H + +#include "bundle_info.h" +#include "iremote_proxy.h" +#include "bundle_mgr_interface.h" + +namespace OHOS { +namespace AppExecFwk { +class BundleMgrProxy : public IRemoteProxy { +public: + explicit BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) {} + virtual ~BundleMgrProxy() {} + + ErrCode GetNameForUid(const int uid, std::string &name) override; + bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, + BundleInfo &bundleInfo, int32_t userId) override; + int GetUidByBundleName(const std::string &bundleName, const int userId) override; + bool GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) override; +}; +} // namespace AppExecFwk +} // namespace OHOS + +#endif // MOCK_OHOS_EDM_MOCK_BUNDLE_MANAGER_H diff --git a/services/reminder/test/unittest/mock/include/mock_ipc_skeleton.h b/services/reminder/test/unittest/mock/include/mock_ipc_skeleton.h new file mode 100644 index 000000000..56591d38e --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_ipc_skeleton.h @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef OHOS_IPC_IPC_SKELETON_H +#define OHOS_IPC_IPC_SKELETON_H + +#include "accesstoken_kit.h" +#include "iremote_object.h" + +namespace OHOS { +class IPCSkeleton { +public: + IPCSkeleton() = default; + ~IPCSkeleton() = default; + + /** + * @brief Set the max number of work thread. + * Default max is 4, only if you need a customize value. + * + * @param maxThreadNum Indicates the max number of work thread + * @return Indicates the result. + */ + static bool SetMaxWorkThreadNum(int maxThreadNum); + + /** + * @brief Join current thread into work loop. + */ + static void JoinWorkThread(); + + /** + * @brief Remove current thread from work loop. + */ + static void StopWorkThread(); + + /** + * @brief Get calling pid. + * + * @return Indicates the calling pid. + */ + static pid_t GetCallingPid(); + + /** + * @brief Get calling uid. + * + * @return Indicates the calling uid. + */ + static pid_t GetCallingUid(); + + /** + * @brief Get the ID of local device. + * + * @return Indicates the ID of local device. + */ + static std::string GetLocalDeviceID(); + + static Security::AccessToken::AccessTokenID GetCallingTokenID(); + + /** + * @brief Get the ID of calling device. + * + * @return Indicates the ID of calling device. + */ + static std::string GetCallingDeviceID(); + + /** + * @brief Whether it is locally calling. + * + * @return Return ture for calling from local, otherwise false. + */ + static bool IsLocalCalling(); + + /** + * @brief Get the instance. + * + * @return Indicates the instance. + */ + static IPCSkeleton &GetInstance(); + + /** + * @brief Get the object of context. + * + * @return Indicates the context cobject. + */ + static sptr GetContextObject(); + + /** + * @brief Set the object of context. + * + * @param object Indicates the context cobject. + * @return Indicates the result. + */ + static bool SetContextObject(sptr &object); + + /** + * @brief Flush the commands. + * + * @param object Indicates the object. + * @return Indicates the result. + */ + static int FlushCommands(IRemoteObject *object); + + /** + * @brief Reset calling identity. + * + * @return Indicates the result. + */ + static std::string ResetCallingIdentity(); + + /** + * @brief Set calling identity. + * + * @param identity Indicates the identity. + * @return Indicates the result. + */ + static bool SetCallingIdentity(std::string &identity); + + /** + * @brief Set calling uid. + * + * @param uid Indicates the uid. + */ + static void SetCallingUid(pid_t uid); + + static void SetCallingTokenID(Security::AccessToken::AccessTokenID callerToken); +}; +} // namespace OHOS +#endif // OHOS_IPC_IPC_SKELETON_H diff --git a/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h b/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h new file mode 100644 index 000000000..f514360df --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2023 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_PUSH_CALL_BACK_STUB_H +#define ANS_MOCK_PUSH_CALL_BACK_STUB_H + +#include +#include + +#include "push_callback_interface.h" + +namespace OHOS { +class MockPushCallBackStub : public IRemoteStub { +public: + MockPushCallBackStub(); + virtual ~MockPushCallBackStub(); + virtual int32_t OnCheckNotification(const std::string ¬ificationData, + const std::shared_ptr &pushCallBackParam) override; +}; +} // namespace OHOS +#endif // ANS_MOCK_PUSH_CALL_BACK_STUB_H diff --git a/services/reminder/test/unittest/mock/include/mock_single_kv_store.h b/services/reminder/test/unittest/mock/include/mock_single_kv_store.h new file mode 100644 index 000000000..844a4ad5a --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_single_kv_store.h @@ -0,0 +1,338 @@ +/* + * 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 "data_query.h" +#include "kvstore.h" +#include "kvstore_observer.h" +#include "kvstore_result_set.h" +#include "kvstore_sync_callback.h" +#include "single_kvstore.h" +#include "types.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 MockSingleKvStore : public SingleKvStore { +public: + /** + * @brief Get all entries in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ + Status GetEntries(const Key &prefixKey, std::vector &entries) const override; + + /** + * @brief Get all entries in this store by query. + * + * @param query Indicates the query object. + * @param entries Indicates the entries. + * @return Indicates the status of this GetEntries operation. + */ + Status GetEntries(const DataQuery &query, std::vector &entries) const override; + + /** + * @brief Get ResultSet in this store which key start with prefixKey. + * + * @param perfixkey Indicates the prefix to be searched. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ + Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; + + /** + * @brief Get ResultSet in this store by Query. + * + * @param query Indicates the query object. + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this GetResultSet operation. + */ + Status GetResultSet(const DataQuery &query, std::shared_ptr &resultSet) const override; + + /** + * @brief Close the ResultSet returned by GetResultSet. + * + * @param resultSet Indicates the resultSet. + * @return Indicates the status of this CloseResultSet operation. + */ + Status CloseResultSet(std::shared_ptr &resultSet) override; + + /** + * @brief Get the number of result by query. + * + * @param query Indicates the query object. + * @param result Indicates the result will be returned in this parameter. + * @return Indicates the status of this CloseResultSet operation. + */ + Status GetCount(const DataQuery &query, int &result) const override; + + /** + * @brief Sync store with other devices. This is an asynchronous method, + * sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync. + * @param mode Indicates the sync 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. + * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. + * @return Indicates the status of this Sync operation. + */ + Status Sync(const std::vector &deviceIds, SyncMode mode, uint32_t delayMs) override; + + /** + * @brief Remove the device data synced from remote. + * + * @param device Indicates the device id. + * @return Indicates the status of this remove operation. + */ + Status RemoveDeviceData(const std::string &device) override; + + /** + * @brief Get id of this AppKvStore. + * + * @return Indicates the id of store. + */ + StoreId GetStoreId() const override; + + /** + * @brief Delete an entry by its key. + * + * @param key Indicates the key of the entry to be deleted. + * @return Indicates the status of this delete operation. + */ + Status Delete(const Key &key) override; + + /** + * @brief Write a pair of key and value to this store. + * + * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. + * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. + * @return Indicates the status of this put operation. + */ + Status Put(const Key &key, const Value &value) override; + + /** + * @brief Get value from AppKvStore by its key. + * + * @param key Indicates the key of this entry. + * @param value Indicates the value will be returned in this parameter. + * @return Indicates the status of this get operation. + */ + Status Get(const Key &key, Value &value) override; + + /** + * @brief Register change of this kvstore to a client-defined observer. + * observer->OnChange method will be called when store changes. + * One observer can subscribe more than one AppKvStore. + * + * @param subscribeType Indicates the subscribe type. + * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, + * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, + * OBSERVER_CHANGES_ALL means both native changes and synced data changes. + * @param observer Indicates the observer to subscribe changes. + * @return Indicates the status of this subscribe operation. + */ + Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + /** + * @brief Unregister a kvstore to an observer. + * + * @param subscribeType Indicates the subscribe type. + * Reserved parameter. Current is always SubscribeType::DEFAULT. + * @param observer Indicates the observer to unsubscribe this store. + * @return Indicates the status of this unsubscribe operation. + */ + Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; + + /** + * @brief Register message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ + Status RegisterSyncCallback(std::shared_ptr callback) override; + + /** + * @brief Unregister message for sync operation. + * + * @param callback Indicates the callback to register. + * @return Indicates the status of this register operation. + */ + Status UnRegisterSyncCallback() override; + + /** + * @brief 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. + * + * @param entries Indicates the entries. + * The entries's size should be less than 128 and memory size must be less than IPC transport limit. + * @return Indicates the status of this register operation. + */ + Status PutBatch(const std::vector &entries) override; + + /** + * @brief 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. + * + * @param keys Indicates the list of keys. + * The keys memory size should not be greater than IPC transport limit, and can not be empty. + * @return Indicates the status of this register operation. + */ + Status DeleteBatch(const std::vector &keys) override; + + /** + * @brief 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. + * + * @return Indicates the status of this operation. + */ + virtual Status StartTransaction() override; + + /** + * @brief 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. + * + * @return Indicates the status of this operation. + */ + virtual Status Commit() override; + + /** + * @brief 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. + * + * @return Indicates the status of this operation. + */ + virtual Status Rollback() override; + + /** + * @brief Set synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ + virtual Status SetSyncParam(const KvSyncParam &syncParam) override; + + /** + * @brief Get synchronization parameters of this store. + * + * @param syncParam Indicates the sync policy parameter. + * @return Indicates the status of this operation. + */ + virtual Status GetSyncParam(KvSyncParam &syncParam) override; + + /** + * @brief Set capability parameters of this store. + * + * @param enabled Indicates the capability Enabled status. + * @return Indicates the status of this operation. + */ + virtual Status SetCapabilityEnabled(bool enabled) const override; + + /** + * @brief Set capability parameters of this store. + * + * @param localLabels Indicates the labels of local. + * @param remoteSupportLabels Indicates the labels of remote support. + * @return Indicates the status of this operation. + */ + virtual Status SetCapabilityRange(const std::vector &localLabels, + const std::vector &remoteSupportLabels) const override; + + /** + * @brief Get security level. + * + * @param securityLevel Indicates the security level. + * @return Indicates the status of this operation. + */ + virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + + /** + * @brief Sync store with other devices only syncing the data which is satisfied with the condition. + * This is an asynchronous method, sync will fail if there is a syncing operation in progress. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. + * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. + * @return Indicates the status of this operation. + */ + virtual Status Sync(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, + std::shared_ptr syncCallback) override; + + /** + * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied + * with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * + * @return Indicates the status of this operation. + */ + virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + /** + * @brief UnSubscribe store with other devices which is satisfied with the condition. + * + * @param deviceIds Indicates the device list to sync, this is network id from soft bus. + * @param query Indicates the query condition. + * @return Indicates the status of this UnSubscribe operation. + */ + virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + /** + * @brief backup the store to a specified backup file + * + * @param file target file of backup. + * @param baseDir root path of store manager. + * @return Indicates the status of this backup operation. + */ + virtual Status Backup(const std::string &file, const std::string &baseDir) override; + + /** + * @brief restore the store from a specified backup file + * + * @param file target file of backup. + * @param baseDir root path of store manager. + * @return Indicates the status of this restore operation. + */ + virtual Status Restore(const std::string &file, const std::string &baseDir) override; + + /** + * @brief delete the backup files + * + * @param file target file of backup. + * @param baseDir root path of store manager. + * @param status result of delete backup. + * @return Indicates the status of this delete backup operation. + */ + virtual Status DeleteBackup(const std::vector &files, const std::string &baseDir, + std::map &status) override; +}; +} // namespace DistributedKv +} // namespace OHOS +#endif // SINGLE_KV_STORE_H diff --git a/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h b/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h new file mode 100644 index 000000000..7bfd08533 --- /dev/null +++ b/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2024 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_SWING_CALL_BACK_STUB_H +#define ANS_MOCK_SWING_CALL_BACK_STUB_H +#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED + +#include +#include + +#include "swing_callback_interface.h" + +namespace OHOS { +class MockSwingCallBackStub : public IRemoteStub { +public: + MockSwingCallBackStub(); + virtual ~MockSwingCallBackStub(); + virtual int32_t OnUpdateStatus(bool isEnable, int triggerMode) override; +}; +} // namespace OHOS +#endif // ANS_MOCK_SWING_CALL_BACK_STUB_H +#endif diff --git a/services/reminder/test/unittest/mock/mock_access_token_helper.cpp b/services/reminder/test/unittest/mock/mock_access_token_helper.cpp new file mode 100644 index 000000000..ee0061f47 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_access_token_helper.cpp @@ -0,0 +1,47 @@ +/* + * Copyright (c) 2022 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 "access_token_helper.h" +#include "ans_ut_constant.h" +#include "ipc_skeleton.h" + +namespace OHOS { +namespace Notification { +bool AccessTokenHelper::VerifyCallerPermission( + const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission) +{ + return true; +} + +bool AccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) +{ + return callerToken == NATIVE_TOKEN; +} + +bool AccessTokenHelper::IsSystemApp() +{ + Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); + if (tokenId == NATIVE_TOKEN) { + return true; + } + return false; +} + +bool AccessTokenHelper::IsDlpHap(const Security::AccessToken::AccessTokenID &callerToken) +{ + return callerToken == DLP_NATIVE_TOKEN; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp b/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp new file mode 100644 index 000000000..721080f62 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp @@ -0,0 +1,78 @@ +/* + * Copyright (c) 2022 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 "accesstoken_kit.h" +#include "ans_log_wrapper.h" +#include "ans_ut_constant.h" +#include "ipc_skeleton.h" + +using namespace OHOS::Security::AccessToken; +namespace OHOS { +namespace Notification { +namespace { +ATokenTypeEnum g_mockGetTokenTypeFlagRet = ATokenTypeEnum::TOKEN_INVALID; +DlpType g_mockDlpType = DlpType::DLP_COMMON; +ATokenAplEnum g_mockApl = ATokenAplEnum::APL_NORMAL; +bool g_mockVerfyPermisson = true; +} + +void MockGetTokenTypeFlag(ATokenTypeEnum mockRet) +{ + g_mockGetTokenTypeFlagRet = mockRet; +} +void MockDlpType(DlpType mockRet) +{ + g_mockDlpType = mockRet; +} +void MockApl(ATokenAplEnum mockRet) +{ + g_mockApl = mockRet; +} + +void MockIsVerfyPermisson(bool isVerify) +{ + g_mockVerfyPermisson = isVerify; +} +} +} +namespace OHOS { +namespace Security { +namespace AccessToken { +int AccessTokenKit::VerifyAccessToken(AccessTokenID tokenID, const std::string& permissionName) +{ + if (!Notification::g_mockVerfyPermisson) { + return PERMISSION_DENIED; + } + + if (tokenID == Notification::NON_NATIVE_TOKEN) { + return PERMISSION_DENIED; + } + return PERMISSION_GRANTED; +} + +ATokenTypeEnum AccessTokenKit::GetTokenTypeFlag(AccessTokenID tokenID) +{ + return Notification::g_mockGetTokenTypeFlagRet; +} + +int AccessTokenKit::GetHapTokenInfo(AccessTokenID tokenID, HapTokenInfo& info) +{ + info.dlpType = Notification::g_mockDlpType; + info.apl = Notification::g_mockApl; + return 0; +} +} // namespace AccessToken +} // namespace Security +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp b/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp new file mode 100644 index 000000000..019ea855e --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2023 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 "advanced_notification_service.h" +#include "ans_inner_errors.h" + +namespace { + bool g_mockGetDistributedEnableInApplicationInfoRet = true; + bool g_mockAppInfoEnableRet = true; +} + +void MockGetDistributedEnableInApplicationInfo(bool mockRet, uint8_t mockCase = 0) +{ + g_mockGetDistributedEnableInApplicationInfoRet = mockRet; + switch (mockCase) { + case 1: { // mock for appInfoEnable + g_mockAppInfoEnableRet = true; + break; + } + default:{ + g_mockAppInfoEnableRet = false; + break; + } + } +} + +namespace OHOS { +namespace Notification { +ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo( + const sptr bundleOption, bool &enable) +{ + enable = g_mockAppInfoEnableRet; + if (g_mockGetDistributedEnableInApplicationInfoRet == false) { + return ERR_ANS_INVALID_PARAM; + } + return ERR_OK; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp new file mode 100644 index 000000000..f03a0287d --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -0,0 +1,82 @@ +/* + * Copyright (c) 2021-2022 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_manager_helper.h" + +#include "ans_ut_constant.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +namespace OHOS { +namespace Notification { +BundleManagerHelper::BundleManagerHelper() +{} + +BundleManagerHelper::~BundleManagerHelper() +{} + +void BundleManagerHelper::OnRemoteDied(const wptr &object) +{} + +std::string BundleManagerHelper::GetBundleNameByUid(int uid) +{ + return (uid == NON_BUNDLE_NAME_UID) ? "" : "bundleName"; +} + +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +{ + if (userId == 0) { + return -1; + } else { + return NON_SYSTEM_APP_UID; + } +} + +bool BundleManagerHelper::IsSystemApp(int uid) +{ + return (uid == SYSTEM_APP_UID || uid == NON_BUNDLE_NAME_UID); +} + +bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) +{ + return true; +} + +bool BundleManagerHelper::GetBundleInfoByBundleName( + const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) +{ + return true; +} + +void BundleManagerHelper::Connect() +{} + +void BundleManagerHelper::Disconnect() +{} + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) +{ + return true; +} +#endif + +bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) +{ + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp b/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp new file mode 100644 index 000000000..8ebd813fb --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp @@ -0,0 +1,72 @@ +/* + * Copyright (c) 2023-2023 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_bundle_mgr.h" + +#include +#include +#include "ans_ut_constant.h" + +namespace OHOS { +namespace Notification { +namespace { +bool g_isNonBundleName = false; +bool g_isEnable = true; +} + +void MockIsNonBundleName(bool isNonBundleName) +{ + g_isNonBundleName = isNonBundleName; +} + +void MockDistributedNotificationEnabled(bool isEnable) +{ + g_isEnable = isEnable; +} +} +} + +namespace OHOS { +namespace AppExecFwk { +ErrCode BundleMgrProxy::GetNameForUid(const int uid, std::string &name) +{ + name = Notification::g_isNonBundleName ? "": "bundleName"; + return ERR_OK; +} + +bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, + int32_t userId) +{ + return true; +} + +int BundleMgrProxy::GetUidByBundleName(const std::string &bundleName, const int userId) +{ + if (userId == 0) { + return -1; + } else { + return Notification::NON_SYSTEM_APP_UID; + } +} + +bool BundleMgrProxy::GetApplicationInfo( + const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) +{ + appInfo.distributedNotificationEnabled = Notification::g_isEnable; + return true; +} + +} // namespace AppExecFwk +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_event_handler.cpp b/services/reminder/test/unittest/mock/mock_event_handler.cpp new file mode 100644 index 000000000..acc5ca6b9 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_event_handler.cpp @@ -0,0 +1,107 @@ +/* + * 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" + +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, const std::string &taskName) +{ + return EVENT_HANDLER_ERR_INVALID_PARAM; +} + +void EventHandler::RemoveAllFileDescriptorListeners() +{} + +void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) +{} + +void EventHandler::SetEventRunner(const std::shared_ptr &runner) +{} + +void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) +{} + +void EventHandler::Dump(Dumper &dumper) +{} + +bool EventHandler::HasInnerEvent(uint32_t innerEventId) +{ + return true; +} + +bool EventHandler::HasInnerEvent(int64_t param) +{ + return true; +} + +std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) +{ + return "132123"; +} + +bool EventHandler::IsIdle() +{ + return true; +} + +void EventHandler::ProcessEvent(const InnerEvent::Pointer &) +{} +} // namespace AppExecFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_ipc.cpp b/services/reminder/test/unittest/mock/mock_ipc.cpp new file mode 100644 index 000000000..dc9c4065d --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_ipc.cpp @@ -0,0 +1,50 @@ +/* + * 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_ipc_skeleton.h" + +namespace OHOS { +#ifdef CONFIG_IPC_SINGLE +using namespace IPC_SINGLE; +#endif + +pid_t uid_ = 1; +Security::AccessToken::AccessTokenID callerToken_ = 0; + +pid_t IPCSkeleton::GetCallingUid() +{ + return uid_; +} + +pid_t IPCSkeleton::GetCallingPid() +{ + return 1; +} + +Security::AccessToken::AccessTokenID IPCSkeleton::GetCallingTokenID() +{ + return callerToken_; +} + +void IPCSkeleton::SetCallingUid(pid_t uid) +{ + uid_ = uid; +} + +void IPCSkeleton::SetCallingTokenID(Security::AccessToken::AccessTokenID callerToken) +{ + callerToken_ = callerToken; +} +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp b/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp new file mode 100644 index 000000000..db18ddcd2 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp @@ -0,0 +1,141 @@ +/* +* Copyright (c) 2021-2024 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_analytics_util.h" + +namespace OHOS { +namespace Notification { + +HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) + : sceneId_(sceneId), branchId_(branchId) +{ +} + +bool HaMetaMessage::NeedReport() const +{ + return true; +} + +HaMetaMessage& HaMetaMessage::SceneId(uint32_t sceneId) +{ + sceneId_ = sceneId; + return *this; +} + +HaMetaMessage& HaMetaMessage::BranchId(uint32_t branchId) +{ + branchId_ = branchId; + return *this; +} + +HaMetaMessage& HaMetaMessage::ErrorCode(uint32_t errorCode) +{ + errorCode_ = errorCode; + return *this; +} + +HaMetaMessage& HaMetaMessage::Message(const std::string& message, bool print) +{ + message_ = message; + return *this; +} + +HaMetaMessage& HaMetaMessage::Checkfailed(bool checkfailed) +{ + checkfailed_ = checkfailed; + return *this; +} + +HaMetaMessage& HaMetaMessage::BundleName(const std::string& bundleName) +{ + bundleName_ = bundleName; + return *this; +} + +HaMetaMessage& HaMetaMessage::AgentBundleName(const std::string& agentBundleName) +{ + agentBundleName_ = agentBundleName; + return *this; +} + +HaMetaMessage& HaMetaMessage::TypeCode(int32_t typeCode) +{ + typeCode_ = typeCode; + return *this; +} + +HaMetaMessage& HaMetaMessage::NotificationId(int32_t notificationId) +{ + notificationId_ = notificationId; + return *this; +} + +std::string HaMetaMessage::GetMessage() const +{ + return message_; +} + +HaMetaMessage& HaMetaMessage::SlotType(int32_t slotType) +{ + slotType_ = slotType; + return *this; +} + +std::string HaMetaMessage::Build() const +{ + return std::string(""); +} + +void NotificationAnalyticsUtil::ReportPublishFailedEvent(const sptr& request, + const HaMetaMessage& message) +{ + return; +} + +void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, + HaMetaMessage& message) +{ + return; +} + +void NotificationAnalyticsUtil::CommonNotificationEvent(const sptr& request, + int32_t eventCode, const HaMetaMessage& message) +{ + return; +} + +void NotificationAnalyticsUtil::ReportNotificationEvent(const sptr& request, + EventFwk::Want want, int32_t eventCode, const std::string& reason) +{ + return; +} + +void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) +{ + return; +} + +void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& message) +{ + return; +} + +void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, + int32_t eventCode, const std::string& reason) +{ + return; +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp b/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp new file mode 100644 index 000000000..450642a7d --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2023 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_push_callback_stub.h" + +namespace OHOS { +MockPushCallBackStub::MockPushCallBackStub() {} +MockPushCallBackStub::~MockPushCallBackStub() {} +int32_t MockPushCallBackStub::OnCheckNotification(const std::string ¬ificationData, + const std::shared_ptr &pushCallBackParam) +{ + return false; +} +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_single_kv_store.cpp b/services/reminder/test/unittest/mock/mock_single_kv_store.cpp new file mode 100644 index 000000000..aa774f06b --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_single_kv_store.cpp @@ -0,0 +1,187 @@ +/* + * 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 { +Status MockSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetEntries(const DataQuery &query, std::vector &entries) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetResultSet(const DataQuery &query, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::CloseResultSet(std::shared_ptr &resultSet) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetCount(const DataQuery &query, int &result) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Sync(const std::vector &deviceIds, SyncMode mode, uint32_t delayMs) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::RemoveDeviceData(const std::string &device) +{ + return Status::SUCCESS; +} + +StoreId MockSingleKvStore::GetStoreId() const +{ + StoreId storeId; + storeId.storeId = ""; + return storeId; +} + +Status MockSingleKvStore::Delete(const Key &key) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Put(const Key &key, const Value &value) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Get(const Key &key, Value &value) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::RegisterSyncCallback(std::shared_ptr callback) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::UnRegisterSyncCallback() +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::PutBatch(const std::vector &entries) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::DeleteBatch(const std::vector &keys) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::StartTransaction() +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Commit() +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Rollback() +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::SetSyncParam(const KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetSyncParam(KvSyncParam &syncParam) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::SetCapabilityEnabled(bool enabled) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::SetCapabilityRange( + const std::vector &localLabels, const std::vector &remoteSupportLabels) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) const +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Sync(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, + std::shared_ptr syncCallback) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Backup(const std::string &file, const std::string &baseDir) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::Restore(const std::string &file, const std::string &baseDir) +{ + return Status::SUCCESS; +} + +Status MockSingleKvStore::DeleteBackup( + const std::vector &files, const std::string &baseDir, + std::map &status) +{ + return Status::SUCCESS; +} +} // namespace DistributedKv +} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp b/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp new file mode 100644 index 000000000..ccd224675 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp @@ -0,0 +1,26 @@ +/* + * Copyright (c) 2024 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. + */ +#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED +#include "mock_swing_callback_stub.h" + +namespace OHOS { +MockSwingCallBackStub::MockSwingCallBackStub() {} +MockSwingCallBackStub::~MockSwingCallBackStub() {} +int32_t MockSwingCallBackStub::OnUpdateStatus(bool isEnable, int triggerMode) +{ + return 0; +} +} // namespace OHOS +#endif diff --git a/services/reminder/test/unittest/os_account_manager_helper_test.cpp b/services/reminder/test/unittest/os_account_manager_helper_test.cpp new file mode 100644 index 000000000..a13607524 --- /dev/null +++ b/services/reminder/test/unittest/os_account_manager_helper_test.cpp @@ -0,0 +1,134 @@ +/* + * Copyright (c) 2022 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "os_account_manager_helper.h" +#include "accesstoken_kit.h" + + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class OsAccountManagerHelperTest : public testing::Test { +public: + static void SetUpTestSuite() {}; + static void TearDownTestSuite() {}; + void SetUp() override {}; + void TearDown() override {}; +}; + +/** + * @tc.number : GetCurrentCallingUserId_00100 + * @tc.name : GetCurrentCallingUserId_00100 + * @tc.desc : test GetCurrentCallingUserId function + */ +HWTEST_F(OsAccountManagerHelperTest, GetCurrentCallingUserId_00100, Function | SmallTest | Level1) +{ + int32_t userId = -1; + ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetCurrentCallingUserId(userId)); +} + +/** + * @tc.number : GetOsAccountLocalIdFromUid_00100 + * @tc.name : GetOsAccountLocalIdFromUid_00100 + * @tc.desc : test GetOsAccountLocalIdFromUid function + */ +HWTEST_F(OsAccountManagerHelperTest, GetOsAccountLocalIdFromUid_00100, Function | SmallTest | Level1) +{ + int32_t userId = -1; + const int uid = 0; + ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId)); +} + +/** + * @tc.number : GetCurrentActiveUserId_00100 + * @tc.name : GetCurrentActiveUserId_00100 + * @tc.desc : test GetCurrentActiveUserId function + */ +HWTEST_F(OsAccountManagerHelperTest, GetCurrentActiveUserId_00100, Function | SmallTest | Level1) +{ + int32_t userId = -1; + ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId)); +} + +/** + * @tc.number : CheckUserExists_00100 + * @tc.name : CheckUserExists_00100 + * @tc.desc : test CheckUserExists function + */ +HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00100, Function | SmallTest | Level1) +{ + int32_t userId = 100; + ASSERT_EQ(true, OsAccountManagerHelper::GetInstance().CheckUserExists(userId)); +} + +/** + * @tc.number : CheckUserExists_00200 + * @tc.name : CheckUserExists_00200 + * @tc.desc : test CheckUserExists function + */ +HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00200, Function | SmallTest | Level1) +{ + int32_t userId = 1099; + ASSERT_EQ(false, OsAccountManagerHelper::GetInstance().CheckUserExists(userId)); +} + +/** + * @tc.number : IsSystemAccount_0100 + * @tc.name : IsSystemAccount_0100 + * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 10736) + */ +HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest | Level1) +{ + int32_t userId = 100; + ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); +} + +/** + * @tc.number : IsSystemAccount_0200 + * @tc.name : IsSystemAccount_0200 + * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 10736) + */ +HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0200, Function | SmallTest | Level1) +{ + int32_t userId = 10737; + ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); +} + +/** + * @tc.number : IsSystemAccount_0300 + * @tc.name : IsSystemAccount_0300 + * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 10736) + */ +HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest | Level1) +{ + int32_t userId = 0; + ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); +} + +/** + * @tc.number : IsSystemAccount_0400 + * @tc.name : IsSystemAccount_0400 + * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 10736) + */ +HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0400, Function | SmallTest | Level1) +{ + int32_t userId = 10736; + ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); +} +} +} \ No newline at end of file diff --git a/services/ans/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp similarity index 100% rename from services/ans/test/unittest/reminder_data_manager_test.cpp rename to services/reminder/test/unittest/reminder_data_manager_test.cpp -- Gitee From a8e9e925ad1608794b6ab4b875e0b94f52d2a9ae Mon Sep 17 00:00:00 2001 From: fengyang Date: Thu, 21 Nov 2024 10:59:12 +0800 Subject: [PATCH 13/29] push Signed-off-by: fengyang --- bundle.json | 2 + frameworks/ans/test/unittest/BUILD.gn | 4 +- frameworks/reminder/src/reminder_request.cpp | 2 +- .../reminder/{src => }/test/unittest/BUILD.gn | 4 +- .../test/unittest/reminder_helper_test.cpp | 0 .../unittest/reminder_request_alarm_test.cpp | 0 .../mock_reminder_request.cpp | 0 .../reminder_request_branch_test.cpp | 0 .../reminder_request_calendar_test.cpp | 0 .../test/unittest/reminder_request_test.cpp | 0 .../unittest/reminder_request_timer_test.cpp | 0 .../test/unittest/reminder_store_test.cpp | 0 interfaces/inner_api/reminder_request_alarm.h | 3 +- .../inner_api/reminder_request_calendar.h | 4 +- .../inner_api/reminder_request_client.h | 2 +- .../inner_api/reminder_request_factory.h | 1 + interfaces/inner_api/reminder_request_timer.h | 3 +- services/ans/test/unittest/BUILD.gn | 85 ------------------- .../reminder/src/reminder_data_manager.cpp | 2 +- services/reminder/test/unittest/BUILD.gn | 50 +++++------ 20 files changed, 36 insertions(+), 126 deletions(-) rename frameworks/reminder/{src => }/test/unittest/BUILD.gn (98%) rename frameworks/reminder/{src => }/test/unittest/reminder_helper_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_alarm_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_calendar_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_request_timer_test.cpp (100%) rename frameworks/reminder/{src => }/test/unittest/reminder_store_test.cpp (100%) diff --git a/bundle.json b/bundle.json index 9dfbd5f73..05d1d5117 100644 --- a/bundle.json +++ b/bundle.json @@ -170,10 +170,12 @@ } ], "test": [ + "//base/notification/distributed_notification_service/services/reminder/test/unittest:unittest", "//base/notification/distributed_notification_service/services/ans/test/unittest:unittest", "//base/notification/distributed_notification_service/services/distributed/test/unittest:ans_unit_test", "//base/notification/distributed_notification_service/services/test/moduletest:moduletest", "//base/notification/distributed_notification_service/frameworks/test/moduletest:moduletest", + "//base/notification/distributed_notification_service/frameworks/reminder/test/unittest:unittest", "//base/notification/distributed_notification_service/frameworks/ans/test/unittest:unittest", "//base/notification/distributed_notification_service/frameworks/core/test/unittest:unittest", "//base/notification/distributed_notification_service/test:systemtest", diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index beea27297..6127d8538 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") module_output_path = "${component_name}/unittest" -ohos_unittest("ans_reminder_unit_test") { +ohos_unittest("ans_test") { module_out_path = module_output_path include_dirs = [ @@ -115,6 +115,6 @@ ohos_unittest("ans_reminder_unit_test") { group("unittest") { testonly = true deps = [ - ":ans_unit_test", + ":ans_test", ] } diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index a5fbc34ef..caaa54b51 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -1163,7 +1163,7 @@ bool ReminderRequest::ReadReminderTypeFormParcel(Parcel &parcel, ReminderType& t ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) { ReminderType tarReminderType = ReminderType::INVALID; - ReadReminderTypeFormParcel(tarReminderType); + ReadReminderTypeFormParcel(parcel, tarReminderType); auto reminderRequest = ReminderRequestFactory::CreateReminderRequest(tarReminderType); if (reminderRequest == nullptr) { diff --git a/frameworks/reminder/src/test/unittest/BUILD.gn b/frameworks/reminder/test/unittest/BUILD.gn similarity index 98% rename from frameworks/reminder/src/test/unittest/BUILD.gn rename to frameworks/reminder/test/unittest/BUILD.gn index edddb02d8..a162e4d7e 100644 --- a/frameworks/reminder/src/test/unittest/BUILD.gn +++ b/frameworks/reminder/test/unittest/BUILD.gn @@ -17,7 +17,7 @@ import("//build/test.gni") module_output_path = "${component_name}/unittest" -ohos_unittest("reminder_unit_test") { +ohos_unittest("reminder_test") { module_out_path = module_output_path include_dirs = [ @@ -152,7 +152,7 @@ ohos_unittest("reminder_request_branch_test") { group("unittest") { testonly = true deps = [ - ":ans_reminder_unit_test", + ":reminder_test", ":reminder_request_branch_test", ":reminder_request_test", ] diff --git a/frameworks/reminder/src/test/unittest/reminder_helper_test.cpp b/frameworks/reminder/test/unittest/reminder_helper_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_helper_test.cpp rename to frameworks/reminder/test/unittest/reminder_helper_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_alarm_test.cpp b/frameworks/reminder/test/unittest/reminder_request_alarm_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_alarm_test.cpp rename to frameworks/reminder/test/unittest/reminder_request_alarm_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp b/frameworks/reminder/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp rename to frameworks/reminder/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp rename to frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_calendar_test.cpp b/frameworks/reminder/test/unittest/reminder_request_calendar_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_calendar_test.cpp rename to frameworks/reminder/test/unittest/reminder_request_calendar_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_test.cpp b/frameworks/reminder/test/unittest/reminder_request_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_test.cpp rename to frameworks/reminder/test/unittest/reminder_request_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_request_timer_test.cpp b/frameworks/reminder/test/unittest/reminder_request_timer_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_request_timer_test.cpp rename to frameworks/reminder/test/unittest/reminder_request_timer_test.cpp diff --git a/frameworks/reminder/src/test/unittest/reminder_store_test.cpp b/frameworks/reminder/test/unittest/reminder_store_test.cpp similarity index 100% rename from frameworks/reminder/src/test/unittest/reminder_store_test.cpp rename to frameworks/reminder/test/unittest/reminder_store_test.cpp diff --git a/interfaces/inner_api/reminder_request_alarm.h b/interfaces/inner_api/reminder_request_alarm.h index e9f01d922..ab24c8984 100644 --- a/interfaces/inner_api/reminder_request_alarm.h +++ b/interfaces/inner_api/reminder_request_alarm.h @@ -110,11 +110,12 @@ public: */ bool ReadFromParcel(Parcel &parcel) override; + ReminderRequestAlarm() : ReminderRequest() {}; + protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; private: - ReminderRequestAlarm() : ReminderRequest() {}; void CheckParamValid() const; /** diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index 4aae0a889..e3167afae 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -313,6 +313,8 @@ public: */ uint64_t GetLastStartDateTime() const; + ReminderRequestCalendar() : ReminderRequest() {}; + public: static constexpr uint8_t MAX_MONTHS_OF_YEAR = 12; static constexpr uint8_t MAX_DAYS_OF_MONTH = 31; @@ -321,7 +323,7 @@ protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; private: - ReminderRequestCalendar() : ReminderRequest() {} + uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; uint64_t GetNextTriggerTime(const bool updateLast = false); diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index 42a7d726f..6c99b594c 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -127,5 +127,5 @@ private: }; } // namespace Notification } // namespace OHOS -#endif BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_CLIENT_H +#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_CLIENT_H diff --git a/interfaces/inner_api/reminder_request_factory.h b/interfaces/inner_api/reminder_request_factory.h index 26a26cea5..97d69648b 100644 --- a/interfaces/inner_api/reminder_request_factory.h +++ b/interfaces/inner_api/reminder_request_factory.h @@ -25,6 +25,7 @@ namespace OHOS { namespace Notification { class ReminderRequestFactory { +public: static ReminderRequest* CreateReminderRequest(ReminderRequest::ReminderType reminderType); }; } // namespace Notification diff --git a/interfaces/inner_api/reminder_request_timer.h b/interfaces/inner_api/reminder_request_timer.h index 527b65cbe..4e89b48a0 100644 --- a/interfaces/inner_api/reminder_request_timer.h +++ b/interfaces/inner_api/reminder_request_timer.h @@ -71,11 +71,12 @@ public: bool ReadFromParcel(Parcel &parcel) override; + ReminderRequestTimer() {}; + protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; private: - ReminderRequestTimer() {}; void CheckParamsValid(const uint64_t countDownTimeInSeconds) const; void UpdateTimeInfo(const std::string &description); uint64_t countDownTimeInSeconds_ {0}; diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 86637a419..df7be80fc 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -17,90 +17,6 @@ import("//build/test.gni") module_output_path = "${component_name}/unittest" -ohos_unittest("reminder_unit_test") { - module_out_path = module_output_path - include_dirs = [ - ".", - "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - ] - - defines = [] - - sources = [ - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", - "mock/mock_access_token_helper.cpp", - "mock/mock_bundle_manager_helper.cpp", - "mock/mock_event_handler.cpp", - "mock/mock_ipc.cpp", - "mock/mock_single_kv_store.cpp", - "reminder_data_manager_test.cpp", - ] - - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", - "//third_party/googletest:gtest_main", - ] - - if (distributed_notification_supported) { - defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] - deps += [ "${services_path}/distributed:libans_distributed" ] - include_dirs += [ "${services_path}/distributed/include" ] - } - - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "ability_runtime:ability_manager", - "ability_runtime:abilitykit_native", - "ability_runtime:app_manager", - "ability_runtime:wantagent_innerkits", - "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "common_event_service:cesfwk_innerkits", - "data_share:datashare_common", - "data_share:datashare_consumer", - "device_manager:devicemanagersdk", - "eventhandler:libeventhandler", - "ffrt:libffrt", - "hilog:libhilog", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "image_framework:image_native", - "ipc:ipc_core", - "kv_store:distributeddata_inner", - "os_account:os_account_innerkits", - "relational_store:native_rdb", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - "time_service:time_client", - ] - - if (device_usage) { - external_deps += [ "device_usage_statistics:usagestatsinner" ] - defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] - } - - if (player_framework) { - external_deps += [ "player_framework:media_client" ] - defines += [ "PLAYER_FRAMEWORK_ENABLE" ] - } - - cflags = [] - if (hisysevent_usage) { - external_deps += [ "hisysevent:libhisysevent" ] - cflags += [ "-DHAS_HISYSEVENT_PART" ] - } - - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - ohos_unittest("ans_unit_test") { module_out_path = module_output_path include_dirs = [ @@ -1338,6 +1254,5 @@ group("unittest") { ":notification_subscriber_manager_test", ":os_account_manager_helper_test", ":push_callback_stub_test", - ":reminder_unit_test", ] } diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 7b817d834..50f31d466 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -15,7 +15,7 @@ #include "reminder_data_manager.h" -#include "ability_manager_client.h"" +#include "ability_manager_client.h" #include "ans_log_wrapper.h" #include "ans_const_define.h" #include "common_event_support.h" diff --git a/services/reminder/test/unittest/BUILD.gn b/services/reminder/test/unittest/BUILD.gn index 30c94feaa..55d36da0f 100644 --- a/services/reminder/test/unittest/BUILD.gn +++ b/services/reminder/test/unittest/BUILD.gn @@ -103,7 +103,7 @@ ohos_unittest("reminder_unit_test") { part_name = "${component_name}" } -ohos_unittest("notification_service_test") { +ohos_unittest("reminder_notification_service_test") { sanitize = { integer_overflow = true ubsan = true @@ -125,8 +125,6 @@ ohos_unittest("notification_service_test") { sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", "advanced_notification_service_test.cpp", - "advanced_notification_slot_service_test.cpp", - "advanced_notification_utils_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_access_token_helper.cpp", @@ -137,7 +135,7 @@ ohos_unittest("notification_service_test") { "mock/mock_ipc.cpp", "mock/mock_push_callback_stub.cpp", "mock/mock_single_kv_store.cpp", - "notification_dialog_test/mock_os_account_manager_annex.cpp", + "mock/mock_os_account_manager_annex.cpp", ] deps = [ @@ -200,7 +198,7 @@ ohos_unittest("notification_service_test") { part_name = "${component_name}" } -ohos_unittest("notification_publish_service_test") { +ohos_unittest("reminder_notification_publish_service_test") { sanitize = { integer_overflow = true ubsan = true @@ -232,7 +230,7 @@ ohos_unittest("notification_publish_service_test") { "mock/mock_ipc.cpp", "mock/mock_push_callback_stub.cpp", "mock/mock_single_kv_store.cpp", - "notification_dialog_test/mock_os_account_manager_annex.cpp", + "mock/mock_os_account_manager_annex.cpp", ] deps = [ @@ -296,7 +294,7 @@ ohos_unittest("notification_publish_service_test") { part_name = "${component_name}" } -ohos_unittest("notification_service_publish_test") { +ohos_unittest("reminder_notification_service_publish_test") { sanitize = { integer_overflow = true ubsan = true @@ -328,7 +326,7 @@ ohos_unittest("notification_service_publish_test") { "mock/mock_ipc.cpp", "mock/mock_push_callback_stub.cpp", "mock/mock_single_kv_store.cpp", - "notification_dialog_test/mock_os_account_manager_annex.cpp", + "mock/mock_os_account_manager_annex.cpp", ] deps = [ @@ -391,7 +389,7 @@ ohos_unittest("notification_service_publish_test") { part_name = "${component_name}" } -ohos_unittest("access_token_helper_test") { +ohos_unittest("reminder_access_token_helper_test") { module_out_path = module_output_path include_dirs = [ ".", @@ -445,7 +443,7 @@ ohos_unittest("access_token_helper_test") { part_name = "${component_name}" } -ohos_unittest("bundle_manager_helper_branch_test") { +ohos_unittest("reminder_bundle_manager_helper_branch_test") { module_out_path = module_output_path include_dirs = [ ".", @@ -498,7 +496,7 @@ ohos_unittest("bundle_manager_helper_branch_test") { part_name = "${component_name}" } -ohos_unittest("advanced_notification_service_branch_test") { +ohos_unittest("reminder_advanced_notification_service_branch_test") { module_out_path = module_output_path include_dirs = [ ".", @@ -522,8 +520,8 @@ ohos_unittest("advanced_notification_service_branch_test") { "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "notification_dialog_test/mock_os_account_manager_annex.cpp", - "notification_subscriber_manager_branch_test/mock_access_token_helper.cpp", + "mock/mock_os_account_manager_annex.cpp", + "mock/mock_access_token_helper.cpp", ] deps = [ @@ -572,7 +570,7 @@ ohos_unittest("advanced_notification_service_branch_test") { part_name = "${component_name}" } -ohos_unittest("os_account_manager_helper_test") { +ohos_unittest("reminder_os_account_manager_helper_test") { module_out_path = module_output_path include_dirs = [ ".", @@ -625,23 +623,13 @@ ohos_unittest("os_account_manager_helper_test") { group("unittest") { testonly = true deps = [ - ":access_token_helper_test", - ":advanced_notification_service_branch_test", - ":ans_unit_test", - ":bundle_manager_helper_branch_test", - ":notification_config_parse_test", - ":notification_dialog_test", - ":notification_preferences_database_branch_test", - ":notification_preferences_database_test", - ":notification_preferences_test", - ":notification_publish_service_test", - ":notification_rdb_data_mgr_test", - ":notification_service_publish_test", - ":notification_service_test", - ":notification_subscriber_manager_branch_test", - ":notification_subscriber_manager_test", - ":os_account_manager_helper_test", - ":push_callback_stub_test", + ":reminder_access_token_helper_test", + ":reminder_advanced_notification_service_branch_test", + ":reminder_bundle_manager_helper_branch_test", + ":reminder_notification_publish_service_test", + ":reminder_notification_service_publish_test", + ":reminder_notification_service_test", + ":reminder_os_account_manager_helper_test", ":reminder_unit_test", ] } -- Gitee From 0880e26b24b09c2bbd2655b1a6e1f355c440d7ae Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 22 Nov 2024 10:24:17 +0800 Subject: [PATCH 14/29] push Signed-off-by: fengyang --- frameworks/ans/test/unittest/BUILD.gn | 3 +- .../unittest/ans_image_util_test/BUILD.gn | 6 +- .../unittest/ans_manager_proxy_test/BUILD.gn | 3 +- .../ans_manager_proxy_unit_test.cpp | 85 - .../ans_manager_stub_test.cpp | 385 -- .../ans_notification_annex_test.cpp | 51 - .../ans_notification_branch_test/BUILD.gn | 3 +- .../ans_notification_branch_test.cpp | 35 - .../unittest/ans_notification_test/BUILD.gn | 3 +- .../ans_notification_unit_test.cpp | 31 - .../ans_subscriber_proxy_branch_test/BUILD.gn | 5 +- .../ans_subscriber_proxy_test/BUILD.gn | 3 +- .../ans_subscriber_stub_test/BUILD.gn | 3 +- frameworks/reminder/test/unittest/BUILD.gn | 5 +- .../test/unittest/reminder_helper_test.cpp | 7 +- frameworks/test/moduletest/BUILD.gn | 4 - notification.gni | 1 - services/ans/test/unittest/BUILD.gn | 3 - ...nced_notification_service_publish_test.cpp | 37 - services/distributed/BUILD.gn | 1 - services/distributed/test/unittest/BUILD.gn | 2 - .../include/reminder_config_change_observer.h | 4 +- .../include/reminder_service_ability.h | 1 - services/reminder/test/unittest/BUILD.gn | 305 +- .../access_token_helper_test.cpp | 56 +- ...nced_notification_publish_service_test.cpp | 1119 ----- ...nced_notification_service_ability_test.cpp | 34 +- ...anced_notification_service_branch_test.cpp | 1226 ------ .../advanced_notification_service_test.cpp | 3774 ----------------- .../bundle_manager_helper_branch_test.cpp | 105 +- .../unittest/bundle_manager_helper_test.cpp | 110 +- services/reminder/test/unittest/mock/blob.cpp | 195 - .../mock/distributed_kv_data_manager.cpp | 61 - .../mock/include/mock_ans_subscriber.h | 61 - .../mock/include/mock_push_callback_stub.h | 33 - .../mock/include/mock_single_kv_store.h | 338 -- .../mock/include/mock_swing_callback_stub.h | 33 - .../mock/mock_access_token_helper.cpp | 17 +- .../unittest/mock/mock_accesstoken_kit.cpp | 2 +- .../mock_advanced_notification_service.cpp | 51 - .../mock/mock_bundle_manager_helper.cpp | 45 +- .../test/unittest/mock/mock_bundle_mgr.cpp | 2 +- .../test/unittest/mock/mock_event_handler.cpp | 107 - .../mock/mock_notification_analytics_util.cpp | 141 - .../unittest/mock/mock_push_callback_stub.cpp | 26 - .../unittest/mock/mock_single_kv_store.cpp | 187 - .../mock/mock_swing_callback_stub.cpp | 26 - .../os_account_manager_helper_test.cpp | 89 +- .../unittest/reminder_data_manager_test.cpp | 182 +- .../test/unittest/reminder_service_test.cpp | 193 + .../reminder_service_publish_test.cpp} | 81 +- .../test/unittest/reminder_ut_constant.h} | 0 services/test/moduletest/BUILD.gn | 1 - .../notification_services_test/BUILD.gn | 1 - .../BUILD.gn | 1 - test/fuzztest/ansmanagerstub_fuzzer/BUILD.gn | 1 - .../ansmanagerstubannex_fuzzer/BUILD.gn | 1 - 57 files changed, 421 insertions(+), 8864 deletions(-) delete mode 100644 services/reminder/test/unittest/advanced_notification_publish_service_test.cpp delete mode 100644 services/reminder/test/unittest/advanced_notification_service_branch_test.cpp delete mode 100644 services/reminder/test/unittest/advanced_notification_service_test.cpp delete mode 100644 services/reminder/test/unittest/mock/blob.cpp delete mode 100644 services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp delete mode 100644 services/reminder/test/unittest/mock/include/mock_ans_subscriber.h delete mode 100644 services/reminder/test/unittest/mock/include/mock_push_callback_stub.h delete mode 100644 services/reminder/test/unittest/mock/include/mock_single_kv_store.h delete mode 100644 services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h delete mode 100644 services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp delete mode 100644 services/reminder/test/unittest/mock/mock_event_handler.cpp delete mode 100644 services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp delete mode 100644 services/reminder/test/unittest/mock/mock_push_callback_stub.cpp delete mode 100644 services/reminder/test/unittest/mock/mock_single_kv_store.cpp delete mode 100644 services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp create mode 100644 services/reminder/test/unittest/reminder_service_test.cpp rename services/reminder/test/unittest/{advanced_notification_service_test/advanced_notification_service_publish_test.cpp => reminder_service_test/reminder_service_publish_test.cpp} (57%) rename services/{ans/test/unittest/ans_ut_constant.h => reminder/test/unittest/reminder_ut_constant.h} (100%) diff --git a/frameworks/ans/test/unittest/BUILD.gn b/frameworks/ans/test/unittest/BUILD.gn index 6127d8538..095ac990a 100644 --- a/frameworks/ans/test/unittest/BUILD.gn +++ b/frameworks/ans/test/unittest/BUILD.gn @@ -25,7 +25,6 @@ ohos_unittest("ans_test") { "include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -70,7 +69,6 @@ ohos_unittest("ans_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", "${services_path}/ans:libans", - "//third_party/googletest:gtest_main", ] defines = [] @@ -91,6 +89,7 @@ ohos_unittest("ans_test") { "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "hitrace:hitrace_meter", "image_framework:image_native", diff --git a/frameworks/core/test/unittest/ans_image_util_test/BUILD.gn b/frameworks/core/test/unittest/ans_image_util_test/BUILD.gn index 703d6cf09..ba78308bd 100644 --- a/frameworks/core/test/unittest/ans_image_util_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_image_util_test/BUILD.gn @@ -33,16 +33,14 @@ ohos_unittest("ans_image_util_test") { "ans_image_util_unit_test.cpp", ] - deps = [ - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", - ] + deps = [] external_deps = [ "ability_base:want", "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "relational_store:native_rdb", diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/BUILD.gn b/frameworks/core/test/unittest/ans_manager_proxy_test/BUILD.gn index 25e4772a3..c627dc580 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/BUILD.gn @@ -32,8 +32,6 @@ ohos_unittest("ans_manager_proxy_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -41,6 +39,7 @@ ohos_unittest("ans_manager_proxy_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_core", diff --git a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp index dbfaabf11..0c78d9019 100644 --- a/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_proxy_test/ans_manager_proxy_unit_test.cpp @@ -7349,91 +7349,6 @@ HWTEST_F(AnsManagerProxyUnitTest, ShellDumpTest_0500, Function | MediumTest | Le EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, result); } -/* - * @tc.name: PublishReminder_0100 - * @tc.desc: test AnsManagerProxy's PublishReminder function - * @tc.type: FUNC - * @tc.require: #I5XO2O - */ -HWTEST_F(AnsManagerProxyUnitTest, PublishReminder_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerProxyUnitTest, PublishReminder_0100, TestSize.Level1"; - MockWriteInterfaceToken(false); - sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); - ASSERT_NE(nullptr, iremoteObject); - std::shared_ptr proxy = std::make_shared(iremoteObject); - ASSERT_NE(nullptr, proxy); - - sptr reminder = new ReminderRequest(); - ErrCode res = proxy->PublishReminder(reminder); - EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, res); -} - -/* - * @tc.name: PublishReminder_0200 - * @tc.desc: test AnsManagerProxy's PublishReminder function - * @tc.type: FUNC - * @tc.require: #I5XO2O - */ -HWTEST_F(AnsManagerProxyUnitTest, PublishReminder_0200, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerProxyUnitTest, PublishReminder_0200, TestSize.Level1"; - MockWriteInterfaceToken(true); - sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); - ASSERT_NE(nullptr, iremoteObject); - std::shared_ptr proxy = std::make_shared(iremoteObject); - ASSERT_NE(nullptr, proxy); - - sptr reminder = nullptr; - ErrCode res = proxy->PublishReminder(reminder); - EXPECT_EQ(ERR_ANS_INVALID_PARAM, res); -} - -/* - * @tc.name: PublishReminder_0300 - * @tc.desc: test AnsManagerProxy's PublishReminder function - * @tc.type: FUNC - * @tc.require: #I5XO2O - */ -HWTEST_F(AnsManagerProxyUnitTest, PublishReminder_0300, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerProxyUnitTest, PublishReminder_0300, TestSize.Level1"; - MockWriteInterfaceToken(true); - sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); - ASSERT_NE(nullptr, iremoteObject); - std::shared_ptr proxy = std::make_shared(iremoteObject); - ASSERT_NE(nullptr, proxy); - - sptr reminder = new ReminderRequest(); - ErrCode res = proxy->PublishReminder(reminder); - EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, res); -} - -/* - * @tc.name: ReadReminders_0100 - * @tc.desc: test AnsManagerProxy's ReadReminders function - * @tc.type: FUNC - * @tc.require: #I5XO2O - */ -HWTEST_F(AnsManagerProxyUnitTest, ReadReminders_0100, Function | MediumTest | Level1) -{ - GTEST_LOG_(INFO) - << "AnsManagerProxyUnitTest, ReadReminders_0100, TestSize.Level1"; - sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); - ASSERT_NE(nullptr, iremoteObject); - std::shared_ptr proxy = std::make_shared(iremoteObject); - ASSERT_NE(nullptr, proxy); - - uint8_t count = 10; - MessageParcel reply; - std::vector> reminders; - ErrCode res = proxy->ReadReminders(count, reply, reminders); - EXPECT_EQ(ERR_ANS_PARCELABLE_FAILED, res); -} - /* * @tc.name: SetBadgeNumberTest_0100 * @tc.desc: test SetBadgeNumber function diff --git a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp index 8623c8d42..6ad143fb9 100644 --- a/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp +++ b/frameworks/core/test/unittest/ans_manager_stub_test/ans_manager_stub_test.cpp @@ -25,9 +25,6 @@ #define protected public #include "ans_manager_stub.h" #include "ans_subscriber_stub.h" -#include "reminder_request_alarm.h" -#include "reminder_request_timer.h" -#include "reminder_request_calendar.h" #include "ans_dialog_host_client.h" #include "notification_subscriber.h" #undef private @@ -3072,291 +3069,6 @@ HWTEST_F(AnsManagerStubTest, HandleShellDump04, Function | SmallTest | Level1) EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); } -/** - * @tc.name: HandlePublishReminder01 - * @tc.desc: Test Reminder type ALARM. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::ALARM); - sptr reminder = new ReminderRequest(); - sptr reminderRequestAlarm = new ReminderRequestAlarm(); - - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteUint8(typeInfo); - data.WriteStrongParcelable(reminder); - data.WriteParcelable(reminderRequestAlarm); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandlePublishReminder02 - * @tc.desc: Test Reminder type invalid. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder02, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); - sptr reminder = new ReminderRequest(); - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteUint8(typeInfo); - data.WriteParcelable(reminder); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: HandlePublishReminder03 - * @tc.desc: Test reminder in date is null. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder03, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - -/** - * @tc.name: HandlePublishReminder04 - * @tc.desc: Test Reminder type TIMER. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder04, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::TIMER); - sptr reminder = new ReminderRequest(); - sptr reminderRequestTimer = new ReminderRequestTimer(); - - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteUint8(typeInfo); - data.WriteStrongParcelable(reminder); - data.WriteParcelable(reminderRequestTimer); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandlePublishReminder05 - * @tc.desc: Test Reminder type CALENDAR. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder05, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::CALENDAR); - sptr reminder = new ReminderRequest(); - sptr reminderRequestCalendar = new ReminderRequestCalendar(); - - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteUint8(typeInfo); - data.WriteStrongParcelable(reminder); - data.WriteParcelable(reminderRequestCalendar); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandlePublishReminder06 - * @tc.desc: Test typeInfo in date is null. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandlePublishReminder06, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::PUBLISH_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - sptr reminder = new ReminderRequest(); - sptr reminderRequestCalendar = new ReminderRequestCalendar(); - - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteStrongParcelable(reminder); - data.WriteParcelable(reminderRequestCalendar); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - -/** - * @tc.name: HandleCancelReminder01 - * @tc.desc: Test HandleCancelReminder ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleCancelReminder01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::CANCEL_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - int32_t reminderId = 4; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - data.WriteInt32(reminderId); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandleCancelReminder02 - * @tc.desc: Test reminderId in data is null. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleCancelReminder02, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::CANCEL_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - -/** - * @tc.name: HandleCancelAllReminders01 - * @tc.desc: Test HandleCancelAllReminders result ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleCancelAllReminders01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::CANCEL_ALL_REMINDERS); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandleGetValidReminders01 - * @tc.desc: Test HandleGetValidReminders result ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleGetValidReminders01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::GET_ALL_VALID_REMINDERS); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: HandleAddExcludeDate01 - * @tc.desc: Test HandleAddExcludeDate result ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleAddExcludeDate01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::ADD_EXCLUDE_DATE_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - -/** - * @tc.name: HandleDelExcludeDates01 - * @tc.desc: Test HandleDelExcludeDates result ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleDelExcludeDates01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::DEL_EXCLUDE_DATES_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - -/** - * @tc.name: HandleGetExcludeDates01 - * @tc.desc: Test HandleGetExcludeDates result ERR_INVALID_OPERATION. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, HandleGetExcludeDates01, Function | SmallTest | Level1) -{ - uint32_t code = static_cast(NotificationInterfaceCode::GET_EXCLUDE_DATES_REMINDER); - MessageParcel data; - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - - data.WriteInterfaceToken(AnsManagerStub::GetDescriptor()); - - ErrCode ret = ansManagerStub_->OnRemoteRequest(code, data, reply, option); - EXPECT_EQ(ret, (int)ERR_ANS_PARCELABLE_FAILED); -} - /** * @tc.name: ReadParcelableVector01 * @tc.desc: Test ReadParcelableVector result. @@ -4540,103 +4252,6 @@ HWTEST_F(AnsManagerStubTest, CancelContinuousTaskNotification01, Function | Smal EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); } -/** - * @tc.name: PublishReminder01 - * @tc.desc: Test PublishReminder return. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, PublishReminder01, Function | SmallTest | Level1) -{ - sptr reminder = new ReminderRequest(); - - ErrCode result = ansManagerStub_->PublishReminder(reminder); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: CancelReminder01 - * @tc.desc: Test CancelReminder return. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, CancelReminder01, Function | SmallTest | Level1) -{ - int32_t reminderId = 5; - - ErrCode result = ansManagerStub_->CancelReminder(reminderId); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: GetValidReminders01 - * @tc.desc: Test GetValidReminders return. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, GetValidReminders01, Function | SmallTest | Level1) -{ - std::vector> reminders; - sptr reminder = new ReminderRequest(); - reminders.emplace_back(reminder); - - ErrCode result = ansManagerStub_->GetValidReminders(reminders); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: CancelAllReminders01 - * @tc.desc: Test CancelAllReminders return. - * @tc.type: FUNC - * @tc.require: issueI620XB - */ -HWTEST_F(AnsManagerStubTest, CancelAllReminders01, Function | SmallTest | Level1) -{ - ErrCode result = ansManagerStub_->CancelAllReminders(); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: AddExcludeDate01 - * @tc.desc: Test AddExcludeDate return. - * @tc.type: FUNC - * @tc.require: issue#I9F24R - */ -HWTEST_F(AnsManagerStubTest, AddExcludeDate01, Function | SmallTest | Level1) -{ - int32_t reminderId = 5; - uint64_t date = 1713196800000; - ErrCode result = ansManagerStub_->AddExcludeDate(reminderId, date); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: DelExcludeDates01 - * @tc.desc: Test DelExcludeDates return. - * @tc.type: FUNC - * @tc.require: issue#I9F24R - */ -HWTEST_F(AnsManagerStubTest, DelExcludeDates01, Function | SmallTest | Level1) -{ - int32_t reminderId = 5; - ErrCode result = ansManagerStub_->DelExcludeDates(reminderId); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - -/** - * @tc.name: GetExcludeDates01 - * @tc.desc: Test GetExcludeDates return. - * @tc.type: FUNC - * @tc.require: issue#I9F24R - */ -HWTEST_F(AnsManagerStubTest, GetExcludeDates01, Function | SmallTest | Level1) -{ - int32_t reminderId = 5; - std::vector dates; - ErrCode result = ansManagerStub_->GetExcludeDates(reminderId, dates); - EXPECT_EQ(result, (int)ERR_INVALID_OPERATION); -} - /** * @tc.name: IsSupportTemplate01 * @tc.desc: Test IsSupportTemplate return. diff --git a/frameworks/core/test/unittest/ans_notification_annex_test/ans_notification_annex_test.cpp b/frameworks/core/test/unittest/ans_notification_annex_test/ans_notification_annex_test.cpp index cf9e8fe2c..09aacf0eb 100644 --- a/frameworks/core/test/unittest/ans_notification_annex_test/ans_notification_annex_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_annex_test/ans_notification_annex_test.cpp @@ -25,9 +25,6 @@ #include "ans_inner_errors.h" #include "ipc_types.h" #include "notification.h" -#include "reminder_request_alarm.h" -#include "reminder_request_calendar.h" -#include "reminder_request_timer.h" #include "singleton.h" #include "notification_subscriber.h" @@ -260,54 +257,6 @@ HWTEST_F(AnsNotificationUnitAnnexTest, PublishContinuousTaskNotification_0200, F EXPECT_EQ(ret1, ERR_ANS_NOT_SYSTEM_SERVICE); } -/* - * @tc.name: PublishReminder_0100 - * @tc.desc: test PublishReminder ErrCode ERR_ANS_SERVICE_NOT_CONNECTED. - * @tc.type: FUNC - * @tc.require: #I62SME - */ -HWTEST_F(AnsNotificationUnitAnnexTest, PublishReminder_0100, Function | MediumTest | Level1) -{ - uint64_t countDownTimeInSeconds = 0; - ReminderRequestTimer reminder = ReminderRequestTimer(countDownTimeInSeconds); - ErrCode ret = ans_->PublishReminder(reminder); - int errorcode = 201; - EXPECT_EQ(ret, errorcode); -} - -/* - * @tc.name: PublishReminder_0200 - * @tc.desc: test PublishReminder ErrCode ERR_ANS_SERVICE_NOT_CONNECTED. - * @tc.type: FUNC - * @tc.require: #I62SME - */ -HWTEST_F(AnsNotificationUnitAnnexTest, PublishReminder_0200, Function | MediumTest | Level1) -{ - std::vector daysOfWeek; - ReminderRequestAlarm reminder = ReminderRequestAlarm(0, 0, daysOfWeek); - ErrCode ret = ans_->PublishReminder(reminder); - int errorcode = 201; - EXPECT_EQ(ret, errorcode); -} - -/* - * @tc.name: PublishReminder_0300 - * @tc.desc: test PublishReminder ErrCode ERR_ANS_SERVICE_NOT_CONNECTED. - * @tc.type: FUNC - * @tc.require: #I62SME - */ -HWTEST_F(AnsNotificationUnitAnnexTest, PublishReminder_0300, Function | MediumTest | Level1) -{ - tm dateTime {}; - std::vector repeatMonths; - std::vector repeatDays; - std::vector daysOfWeek; - ReminderRequestCalendar reminder = ReminderRequestCalendar(dateTime, repeatMonths, repeatDays, daysOfWeek); - ErrCode ret = ans_->PublishReminder(reminder); - int errorcode = 201; - EXPECT_EQ(ret, errorcode); -} - /* * @tc.name: CheckImageSizeForContent_0100 * @tc.desc: test CheckImageSizeForContent. diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn index c96bda5b6..a29232655 100755 --- a/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_notification_branch_test/BUILD.gn @@ -31,8 +31,6 @@ ohos_unittest("ans_notification_branch_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -40,6 +38,7 @@ ohos_unittest("ans_notification_branch_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_single", diff --git a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp index e89508e46..c63058219 100644 --- a/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_branch_test/ans_notification_branch_test.cpp @@ -393,41 +393,6 @@ public: return ERR_ANS_INVALID_PARAM; } - ErrCode PublishReminder(sptr &reminder) override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode CancelReminder(const int32_t reminderId) override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode GetValidReminders(std::vector> &reminders) override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode CancelAllReminders() override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode AddExcludeDate(const int32_t reminderId, const uint64_t date) override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode DelExcludeDates(const int32_t reminderId) override - { - return ERR_ANS_INVALID_PARAM; - } - - ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override - { - return ERR_ANS_INVALID_PARAM; - } - ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override { return ERR_ANS_INVALID_PARAM; diff --git a/frameworks/core/test/unittest/ans_notification_test/BUILD.gn b/frameworks/core/test/unittest/ans_notification_test/BUILD.gn index 0baa458dc..64aa04f12 100644 --- a/frameworks/core/test/unittest/ans_notification_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_notification_test/BUILD.gn @@ -31,8 +31,6 @@ ohos_unittest("ans_notification_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -40,6 +38,7 @@ ohos_unittest("ans_notification_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_single", diff --git a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp index 6d499f03e..3fed63cff 100644 --- a/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp +++ b/frameworks/core/test/unittest/ans_notification_test/ans_notification_unit_test.cpp @@ -873,37 +873,6 @@ HWTEST_F(AnsNotificationUnitTest, IsDistributedEnabled_0100, Function | MediumTe EXPECT_EQ(ret5, ERR_ANS_SERVICE_NOT_CONNECTED); } -/* - * @tc.name: GetDeviceRemindType_0100 - * @tc.desc: test GetDeviceRemindType ErrCode ERR_ANS_SERVICE_NOT_CONNECTED. - * @tc.type: FUNC - * @tc.require: #I62SME - */ -HWTEST_F(AnsNotificationUnitTest, GetDeviceRemindType_0100, Function | MediumTest | Level1) -{ - MockWriteInterfaceToken(false); - sptr iremoteObject = new (std::nothrow) MockIRemoteObject(); - ASSERT_NE(nullptr, iremoteObject); - std::shared_ptr proxy = std::make_shared(iremoteObject); - ASSERT_NE(nullptr, proxy); - ans_->GetAnsManagerProxy(); - - NotificationConstant::RemindType remindType = NotificationConstant::RemindType::NONE; - ErrCode ret1 = ans_->GetDeviceRemindType(remindType); - EXPECT_EQ(ret1, ERR_ANS_SERVICE_NOT_CONNECTED); - ReminderRequest reminder; - ErrCode ret2 = ans_->PublishReminder(reminder); - EXPECT_EQ(ret2, ERR_ANS_INVALID_PARAM); - int32_t reminderId = 1; - ErrCode ret3 = ans_->CancelReminder(reminderId); - EXPECT_EQ(ret3, ERR_ANS_SERVICE_NOT_CONNECTED); - ErrCode ret4 = ans_->CancelAllReminders(); - EXPECT_EQ(ret4, ERR_ANS_SERVICE_NOT_CONNECTED); - std::vector> validReminders; - ErrCode ret5 = ans_->GetValidReminders(validReminders); - EXPECT_EQ(ret5, ERR_ANS_SERVICE_NOT_CONNECTED); -} - /* * @tc.name: IsSupportTemplate_0100 * @tc.desc: test IsSupportTemplate ErrCode ERR_ANS_SERVICE_NOT_CONNECTED. diff --git a/frameworks/core/test/unittest/ans_subscriber_proxy_branch_test/BUILD.gn b/frameworks/core/test/unittest/ans_subscriber_proxy_branch_test/BUILD.gn index c66a78698..a42d11e55 100755 --- a/frameworks/core/test/unittest/ans_subscriber_proxy_branch_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_subscriber_proxy_branch_test/BUILD.gn @@ -9,7 +9,7 @@ # 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. +# limitations under the License. import("//base/notification/distributed_notification_service/notification.gni") import("//build/ohos.gni") @@ -28,8 +28,6 @@ ohos_unittest("ans_subscriber_proxy_branch_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -37,6 +35,7 @@ ohos_unittest("ans_subscriber_proxy_branch_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_single", diff --git a/frameworks/core/test/unittest/ans_subscriber_proxy_test/BUILD.gn b/frameworks/core/test/unittest/ans_subscriber_proxy_test/BUILD.gn index 9f5c0eaf5..f5d100744 100644 --- a/frameworks/core/test/unittest/ans_subscriber_proxy_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_subscriber_proxy_test/BUILD.gn @@ -28,8 +28,6 @@ ohos_unittest("ans_subscriber_proxy_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -37,6 +35,7 @@ ohos_unittest("ans_subscriber_proxy_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_single", diff --git a/frameworks/core/test/unittest/ans_subscriber_stub_test/BUILD.gn b/frameworks/core/test/unittest/ans_subscriber_stub_test/BUILD.gn index fc967ba2c..46417089e 100644 --- a/frameworks/core/test/unittest/ans_subscriber_stub_test/BUILD.gn +++ b/frameworks/core/test/unittest/ans_subscriber_stub_test/BUILD.gn @@ -28,8 +28,6 @@ ohos_unittest("ans_subscriber_stub_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", - "//third_party/googletest:gmock_main", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -37,6 +35,7 @@ ohos_unittest("ans_subscriber_stub_test") { "ability_base:zuri", "ability_runtime:wantagent_innerkits", "c_utils:utils", + "googletest:gmock_main", "hilog:libhilog", "image_framework:image_native", "ipc:ipc_single", diff --git a/frameworks/reminder/test/unittest/BUILD.gn b/frameworks/reminder/test/unittest/BUILD.gn index a162e4d7e..ed116e6d8 100644 --- a/frameworks/reminder/test/unittest/BUILD.gn +++ b/frameworks/reminder/test/unittest/BUILD.gn @@ -26,7 +26,6 @@ ohos_unittest("reminder_test") { "/${services_path}/ans/include", "/${services_path}/reminder/include", "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -41,7 +40,6 @@ ohos_unittest("reminder_test") { "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] defines = [] @@ -62,6 +60,7 @@ ohos_unittest("reminder_test") { "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "hitrace:hitrace_meter", "image_framework:image_native", @@ -102,7 +101,6 @@ ohos_unittest("reminder_request_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_module_reminder_path}:reminder_innerkits", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -135,7 +133,6 @@ ohos_unittest("reminder_request_branch_test") { deps = [ "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_module_reminder_path}:reminder_innerkits", - "//third_party/googletest:gtest_main", ] external_deps = [ diff --git a/frameworks/reminder/test/unittest/reminder_helper_test.cpp b/frameworks/reminder/test/unittest/reminder_helper_test.cpp index a97c0ed63..799caa049 100644 --- a/frameworks/reminder/test/unittest/reminder_helper_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_helper_test.cpp @@ -45,7 +45,8 @@ HWTEST_F(ReminderHelperTest, PublishReminder_00001, Function | SmallTest | Level { ReminderRequest reminder; ReminderHelper reminderHelper; - ErrCode ret = reminderHelper.PublishReminder(reminder); + int32_t reminderId = -1; + ErrCode ret = reminderHelper.PublishReminder(reminder, reminderId); EXPECT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); } @@ -84,7 +85,7 @@ HWTEST_F(ReminderHelperTest, CancelAllReminders_00001, Function | SmallTest | Le */ HWTEST_F(ReminderHelperTest, GetValidReminders_00001, Function | SmallTest | Level1) { - std::vector> validReminders; + std::vector validReminders; ReminderHelper reminderHelper; ErrCode ret = reminderHelper.GetValidReminders(validReminders); EXPECT_NE(ret, (int)ERR_OK); @@ -156,7 +157,7 @@ HWTEST_F(ReminderHelperTest, DelExcludeDates_00001, Function | SmallTest | Level HWTEST_F(ReminderHelperTest, GetExcludeDates_00001, Function | SmallTest | Level1) { int32_t reminderId = 1; - std::vector dates; + std::vector dates; ReminderHelper reminderHelper; ErrCode ret = reminderHelper.GetExcludeDates(reminderId, dates); EXPECT_NE(ret, (int)ERR_ANS_INVALID_BUNDLE); diff --git a/frameworks/test/moduletest/BUILD.gn b/frameworks/test/moduletest/BUILD.gn index c37703db6..ead308c2a 100644 --- a/frameworks/test/moduletest/BUILD.gn +++ b/frameworks/test/moduletest/BUILD.gn @@ -40,7 +40,6 @@ ohos_moduletest("ans_fw_module_test") { "${core_path}/include", "${inner_api_path}", "${frameworks_path}/test/moduletest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -118,7 +117,6 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "${core_path}/include", "${inner_api_path}", "${frameworks_path}/test/moduletest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -186,7 +184,6 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "${core_path}/include", "${inner_api_path}", "${frameworks_path}/test/moduletest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -263,7 +260,6 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "${core_path}/include", "${inner_api_path}", "${frameworks_path}/test/moduletest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ diff --git a/notification.gni b/notification.gni index 776b78f68..e0622f0f0 100644 --- a/notification.gni +++ b/notification.gni @@ -17,7 +17,6 @@ ability_runtime_services_path = "${ability_runtime_path}/services" ability_runtime_kits_path = "${ability_runtime_path}/frameworks/kits" ability_runtime_napi_path = "${ability_runtime_path}/frameworks/js/napi" access_token_path = "//base/security/access_token" -ffrt_path = "//foundation/resourceschedule/ffrt" component_name = "distributed_notification_service" component_path = "//base/notification/distributed_notification_service" multimedia_path = "//foundation/multimedia/image_framework" diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index df7be80fc..67a8e4ea2 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -829,7 +829,6 @@ ohos_unittest("notification_subscriber_manager_branch_test") { "include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", ] defines = [] @@ -899,7 +898,6 @@ ohos_unittest("advanced_notification_service_branch_test") { "include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", ] defines = [] @@ -973,7 +971,6 @@ ohos_unittest("notification_preferences_database_branch_test") { "include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ diff --git a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp index a6ef039d2..70ed05776 100644 --- a/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp @@ -1339,43 +1339,6 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21500, GTEST_LOG_(INFO) << "PublishPreparedNotification_1000 test end"; } -/** - * @tc.number : AdvancedNotificationServiceTest_17900 - * @tc.name : PublishReminder_1000 - * @tc.desc : Test PublishReminder function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; - - int32_t reminderId = 1; - sptr reminder = new ReminderRequest(reminderId); - reminder->InitNotificationRequest(); - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); - - GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18000 - * @tc.name : PublishReminder_2000 - * @tc.desc : Test PublishReminder function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test start"; - - MockIsNonBundleName(true); - int32_t reminderId = 1; - sptr reminder = new ReminderRequest(reminderId); - reminder->InitNotificationRequest(); - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; -} - /** * @tc.number : AdvancedNotificationServiceTest_19000 * @tc.name : ANS_Publish_With_PixelMap diff --git a/services/distributed/BUILD.gn b/services/distributed/BUILD.gn index 07554f3a3..b0ca637dd 100644 --- a/services/distributed/BUILD.gn +++ b/services/distributed/BUILD.gn @@ -17,7 +17,6 @@ import("//build/ohos.gni") config("ans_distributed_config") { include_dirs = [ "${services_path}/distributed/include", - "${ffrt_path}/interfaces/kits", ] } diff --git a/services/distributed/test/unittest/BUILD.gn b/services/distributed/test/unittest/BUILD.gn index 0dd4677ed..7ff080823 100644 --- a/services/distributed/test/unittest/BUILD.gn +++ b/services/distributed/test/unittest/BUILD.gn @@ -37,7 +37,6 @@ ohos_unittest("ans_distributed_unit_test") { module_out_path = "${component_name}/unittest" include_dirs = [ "/${services_path}/distributed/include", - "${ffrt_path}/interfaces/kits", ] sources = [ @@ -382,7 +381,6 @@ ohos_unittest("distributed_notification_manager_branch_test") { module_out_path = "${component_name}/unittest" include_dirs = [ "/${services_path}/distributed/include", - "${ffrt_path}/interfaces/kits", ] sources = [ diff --git a/services/reminder/include/reminder_config_change_observer.h b/services/reminder/include/reminder_config_change_observer.h index c7981b0b8..982b7ddb1 100644 --- a/services/reminder/include/reminder_config_change_observer.h +++ b/services/reminder/include/reminder_config_change_observer.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_ANS_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H +#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H +#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_CONFIG_CHANGE_OBSERVER_H #include "configuration_observer_stub.h" diff --git a/services/reminder/include/reminder_service_ability.h b/services/reminder/include/reminder_service_ability.h index 36111f397..22251347c 100644 --- a/services/reminder/include/reminder_service_ability.h +++ b/services/reminder/include/reminder_service_ability.h @@ -21,7 +21,6 @@ #include "reminder_service.h" #include "reminder_data_manager.h" #include "system_ability_definition.h" -// #include "notification_extension_wrapper.h" namespace OHOS { namespace Notification { diff --git a/services/reminder/test/unittest/BUILD.gn b/services/reminder/test/unittest/BUILD.gn index 55d36da0f..2e0afb4db 100644 --- a/services/reminder/test/unittest/BUILD.gn +++ b/services/reminder/test/unittest/BUILD.gn @@ -30,13 +30,9 @@ ohos_unittest("reminder_unit_test") { defines = [] sources = [ - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", "mock/mock_access_token_helper.cpp", "mock/mock_bundle_manager_helper.cpp", - "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", - "mock/mock_single_kv_store.cpp", "reminder_data_manager_test.cpp", ] @@ -103,7 +99,7 @@ ohos_unittest("reminder_unit_test") { part_name = "${component_name}" } -ohos_unittest("reminder_notification_service_test") { +ohos_unittest("reminder_service_publish_test") { sanitize = { integer_overflow = true ubsan = true @@ -116,31 +112,25 @@ ohos_unittest("reminder_notification_service_test") { include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] defines = [] sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", - "advanced_notification_service_test.cpp", - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", + "reminder_service_test/reminder_service_publish_test.cpp", "mock/mock_access_token_helper.cpp", "mock/mock_accesstoken_kit.cpp", "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr.cpp", - "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", - "mock/mock_push_callback_stub.cpp", - "mock/mock_single_kv_store.cpp", - "mock/mock_os_account_manager_annex.cpp", ] deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", "//third_party/googletest:gtest_main", ] @@ -198,73 +188,42 @@ ohos_unittest("reminder_notification_service_test") { part_name = "${component_name}" } -ohos_unittest("reminder_notification_publish_service_test") { - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false - } +ohos_unittest("reminder_access_token_helper_test") { module_out_path = module_output_path include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] - defines = [] - sources = [ + "${services_path}/reminder/src/reminder_access_token_helper.cpp", + "${services_path}/reminder/test/unittest/mock/mock_accesstoken_kit.cpp", "${test_path}/mock/mock_tokenid_kit.cpp", - "advanced_notification_publish_service_test.cpp", - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", - "mock/mock_access_token_helper.cpp", - "mock/mock_accesstoken_kit.cpp", - "mock/mock_bundle_manager_helper.cpp", - "mock/mock_bundle_mgr.cpp", - "mock/mock_event_handler.cpp", - "mock/mock_ipc.cpp", - "mock/mock_push_callback_stub.cpp", - "mock/mock_single_kv_store.cpp", - "mock/mock_os_account_manager_annex.cpp", - ] - - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", - "//third_party/googletest:gtest_main", + "access_token_helper_test/access_token_helper_test.cpp", ] - if (distributed_notification_supported) { - defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] - deps += [ "${services_path}/distributed:libans_distributed" ] - include_dirs += [ "${services_path}/distributed/include" ] - } + deps = [ "${frameworks_module_reminder_path}:reminder_innerkits" ] external_deps = [ - "ability_base:base", "ability_base:want", "ability_base:zuri", - "ability_runtime:ability_manager", "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", - "device_manager:devicemanagersdk", "eventhandler:libeventhandler", - "ffrt:libffrt", "hilog:libhilog", "hitrace:hitrace_meter", "hitrace:libhitracechain", "image_framework:image_native", + "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", "os_account:os_account_innerkits", @@ -274,140 +233,34 @@ ohos_unittest("reminder_notification_publish_service_test") { "time_service:time_client", ] - if (device_usage) { - external_deps += [ "device_usage_statistics:usagestatsinner" ] - defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] - } - if (player_framework) { external_deps += [ "player_framework:media_client" ] - defines += [ "PLAYER_FRAMEWORK_ENABLE" ] - } - - cflags = [] - if (hisysevent_usage) { - external_deps += [ "hisysevent:libhisysevent" ] - cflags += [ "-DHAS_HISYSEVENT_PART" ] + defines = [ "PLAYER_FRAMEWORK_ENABLE" ] } - subsystem_name = "${subsystem_name}" part_name = "${component_name}" } -ohos_unittest("reminder_notification_service_publish_test") { - sanitize = { - integer_overflow = true - ubsan = true - boundary_sanitize = true - cfi = true - cfi_cross_dso = true - debug = false - } +ohos_unittest("reminder_bundle_manager_helper_branch_test") { module_out_path = module_output_path include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] - defines = [] - sources = [ - "${test_path}/mock/mock_tokenid_kit.cpp", - "advanced_notification_service_test/advanced_notification_service_publish_test.cpp", - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", - "mock/mock_access_token_helper.cpp", - "mock/mock_accesstoken_kit.cpp", - "mock/mock_bundle_manager_helper.cpp", - "mock/mock_bundle_mgr.cpp", - "mock/mock_event_handler.cpp", - "mock/mock_ipc.cpp", - "mock/mock_push_callback_stub.cpp", - "mock/mock_single_kv_store.cpp", - "mock/mock_os_account_manager_annex.cpp", + "bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp", + "bundle_manager_helper_branch_test/mock_service_registry.cpp", ] deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", "//third_party/googletest:gtest_main", ] - if (distributed_notification_supported) { - defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] - deps += [ "${services_path}/distributed:libans_distributed" ] - include_dirs += [ "${services_path}/distributed/include" ] - } - - external_deps = [ - "ability_base:base", - "ability_base:want", - "ability_base:zuri", - "ability_runtime:abilitykit_native", - "ability_runtime:app_manager", - "ability_runtime:wantagent_innerkits", - "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "common_event_service:cesfwk_innerkits", - "device_manager:devicemanagersdk", - "eventhandler:libeventhandler", - "ffrt:libffrt", - "hilog:libhilog", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "image_framework:image_native", - "ipc:ipc_core", - "kv_store:distributeddata_inner", - "os_account:os_account_innerkits", - "relational_store:native_rdb", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - "time_service:time_client", - ] - - if (device_usage) { - external_deps += [ "device_usage_statistics:usagestatsinner" ] - defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] - } - - if (player_framework) { - external_deps += [ "player_framework:media_client" ] - defines += [ "PLAYER_FRAMEWORK_ENABLE" ] - } - - cflags = [] - if (hisysevent_usage) { - external_deps += [ "hisysevent:libhisysevent" ] - cflags += [ "-DHAS_HISYSEVENT_PART" ] - } - - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - -ohos_unittest("reminder_access_token_helper_test") { - module_out_path = module_output_path - include_dirs = [ - ".", - "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - ] - - sources = [ - "${services_path}/ans/src/access_token_helper.cpp", - "${services_path}/ans/test/unittest/mock/mock_accesstoken_kit.cpp", - "${services_path}/ans/test/unittest/mock/mock_notification_analytics_util.cpp", - "${test_path}/mock/mock_tokenid_kit.cpp", - "access_token_helper_test/access_token_helper_test.cpp", - ] - - deps = [ "${frameworks_module_ans_path}:ans_innerkits" ] - external_deps = [ "ability_base:want", "ability_base:zuri", @@ -415,7 +268,6 @@ ohos_unittest("reminder_access_token_helper_test") { "ability_runtime:app_manager", "ability_runtime:wantagent_innerkits", "access_token:libaccesstoken_sdk", - "access_token:libtokenid_sdk", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "c_utils:utils", @@ -425,7 +277,6 @@ ohos_unittest("reminder_access_token_helper_test") { "hitrace:hitrace_meter", "hitrace:libhitracechain", "image_framework:image_native", - "init:libbegetutil", "ipc:ipc_core", "kv_store:distributeddata_inner", "os_account:os_account_innerkits", @@ -443,23 +294,20 @@ ohos_unittest("reminder_access_token_helper_test") { part_name = "${component_name}" } -ohos_unittest("reminder_bundle_manager_helper_branch_test") { +ohos_unittest("reminder_os_account_manager_helper_test") { module_out_path = module_output_path include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] - sources = [ - "bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp", - "bundle_manager_helper_branch_test/mock_service_registry.cpp", - ] + sources = [ "os_account_manager_helper_test.cpp" ] deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", "//third_party/googletest:gtest_main", ] @@ -496,37 +344,38 @@ ohos_unittest("reminder_bundle_manager_helper_branch_test") { part_name = "${component_name}" } -ohos_unittest("reminder_advanced_notification_service_branch_test") { +ohos_unittest("reminder_service_test") { + sanitize = { + integer_overflow = true + ubsan = true + boundary_sanitize = true + cfi = true + cfi_cross_dso = true + debug = false + } module_out_path = module_output_path include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - "${ffrt_path}/interfaces/kits", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] defines = [] sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", - "advanced_notification_service_branch_test.cpp", - "mock/blob.cpp", - "mock/distributed_kv_data_manager.cpp", + "reminder_service_test.cpp", + "mock/mock_access_token_helper.cpp", "mock/mock_accesstoken_kit.cpp", - "mock/mock_advanced_notification_service.cpp", "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr.cpp", - "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", - "mock/mock_single_kv_store.cpp", - "mock/mock_os_account_manager_annex.cpp", - "mock/mock_access_token_helper.cpp", ] deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", "//third_party/googletest:gtest_main", ] @@ -537,6 +386,7 @@ ohos_unittest("reminder_advanced_notification_service_branch_test") { } external_deps = [ + "ability_base:base", "ability_base:want", "ability_base:zuri", "ability_runtime:abilitykit_native", @@ -547,6 +397,7 @@ ohos_unittest("reminder_advanced_notification_service_branch_test") { "bundle_framework:appexecfwk_core", "c_utils:utils", "common_event_service:cesfwk_innerkits", + "device_manager:devicemanagersdk", "eventhandler:libeventhandler", "ffrt:libffrt", "hilog:libhilog", @@ -562,60 +413,22 @@ ohos_unittest("reminder_advanced_notification_service_branch_test") { "time_service:time_client", ] + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + if (player_framework) { external_deps += [ "player_framework:media_client" ] defines += [ "PLAYER_FRAMEWORK_ENABLE" ] } - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - -ohos_unittest("reminder_os_account_manager_helper_test") { - module_out_path = module_output_path - include_dirs = [ - ".", - "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", - ] - sources = [ "os_account_manager_helper_test.cpp" ] - - deps = [ - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", - "//third_party/googletest:gtest_main", - ] - - external_deps = [ - "ability_base:want", - "ability_base:zuri", - "ability_runtime:abilitykit_native", - "ability_runtime:app_manager", - "ability_runtime:wantagent_innerkits", - "access_token:libaccesstoken_sdk", - "bundle_framework:appexecfwk_base", - "bundle_framework:appexecfwk_core", - "c_utils:utils", - "common_event_service:cesfwk_innerkits", - "eventhandler:libeventhandler", - "hilog:libhilog", - "hitrace:hitrace_meter", - "hitrace:libhitracechain", - "image_framework:image_native", - "ipc:ipc_core", - "kv_store:distributeddata_inner", - "os_account:os_account_innerkits", - "relational_store:native_rdb", - "safwk:system_ability_fwk", - "samgr:samgr_proxy", - "time_service:time_client", - ] - - if (player_framework) { - external_deps += [ "player_framework:media_client" ] - defines = [ "PLAYER_FRAMEWORK_ENABLE" ] + cflags = [] + if (hisysevent_usage) { + external_deps += [ "hisysevent:libhisysevent" ] + cflags += [ "-DHAS_HISYSEVENT_PART" ] } + subsystem_name = "${subsystem_name}" part_name = "${component_name}" } @@ -624,11 +437,9 @@ group("unittest") { testonly = true deps = [ ":reminder_access_token_helper_test", - ":reminder_advanced_notification_service_branch_test", ":reminder_bundle_manager_helper_branch_test", - ":reminder_notification_publish_service_test", - ":reminder_notification_service_publish_test", - ":reminder_notification_service_test", + ":reminder_service_publish_test", + ":reminder_service_test", ":reminder_os_account_manager_helper_test", ":reminder_unit_test", ] diff --git a/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp b/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp index 7cd61c13c..cc6b5482d 100644 --- a/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp +++ b/services/reminder/test/unittest/access_token_helper_test/access_token_helper_test.cpp @@ -18,7 +18,7 @@ #include "accesstoken_kit.h" #define private public #define protected public -#include "access_token_helper.h" +#include "reminder_access_token_helper.h" #include "ans_log_wrapper.h" #include "ipc_skeleton.h" #undef private @@ -39,7 +39,7 @@ public: void SetUp() override; void TearDown() override; - std::shared_ptr stub_; + std::shared_ptr stub_; }; void AccessTokenHelperTest::SetUpTestCase() @@ -52,25 +52,13 @@ void AccessTokenHelperTest::TearDownTestCase() void AccessTokenHelperTest::SetUp() { - stub_ = std::make_shared(); + stub_ = std::make_shared(); } void AccessTokenHelperTest::TearDown() { } -/** - * @tc.number : AccessTokenHelperTest - * @tc.name : VerifyCallerPermission_00100 - * @tc.desc : VerifyCallerPermission success - */ -HWTEST_F(AccessTokenHelperTest, VerifyCallerPermission_00100, Function | SmallTest | Level1) -{ - AccessTokenID tokenID = 0; - string permission; - EXPECT_TRUE(stub_->VerifyCallerPermission(tokenID, permission)); -} - /** * @tc.number : AccessTokenHelperTest * @tc.name : VerifyNativeToken_00100 @@ -105,43 +93,5 @@ HWTEST_F(AccessTokenHelperTest, IsSystemApp_00200, Function | SmallTest | Level1 EXPECT_TRUE(stub_->IsSystemApp()); } -/** - * @tc.number : AccessTokenHelperTest - * @tc.name : IsDlpHap_00100 - * @tc.desc : IsDlpHap Token Type TOKEN_HAP - */ -HWTEST_F(AccessTokenHelperTest, IsDlpHap_00100, Function | SmallTest | Level1) -{ - AccessTokenID tokenID = 0; - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockDlpType(DlpType::DLP_READ); - EXPECT_TRUE(stub_->IsDlpHap(tokenID)); -} - -/** - * @tc.number : AccessTokenHelperTest - * @tc.name : IsDlpHap_00200 - * @tc.desc : IsDlpHap Token Type TOKEN_NATIVE - */ -HWTEST_F(AccessTokenHelperTest, IsDlpHap_00200, Function | SmallTest | Level1) -{ - AccessTokenID tokenID = 0; - MockDlpType(DlpType::DLP_COMMON); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_NATIVE); - EXPECT_FALSE(stub_->IsDlpHap(tokenID)); -} - - -/** - * @tc.number : AdvancedNotificationService_01300 - * @tc.name : AdvancedNotificationService_01300 - * @tc.desc : Test CheckPermission function and result is false - */ -HWTEST_F(AccessTokenHelperTest, CheckPermission_00100, Function | SmallTest | Level1) -{ - std::string permission = ""; - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - ASSERT_EQ(stub_->CheckPermission(permission), true); -} } // namespace Notification } // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp b/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp deleted file mode 100644 index 6512c10ee..000000000 --- a/services/reminder/test/unittest/advanced_notification_publish_service_test.cpp +++ /dev/null @@ -1,1119 +0,0 @@ -/* - * Copyright (c) 2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include -#include - -#include "gtest/gtest.h" - -#define private public -#include "advanced_notification_service.h" -#include "ability_manager_errors.h" -#include "ans_inner_errors.h" -#include "ans_log_wrapper.h" -#include "accesstoken_kit.h" -#include "notification_preferences.h" -#include "notification_constant.h" -#include "ans_ut_constant.h" -#include "ans_dialog_host_client.h" -#include "mock_push_callback_stub.h" - -extern void MockIsOsAccountExists(bool exists); - -using namespace testing::ext; -using namespace OHOS::Security::AccessToken; - -namespace OHOS { -namespace Notification { -extern void MockIsVerfyPermisson(bool isVerify); -extern void MockGetTokenTypeFlag(ATokenTypeEnum mockRet); -extern void MockIsSystemApp(bool isSystemApp); -class AnsPublishServiceTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); - -private: - void TestAddNotification(int notificationId, const sptr &bundle); - void RegisterPushCheck(); - -private: - static sptr advancedNotificationService_; -}; - -sptr AnsPublishServiceTest::advancedNotificationService_ = nullptr; - -void AnsPublishServiceTest::SetUpTestCase() {} - -void AnsPublishServiceTest::TearDownTestCase() {} - -void AnsPublishServiceTest::SetUp() -{ - GTEST_LOG_(INFO) << "SetUp start"; - - advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); - NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); - advancedNotificationService_->CancelAll(0); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); - MockIsSystemApp(true); - GTEST_LOG_(INFO) << "SetUp end"; -} - -void AnsPublishServiceTest::TearDown() -{ - delete advancedNotificationService_; - advancedNotificationService_ = nullptr; - GTEST_LOG_(INFO) << "TearDown"; -} - -void AnsPublishServiceTest::TestAddNotification(int notificationId, const sptr &bundle) -{ - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(slotType); - request->SetOwnerUserId(1); - request->SetCreatorUserId(1); - request->SetOwnerBundleName("test"); - request->SetOwnerUid(0); - request->SetNotificationId(notificationId); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - auto ret = advancedNotificationService_->AssignToNotificationList(record); -} - -void AnsPublishServiceTest::RegisterPushCheck() -{ - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - checkRequest->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), ERR_OK); -} - -/** - * @tc.name: Publish_00001 - * @tc.desc: Test Publish - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - auto localLiveContent = std::make_shared(); - auto content = std::make_shared(localLiveContent); - request->SetContent(content); - request->SetCreatorUid(1); - request->SetOwnerUid(1); - MockIsOsAccountExists(true); - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.name: Publish_00002 - * @tc.desc: Test Publish - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00002, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); - request->SetRemoveAllowed(false); - request->SetInProgress(true); - auto normalContent = std::make_shared(); - auto content = std::make_shared(normalContent); - request->SetContent(content); - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERR_OK); -} - - -/** - * @tc.name: Publish_00003 - * @tc.desc: Publish live_view notification once - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00003, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - request->SetNotificationId(1); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - RegisterPushCheck(); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERR_OK); - - sptr slot; - NotificationConstant::SlotType slotType = NotificationConstant::SlotType::LIVE_VIEW; - ret = advancedNotificationService_->GetSlotByType(slotType, slot); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(1, slot->GetAuthorizedStatus()); - ASSERT_EQ(1, slot->GetAuthHintCnt()); -} - -/** - * @tc.name: Publish_00004 - * @tc.desc: Publish live_view notification twice - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00004, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - request->SetNotificationId(1); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - RegisterPushCheck(); - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERR_OK); - - sptr request2 = new (std::nothrow) NotificationRequest(); - request2->SetNotificationId(2); - request2->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - request2->SetContent(content); - ret = advancedNotificationService_->Publish(label, request2); - ASSERT_EQ(ret, (int)ERR_OK); - - sptr slot; - NotificationConstant::SlotType slotType = NotificationConstant::SlotType::LIVE_VIEW; - ret = advancedNotificationService_->GetSlotByType(slotType, slot); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(0, slot->GetAuthorizedStatus()); - ASSERT_EQ(2, slot->GetAuthHintCnt()); -} - -/** - * @tc.name: Publish_00005 - * @tc.desc: Publish test receiver user and checkUserExists is true - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00005, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - request->SetNotificationId(1); - request->SetReceiverUserId(101); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - RegisterPushCheck(); - MockIsOsAccountExists(true); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: Publish_00006 - * @tc.desc: Publish test receiver user and checkUserExists is false - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, Publish_00006, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - std::string label = ""; - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - request->SetNotificationId(1); - request->SetReceiverUserId(101); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - MockIsOsAccountExists(false); - - auto ret = advancedNotificationService_->Publish(label, request); - ASSERT_EQ(ret, (int)ERROR_USER_NOT_EXIST); -} - -/** - * @tc.name: DeleteByBundle_00001 - * @tc.desc: Test DeleteByBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00001, Function | SmallTest | Level1) -{ - sptr bundleOption = nullptr; - auto ret = advancedNotificationService_->DeleteByBundle(bundleOption); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: DeleteByBundle_00002 - * @tc.desc: Test DeleteByBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00002, Function | SmallTest | Level1) -{ - sptr bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto ret = advancedNotificationService_->DeleteByBundle(bundle); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: DeleteByBundle_00003 - * @tc.desc: Test DeleteByBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DeleteByBundle_00003, Function | SmallTest | Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - TestAddNotification(1, bundle); - auto ret = advancedNotificationService_->DeleteByBundle(bundle); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 0); -} - -/** - * @tc.name: DeleteAll_00001 - * @tc.desc: Test DeleteAll - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DeleteAll_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto ret = advancedNotificationService_->DeleteAll(); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: SetShowBadgeEnabledForBundle_00001 - * @tc.desc: Test SetShowBadgeEnabledForBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, SetShowBadgeEnabledForBundle_00001, Function | SmallTest | Level1) -{ - sptr bundleOption = nullptr; - auto ret = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, true); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); - - bool enabled = false; - ret = advancedNotificationService_->GetShowBadgeEnabledForBundle(bundleOption, enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: SetShowBadgeEnabledForBundle_00002 - * @tc.desc: Test SetShowBadgeEnabledForBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, SetShowBadgeEnabledForBundle_00002, Function | SmallTest | Level1) -{ - sptr bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto ret = advancedNotificationService_->SetShowBadgeEnabledForBundle(bundle, true); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - bool enabled = false; - ret = advancedNotificationService_->GetShowBadgeEnabledForBundle(bundle, enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: GetShowBadgeEnabled_00001 - * @tc.desc: Test GetShowBadgeEnabled - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - bool enabled = false; - auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: GetShowBadgeEnabled_00002 - * @tc.desc: Test GetShowBadgeEnabled - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, GetShowBadgeEnabled_00002, Function | SmallTest | Level1) -{ - bool enabled = true; - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - auto ret = advancedNotificationService_->GetShowBadgeEnabled(enabled); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(enabled, true); -} - -/** - * @tc.name: RequestEnableNotification_00001 - * @tc.desc: Test RequestEnableNotification - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00001, Function | SmallTest | Level1) -{ - std::string deviceId = "deviceId"; - sptr client = nullptr; - AnsDialogHostClient::CreateIfNullptr(client); - client = AnsDialogHostClient::GetInstance(); - sptr callerToken = nullptr; - - auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), false); - ASSERT_EQ(ret, (int)ERR_OK); - - ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); - ASSERT_EQ(ret, (int)ERROR_INTERNAL_ERROR); -} - -/** - * @tc.name: RequestEnableNotification_00002 - * @tc.desc: Test RequestEnableNotification - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00002, Function | SmallTest | Level1) -{ - std::string deviceId = "deviceId"; - sptr client = nullptr; - AnsDialogHostClient::CreateIfNullptr(client); - client = AnsDialogHostClient::GetInstance(); - sptr callerToken = nullptr; - - auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true); - ASSERT_EQ(ret, (int)ERR_OK); - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: RequestEnableNotification_00003 - * @tc.desc: Test RequestEnableNotification - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RequestEnableNotification_00003, Function | SmallTest | Level1) -{ - std::string deviceId = "deviceId"; - sptr client = nullptr; - AnsDialogHostClient::CreateIfNullptr(client); - client = AnsDialogHostClient::GetInstance(); - sptr callerToken = nullptr; - - auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), false); - ASSERT_EQ(ret, (int)ERR_OK); - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - - auto bundle = advancedNotificationService_->GenerateBundleOption(); - NotificationPreferences::GetInstance()->SetHasPoppedDialog(bundle, true); - - ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); - ASSERT_EQ(ret, (int)ERR_ANS_NOT_ALLOWED); - - NotificationPreferences::GetInstance()->SetHasPoppedDialog(bundle, false); - ret = advancedNotificationService_->RequestEnableNotification(deviceId, client, callerToken); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: SetNotificationsEnabledForAllBundles_00001 - * @tc.desc: Test SetNotificationsEnabledForAllBundles - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, SetNotificationsEnabledForAllBundles_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - bool enabled = false; - auto ret = advancedNotificationService_->SetNotificationsEnabledForAllBundles("", enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: SetNotificationsEnabledForSpecialBundle_00001 - * @tc.desc: Test SetNotificationsEnabledForSpecialBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, SetNotificationsEnabledForSpecialBundle_00001, Function | SmallTest | Level1) -{ - sptr bundle = nullptr; - bool enabled = false; - std::string deviceId = "deviceId"; - auto ret = advancedNotificationService_->SetNotificationsEnabledForSpecialBundle(deviceId, bundle, enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: IsAllowedNotify_00001 - * @tc.desc: Test IsAllowedNotify - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, IsAllowedNotify_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - bool allowed = false; - auto ret = advancedNotificationService_->IsAllowedNotify(allowed); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: IsAllowedNotifyForBundle_00001 - * @tc.desc: Test IsAllowedNotifyForBundle - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, IsAllowedNotifyForBundle_00001, Function | SmallTest | Level1) -{ - bool allowed = false; - sptr bundle = nullptr; - auto ret = advancedNotificationService_->IsAllowedNotifyForBundle(bundle, allowed); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: TriggerLocalLiveView_00001 - * @tc.desc: Test TriggerLocalLiveView - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, TriggerLocalLiveView_00001, Function | SmallTest | Level1) -{ - int notificationId = 1; - sptr bundle = nullptr; - sptr buttonOption = nullptr; - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - MockIsVerfyPermisson(false); - - auto ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); - ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); - - MockIsSystemApp(true); - ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->TriggerLocalLiveView(bundle, notificationId, buttonOption); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: RemoveNotification_00001 - * @tc.desc: Test RemoveNotification - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveNotification_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - std::string label = "label"; - int notificationId = 1; - auto ret = advancedNotificationService_->RemoveNotification(bundle, notificationId, label, 0); - - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: RemoveNotifications_00001 - * @tc.desc: Test RemoveNotifications - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveNotifications_00001, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - std::vector keys; - int removeReason = 1; - auto ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); - ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); - - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - advancedNotificationService_->notificationSvrQueue_ = nullptr; - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: RemoveNotifications_00002 - * @tc.desc: Test RemoveNotifications - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveNotifications_00002, Function | SmallTest | Level1) -{ - std::vector keys; - int removeReason = 1; - - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - sptr req = new (std::nothrow) NotificationRequest(); - req->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - req->SetOwnerUserId(1); - req->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); - req->SetNotificationId(1); - auto record = advancedNotificationService_->MakeNotificationRecord(req, bundle); - auto ret = advancedNotificationService_->AssignToNotificationList(record); - keys.emplace_back(record->notification->GetKey()); - - ret = advancedNotificationService_->RemoveNotifications(keys, removeReason); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: RemoveNotificationBySlot_00001 - * @tc.desc: Test RemoveNotificationBySlot - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00001, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - sptr bundle = nullptr; - sptr slot = nullptr; - auto ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); - ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); - - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.name: RemoveNotificationBySlot_00002 - * @tc.desc: Test RemoveNotificationBySlot - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveNotificationBySlot_00002, Function | SmallTest | Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - sptr req = new (std::nothrow) NotificationRequest(); - req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - req->SetOwnerUserId(1); - req->SetOwnerBundleName(TEST_DEFUALT_BUNDLE); - req->SetNotificationId(1); - auto multiLineContent = std::make_shared(); - auto content = std::make_shared(multiLineContent); - req->SetContent(content); - auto record = advancedNotificationService_->MakeNotificationRecord(req, bundle); - auto ret = advancedNotificationService_->AssignToNotificationList(record); - auto slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - - ret = advancedNotificationService_->RemoveNotificationBySlot(bundle, slot, - NotificationConstant::DEFAULT_REASON_DELETE); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: NotificationSvrQueue_00001 - * @tc.desc: Test notificationSvrQueue is nullptr - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - - auto ret = advancedNotificationService_->CancelAll(0); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->Delete("", 1); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->CancelGroup("group", 0); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->RemoveGroupByBundle(bundle, "group"); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - bool allowed = false; - ret = advancedNotificationService_->IsSpecialUserAllowedNotify(1, allowed); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->SetNotificationsEnabledByUser(1, false); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->SetBadgeNumber(1, 0); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->SubscribeLocalLiveView(nullptr, nullptr, true); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/* - * @tc.name: SetDistributedEnabledByBundle_0100 - * @tc.desc: test SetDistributedEnabledByBundle with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0100, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType"; - - ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); - ASSERT_EQ(res, ERR_OK); -} - -/* - * @tc.name: SetDistributedEnabledByBundle_0200 - * @tc.desc: test SetDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0200, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType"; - - ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); - ASSERT_EQ(res, ERR_ANS_NON_SYSTEM_APP); -} - -/* - * @tc.name: SetDistributedEnabledByBundle_0300 - * @tc.desc: test SetDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetDistributedEnabledByBundle_0300, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType"; - - ErrCode res = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); - ASSERT_EQ(res, ERR_ANS_PERMISSION_DENIED); -} - - -/** - * @tc.name: IsDistributedEnabledByBundle_0100 - * @tc.desc: test IsDistributedEnabledByBundle with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0100, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType1111"; - bool enable = true; - ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - ASSERT_EQ(result, ERR_OK); -} - -/** - * @tc.name: IsDistributedEnabledByBundle_0200 - * @tc.desc: test IsDistributedEnabledByBundle with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0200, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType"; - - ErrCode ret = advancedNotificationService_->SetDistributedEnabledByBundle(bundleOption, deviceType, true); - ASSERT_EQ(ret, ERR_OK); - bool enable = false; - ret = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - ASSERT_EQ(ret, ERR_OK); - ASSERT_EQ(enable, true); -} - -/** - * @tc.name: IsDistributedEnabledByBundle_0300 - * @tc.desc: test IsDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0300, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType1111"; - bool enable = true; - ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - ASSERT_EQ(result, ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.name: IsDistributedEnabledByBundle_0400 - * @tc.desc: test IsDistributedEnabledByBundle with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsDistributedEnabledByBundle_0400, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - sptr bundleOption(new NotificationBundleOption("bundleName", 1)); - std::string deviceType = "testDeviceType1111"; - bool enable = true; - ErrCode result = advancedNotificationService_->IsDistributedEnabledByBundle(bundleOption, deviceType, enable); - ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.name: DuplicateMsgControl_00001 - * @tc.desc: Test DuplicateMsgControl - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - auto liveViewContent = std::make_shared(); - auto content = std::make_shared(liveViewContent); - request->SetContent(content); - - auto ret = advancedNotificationService_->DuplicateMsgControl(request); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: DuplicateMsgControl_00002 - * @tc.desc: Test DuplicateMsgControl - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00002, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test1"); - auto uniqueKey = request->GenerateUniqueKey(); - advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); - - auto ret = advancedNotificationService_->DuplicateMsgControl(request); - ASSERT_EQ(ret, (int)ERR_ANS_DUPLICATE_MSG); -} - -/** - * @tc.name: DuplicateMsgControl_00003 - * @tc.desc: Test DuplicateMsgControl - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, DuplicateMsgControl_00003, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - - auto ret = advancedNotificationService_->DuplicateMsgControl(request); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); -} - -/** - * @tc.name: IsDuplicateMsg_00001 - * @tc.desc: Test IsDuplicateMsg - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - auto uniqueKey = request->GenerateUniqueKey(); - - auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); - ASSERT_EQ(ret, false); -} - -/** - * @tc.name: IsDuplicateMsg_00002 - * @tc.desc: Test IsDuplicateMsg - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, IsDuplicateMsg_00002, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - auto uniqueKey = request->GenerateUniqueKey(); - advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::steady_clock::now(), uniqueKey)); - - auto ret = advancedNotificationService_->IsDuplicateMsg(uniqueKey); - ASSERT_EQ(ret, true); -} - -/** - * @tc.name: RemoveExpiredUniqueKey_00001 - * @tc.desc: Test RemoveExpiredUniqueKey - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, RemoveExpiredUniqueKey_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - auto uniqueKey = request->GenerateUniqueKey(); - advancedNotificationService_->uniqueKeyList_.emplace_back( - std::make_pair(std::chrono::steady_clock::now() - std::chrono::hours(24), uniqueKey)); - - sleep(1); - ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 1); - advancedNotificationService_->RemoveExpiredUniqueKey(); - ASSERT_EQ(advancedNotificationService_->uniqueKeyList_.size(), 0); -} - -/* - * @tc.name: SetSmartReminderEnabled_0100 - * @tc.desc: test SetSmartReminderEnabled with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0100, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); - ASSERT_EQ(res, ERR_OK); -} - -/* - * @tc.name: SetSmartReminderEnabled_0200 - * @tc.desc: test SetSmartReminderEnabled with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0200, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); - ASSERT_EQ(res, ERR_ANS_NON_SYSTEM_APP); -} - -/* - * @tc.name: SetSmartReminderEnabled_0300 - * @tc.desc: test SetSmartReminderEnabled with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, SetSmartReminderEnabled_0300, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - ErrCode res = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); - ASSERT_EQ(res, ERR_ANS_PERMISSION_DENIED); -} - - -/** - * @tc.name: IsSmartReminderEnabled_0100 - * @tc.desc: test IsSmartReminderEnabled with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0100, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - bool enable = true; - ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); - ASSERT_EQ(result, ERR_OK); -} - -/** - * @tc.name: IsSmartReminderEnabled_0200 - * @tc.desc: test IsSmartReminderEnabled with parameters - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0200, TestSize.Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - ErrCode ret = advancedNotificationService_->SetSmartReminderEnabled("testDeviceType", true); - ASSERT_EQ(ret, ERR_OK); - bool enable = false; - ret = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType", enable); - ASSERT_EQ(ret, ERR_OK); - ASSERT_EQ(enable, true); -} - -/** - * @tc.name: IsSmartReminderEnabled_0300 - * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_NON_SYSTEM_APP. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0300, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - bool enable = true; - ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); - ASSERT_EQ(result, ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.name: IsSmartReminderEnabled_0400 - * @tc.desc: test IsSmartReminderEnabled with parameters, expect errorCode ERR_ANS_PERMISSION_DENIED. - * @tc.type: FUNC - */ -HWTEST_F(AnsPublishServiceTest, IsSmartReminderEnabled_0400, TestSize.Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - bool enable = true; - ErrCode result = advancedNotificationService_->IsSmartReminderEnabled("testDeviceType1111", enable); - ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.name: PublishRemoveDuplicateEvent_00001 - * @tc.desc: Test PublishRemoveDuplicateEvent - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - request->SetNotificationId(1); - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - - auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: PublishRemoveDuplicateEvent_00002 - * @tc.desc: Test PublishRemoveDuplicateEvent - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00002, Function | SmallTest | Level1) -{ - std::shared_ptr record= nullptr; - auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: PublishRemoveDuplicateEvent_00003 - * @tc.desc: Test PublishRemoveDuplicateEvent - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, PublishRemoveDuplicateEvent_00003, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - request->SetAppMessageId("test2"); - request->SetNotificationId(1); - request->SetIsAgentNotification(true); - auto normalContent = std::make_shared(); - auto content = std::make_shared(normalContent); - request->SetContent(content); - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - - auto ret = advancedNotificationService_->PublishRemoveDuplicateEvent(record); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: CanPopEnableNotificationDialog_001 - * @tc.desc: Test CanPopEnableNotificationDialog - * @tc.type: FUNC - * @tc.require: issue - */ -HWTEST_F(AnsPublishServiceTest, CanPopEnableNotificationDialog_001, Function | SmallTest | Level1) -{ - sptr callback = nullptr; - bool canPop = false; - std::string bundleName = ""; - ErrCode result = advancedNotificationService_->CanPopEnableNotificationDialog(callback, canPop, bundleName); - ASSERT_EQ(result, ERROR_INTERNAL_ERROR); -} - -} // namespace Notification -} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp b/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp index 106779549..4cc27724b 100644 --- a/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/reminder/test/unittest/advanced_notification_service_ability_test.cpp @@ -17,13 +17,13 @@ #include #define private public #define protected public -#include "advanced_notification_service_ability.h" +#include "reminder_service_ability.h" using namespace testing::ext; namespace OHOS { namespace Notification { -class AdvancedNotificationServiceAbilityTest : public testing::Test { +class ReminderServiceAbilityTest : public testing::Test { public: static void SetUpTestCase() {}; static void TearDownTestCase() {}; @@ -32,43 +32,43 @@ public: }; /** - * @tc.number : AdvancedNotificationServiceAbilityTest_00100 - * @tc.name : ANS_AdvancedNotificationServiceAbility_0100 - * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + * @tc.number : ReminderServiceAbilityTest_00100 + * @tc.name : ReminderServiceAbility_0100 + * @tc.desc : Structure ReminderServiceAbility with systemAbilityId and runOnCreate */ HWTEST_F( - AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00100, Function | SmallTest | Level1) + ReminderServiceAbilityTest, ReminderServiceAbilityTest_00100, Function | SmallTest | Level1) { int32_t systemAbilityId = 1; bool runOnCreate = true; - AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); + ReminderServiceAbility(systemAbilityId, runOnCreate); } /** - * @tc.number : AdvancedNotificationServiceAbilityTest_00200 - * @tc.name : ANS_AdvancedNotificationServiceAbility_0200 - * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + * @tc.number : ReminderServiceAbilityTest_00200 + * @tc.name : ReminderServiceAbility_0200 + * @tc.desc : Structure ReminderServiceAbility with systemAbilityId and runOnCreate */ HWTEST_F( - AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00200, Function | SmallTest | Level1) + ReminderServiceAbilityTest, ReminderServiceAbilityTest_00200, Function | SmallTest | Level1) { int32_t systemAbilityId = 1; bool runOnCreate = true; - AdvancedNotificationServiceAbility test(systemAbilityId, runOnCreate); + ReminderServiceAbility test(systemAbilityId, runOnCreate); test.OnStart(); } /** - * @tc.number : AdvancedNotificationServiceAbilityTest_00300 - * @tc.name : ANS_AdvancedNotificationServiceAbility_0300 - * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate + * @tc.number : ReminderServiceAbilityTest_00300 + * @tc.name : ReminderServiceAbility_0300 + * @tc.desc : Structure ReminderServiceAbility with systemAbilityId and runOnCreate */ HWTEST_F( - AdvancedNotificationServiceAbilityTest, AdvancedNotificationServiceAbilityTest_00300, Function | SmallTest | Level1) + ReminderServiceAbilityTest, ReminderServiceAbilityTest_00300, Function | SmallTest | Level1) { int32_t systemAbilityId = 1; bool runOnCreate = true; - AdvancedNotificationServiceAbility test(systemAbilityId, runOnCreate); + ReminderServiceAbility test(systemAbilityId, runOnCreate); test.OnStop(); test.OnStart(); } diff --git a/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp b/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp deleted file mode 100644 index 4a0d9f06b..000000000 --- a/services/reminder/test/unittest/advanced_notification_service_branch_test.cpp +++ /dev/null @@ -1,1226 +0,0 @@ -/* - * Copyright (c) 2023-2024 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include -#include -#include - -#include "gtest/gtest.h" - -#define private public - -#include "advanced_notification_service.h" -#include "ans_const_define.h" -#include "ans_inner_errors.h" -#include "ans_log_wrapper.h" -#include "ans_subscriber_listener.h" -#include "ans_ut_constant.h" -#include "iremote_object.h" -#include "want_agent_info.h" -#include "want_agent_helper.h" -#include "want_params.h" -#include "mock_ipc_skeleton.h" -#include "notification_preferences.h" -#include "notification_constant.h" -#include "notification_record.h" -#include "notification_subscriber.h" -#include "refbase.h" - -extern void MockVerifyNativeToken(bool mockRet); -extern void MockVerifyShellToken(bool mockRet); -extern void MockGetDistributedEnableInApplicationInfo(bool mockRet, uint8_t mockCase = 0); -extern void MockGetOsAccountLocalIdFromUid(bool mockRet, uint8_t mockCase = 0); - -using namespace testing::ext; -using namespace OHOS::Media; -using namespace OHOS::Security::AccessToken; - -namespace OHOS { -namespace Notification { -extern void MockIsVerfyPermisson(bool isVerify); -extern void MockGetTokenTypeFlag(ATokenTypeEnum mockRet); -extern void MockIsSystemApp(bool isSystemApp); -extern void MockDistributedNotificationEnabled(bool isEnable); -extern void MockIsNonBundleName(bool isNonBundleName); - -class AnsBranchTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); - static void InitNotificationRecord(std::shared_ptr &record, - const NotificationLiveViewContent::LiveViewStatus &status); -private: - void TestAddSlot(NotificationConstant::SlotType type); - -private: - static sptr advancedNotificationService_; -}; - -sptr AnsBranchTest::advancedNotificationService_ = nullptr; - -void AnsBranchTest::SetUpTestCase() {} - -void AnsBranchTest::TearDownTestCase() {} - -void AnsBranchTest::SetUp() -{ - GTEST_LOG_(INFO) << "SetUp start"; - - advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); - IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); - IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - advancedNotificationService_->CancelAll(0); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); - MockIsSystemApp(true); - GTEST_LOG_(INFO) << "SetUp end"; -} - -void AnsBranchTest::TearDown() -{ - IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - advancedNotificationService_ = nullptr; - GTEST_LOG_(INFO) << "TearDown"; -} - -inline void SleepForFC() -{ - // For ANS Flow Control - std::this_thread::sleep_for(std::chrono::seconds(1)); -} - -class TestAnsSubscriber : public NotificationSubscriber { -public: - void OnDied() override - {} - void OnConnected() override - {} - void OnDisconnected() override - {} - void OnUpdate(const std::shared_ptr &sortingMap) override - {} - void OnDoNotDisturbDateChange(const std::shared_ptr &date) override - {} - void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int32_t deleteReason) override - {} - void OnEnabledNotificationChanged( - const std::shared_ptr &callbackData) override - {} - void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override - {} - void OnBadgeChanged(const std::shared_ptr &badgeData) override - {} - void OnBadgeEnabledChanged(const sptr &callbackData) override - {} - void OnBatchCanceled(const std::vector> - &requestList, const std::shared_ptr &sortingMap, int32_t deleteReason) override - {} -}; - -void AnsBranchTest::TestAddSlot(NotificationConstant::SlotType type) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - std::vector> slots; - sptr slot = new NotificationSlot(type); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); -} - -/** - * @tc.number : AnsBranchTest_222000 - * @tc.name : PrepareNotificationRequest_1000 - * @tc.desc : Test PrepareNotificationRequest function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_222000, Function | SmallTest | Level1) -{ - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - - req->SetIsAgentNotification(true); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_223000 - * @tc.name : PrepareNotificationRequest_2000 - * @tc.desc : Test PrepareNotificationRequest function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_223000, Function | SmallTest | Level1) -{ - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - - req->SetIsAgentNotification(true); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_224000 - * @tc.name : Publish_1000 - * @tc.desc : Test Publish function req is false. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_224000, Function | SmallTest | Level1) -{ - std::string label = "publish's label"; - ASSERT_EQ(advancedNotificationService_->Publish(label, nullptr), ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AnsBranchTest_225000 - * @tc.name : CancelAsBundle_1000 - * @tc.desc : Test CancelAsBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_225000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - int32_t notificationId = 1; - std::string representativeBundle = "RepresentativeBundle"; - int32_t userId = 1; - ASSERT_EQ(advancedNotificationService_->CancelAsBundle( - notificationId, representativeBundle, userId), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_226000 - * @tc.name : CancelAsBundle_2000 - * @tc.desc : Test CancelAsBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_226000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - int32_t notificationId = 1; - std::string representativeBundle = "RepresentativeBundle"; - int32_t userId = 1; - ASSERT_EQ(advancedNotificationService_->CancelAsBundle( - notificationId, representativeBundle, userId), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_227000 - * @tc.name : AddSlots_2000 - * @tc.desc : Test AddSlots function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_227000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - slots.push_back(slot1); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_228000 - * @tc.name : Delete_1000 - * @tc.desc : Test Delete function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_228000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - const std::string key = "key"; - ASSERT_EQ(advancedNotificationService_->Delete( - key, NotificationConstant::CANCEL_REASON_DELETE), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_229000 - * @tc.name : DeleteByBundle_1000 - * @tc.desc : Test DeleteByBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_229000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->DeleteByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_230000 - * @tc.name : DeleteByBundle_2000 - * @tc.desc : Test DeleteByBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_230000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - ASSERT_EQ(advancedNotificationService_->DeleteByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_231000 - * @tc.name : DeleteAll_1000 - * @tc.desc : Test DeleteAll function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_231000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_232000 - * @tc.name : GetSlotsByBundle_1000 - * @tc.desc : Test GetSlotsByBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_232000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - std::vector> slots; - ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_233000 - * @tc.name : GetSlotsByBundle_2000 - * @tc.desc : Test GetSlotsByBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_233000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::vector> slots; - ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_234000 - * @tc.name : UpdateSlots_1000 - * @tc.desc : Test UpdateSlots function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_234000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ(advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_235000 - * @tc.name : UpdateSlots_1000 - * @tc.desc : Test UpdateSlots function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_235000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ(advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_236000 - * @tc.name : SetShowBadgeEnabledForBundle_1000 - * @tc.desc : Test SetShowBadgeEnabledForBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_236000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_237000 - * @tc.name : GetShowBadgeEnabledForBundle_1000 - * @tc.desc : Test GetShowBadgeEnabledForBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_237000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - bool allow = false; - ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_238000 - * @tc.name : GetShowBadgeEnabledForBundle_2000 - * @tc.desc : Test GetShowBadgeEnabledForBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_238000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool allow = false; - ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_239000 - * @tc.name : Subscribe_1000 - * @tc.desc : Test Subscribe function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_239000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - ASSERT_EQ(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_240000 - * @tc.name : Subscribe_1000 - * @tc.desc : Test Subscribe function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_240000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - ASSERT_EQ(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_241000 - * @tc.name : Unsubscribe_1000 - * @tc.desc : Test Unsubscribe function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_241000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - ASSERT_EQ(advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), info), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_242000 - * @tc.name : GetAllActiveNotifications_1000 - * @tc.desc : Test GetAllActiveNotifications function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_242000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::vector> allNotifications; - ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(allNotifications), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_243000 - * @tc.name : GetSpecialActiveNotifications_1000 - * @tc.desc : Test GetSpecialActiveNotifications function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_243000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - std::vector keys; - std::vector> specialActiveNotifications; - ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications( - keys, specialActiveNotifications), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_244000 - * @tc.name : GetSpecialActiveNotifications_2000 - * @tc.desc : Test GetSpecialActiveNotifications function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_244000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::vector keys; - std::vector> specialActiveNotifications; - ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications( - keys, specialActiveNotifications), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_245000 - * @tc.name : SetNotificationsEnabledForAllBundles_2000 - * @tc.desc : Test SetNotificationsEnabledForAllBundles function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_245000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles( - std::string(), true), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_246000 - * @tc.name : SetNotificationsEnabledForAllBundles_1000 - * @tc.desc : Test SetNotificationsEnabledForAllBundles function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_246000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles( - std::string(), true), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_247000 - * @tc.name : SetNotificationsEnabledForSpecialBundle_1000 - * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_247000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( - std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), false), - ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_248000 - * @tc.name : IsAllowedNotify_1000 - * @tc.desc : Test IsAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_248000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - bool allowed = false; - ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(allowed), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_249000 - * @tc.name : IsAllowedNotify_2000 - * @tc.desc : Test IsAllowedNotify function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_249000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool allowed = false; - ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(allowed), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_250000 - * @tc.name : GetAppTargetBundle_1000 - * @tc.desc : Test GetAppTargetBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_250000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - sptr targetBundle(nullptr); - bundleOption->SetBundleName("test"); - ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_251000 - * @tc.name : IsSpecialBundleAllowedNotify_1000 - * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_251000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - bool allowed = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_252000 - * @tc.name : IsSpecialBundleAllowedNotify_2000 - * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_252000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool allowed = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_254000 - * @tc.name : IsSpecialBundleAllowedNotify_4000 - * @tc.desc : Test IsSpecialBundleAllowedNotify function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_254000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(true); - - MockIsNonBundleName(true); - bool allowed = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialBundleAllowedNotify( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), ERR_ANS_INVALID_BUNDLE); -} - -/** - * @tc.number : AnsBranchTest_255000 - * @tc.name : RemoveNotification_1000 - * @tc.desc : Test RemoveNotification function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_255000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - int32_t notificationId = 1; - std::string label = "testRemove"; - auto result = advancedNotificationService_->RemoveNotification( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), - notificationId, label, NotificationConstant::CANCEL_REASON_DELETE); - ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_256000 - * @tc.name : RemoveAllNotifications_1000 - * @tc.desc : Test RemoveAllNotifications function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_256000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->RemoveAllNotifications(bundleOption), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_257000 - * @tc.name : GetSlotNumAsBundle_1000 - * @tc.desc : Test GetSlotNumAsBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_257000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - uint64_t num = 1; - ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_258000 - * @tc.name : GetSlotNumAsBundle_2000 - * @tc.desc : Test GetSlotNumAsBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_258000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - uint64_t num = 1; - ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_259000 - * @tc.name : RemoveGroupByBundle_2000 - * @tc.desc : Test RemoveGroupByBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_259000, Function | SmallTest | Level1) -{ - MockVerifyNativeToken(false); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - std::string groupName = "group"; - ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_260000 - * @tc.name : SetDoNotDisturbDate_1000 - * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_260000, Function | SmallTest | Level1) -{ - MockVerifyNativeToken(false); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_261000 - * @tc.name : SetDoNotDisturbDate_2000 - * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_261000, Function | SmallTest | Level1) -{ - MockVerifyNativeToken(false); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_262000 - * @tc.name : DoesSupportDoNotDisturbMode_1000 - * @tc.desc : Test DoesSupportDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_262000, Function | SmallTest | Level1) -{ - MockIsSystemApp(false); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - - bool doesSupport = true; - ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_263000 - * @tc.name : DoesSupportDoNotDisturbMode_2000 - * @tc.desc : Test DoesSupportDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_263000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool doesSupport = true; - ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_264000 - * @tc.name : EnableDistributed_1000 - * @tc.desc : Test EnableDistributed function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_264000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - bool enabled = true; - sptr bundleOption = - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_284000 - * @tc.name : EnableDistributed_2000 - * @tc.desc : Test EnableDistributed function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_284000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool enabled = true; - sptr bundleOption = - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle( - bundleOption, enabled), ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle( - bundleOption, enabled), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_265000 - * @tc.name : GetDeviceRemindType_1000 - * @tc.desc : Test GetDeviceRemindType function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_265000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; - ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_266000 - * @tc.name : GetDeviceRemindType_2000 - * @tc.desc : Test GetDeviceRemindType function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_266000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; - ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_267000 - * @tc.name : IsSpecialUserAllowedNotify_1000 - * @tc.desc : Test IsSpecialUserAllowedNotify function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_267000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - int32_t userId = 3; - bool allowed = true; - bool enable = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify( - userId, allowed), (int)ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser( - userId, enable), (int)ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_267100 - * @tc.name : IsSpecialUserAllowedNotify_1000 - * @tc.desc : Test IsSpecialUserAllowedNotify function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_267100, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - int32_t userId = 3; - bool allowed = true; - bool enable = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify( - userId, allowed), (int)ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser( - userId, enable), (int)ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_268000 - * @tc.name : SetDoNotDisturbDate_1000 - * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_268000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - int32_t userId = 3; - sptr date = nullptr; - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_269000 - * @tc.name : SetDoNotDisturbDate_2000 - * @tc.desc : Test SetDoNotDisturbDate function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_269000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - int32_t userId = 3; - sptr date = nullptr; - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_270000 - * @tc.name : SetEnabledForBundleSlot_1000 - * @tc.desc : Test SetEnabledForBundleSlot function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_270000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - bool enabled = false; - bool isForceControl = false; - auto result = advancedNotificationService_->SetEnabledForBundleSlot( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), - NotificationConstant::SlotType::SOCIAL_COMMUNICATION, enabled, false); - - ASSERT_EQ(result, ERR_ANS_PERMISSION_DENIED); - auto result1 = advancedNotificationService_->GetEnabledForBundleSlot( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), - NotificationConstant::SlotType::SOCIAL_COMMUNICATION, enabled); - ASSERT_EQ(result1, ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_271000 - * @tc.name : SetEnabledForBundleSlot_1000 - * @tc.desc : Test SetEnabledForBundleSlot function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_271000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockVerifyShellToken(false); - - std::string cmd = "CMD"; - std::string bundle = "Bundle"; - int32_t userId = 4; - std::vector dumpInfo; - ASSERT_EQ(advancedNotificationService_->ShellDump( - cmd, bundle, userId, 0, dumpInfo), (int)ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_272000 - * @tc.name : SetSyncNotificationEnabledWithoutApp_1000 - * @tc.desc : Test SetSyncNotificationEnabledWithoutApp function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_272000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - - int32_t userId = 3; - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp( - userId, enabled), ERR_ANS_NON_SYSTEM_APP); - ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp( - userId, enabled), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_273000 - * @tc.name : SetSyncNotificationEnabledWithoutApp_2000 - * @tc.desc : Test SetSyncNotificationEnabledWithoutApp function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_273000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - int32_t userId = 3; - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp( - userId, enabled), ERR_ANS_PERMISSION_DENIED); - ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp( - userId, enabled), ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_274000 - * @tc.name : EnableDistributedByBundle_3000 - * @tc.desc : Test EnableDistributedByBundle function return ERR_ANS_NON_SYSTEM_APP. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_274000, Function | SmallTest | Level1) -{ - MockGetDistributedEnableInApplicationInfo(false, 2); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - bool enabled = true; - sptr bundleOption = - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle( - bundleOption, enabled), ERR_ANS_NON_SYSTEM_APP); -} - -/** - * @tc.number : AnsBranchTest_275000 - * @tc.name : EnableDistributedSelf_2000 - * @tc.desc : Test EnableDistributedSelf function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_275000, Function | SmallTest | Level1) -{ - MockDistributedNotificationEnabled(false); - MockIsNonBundleName(false); - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), (int)ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.number : AnsBranchTest_276000 - * @tc.name : IsDistributedEnableByBundle_3000 - * @tc.desc : Test IsDistributedEnableByBundle function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_276000, Function | SmallTest | Level1) -{ - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - MockVerifyNativeToken(true); - MockGetDistributedEnableInApplicationInfo(true, 2); - sptr bundleOption = new NotificationBundleOption( - TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - bool enabled = false; - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); -} - -/** - * @tc.number : AnsBranchTest_277000 - * @tc.name : DoDistributedPublish_3000 - * @tc.desc : Test DoDistributedPublish function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_277000, Function | SmallTest | Level1) -{ - MockGetDistributedEnableInApplicationInfo(false, 2); - MockGetOsAccountLocalIdFromUid(false, 1); - MockDistributedNotificationEnabled(false); - sptr bundleOption = new NotificationBundleOption( - TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - std::shared_ptr record = nullptr; - ASSERT_EQ(advancedNotificationService_->DoDistributedPublish(bundleOption, record), ERR_OK); -} - -/** - * @tc.number : AnsBranchTest_278000 - * @tc.name : GetDistributedEnableInApplicationInfo_3000 - * @tc.desc : Test GetDistributedEnableInApplicationInfo function return ERR_ANS_PERMISSION_DENIED. - * @tc.require : #I6P8UI - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_278000, Function | SmallTest | Level1) -{ - MockGetOsAccountLocalIdFromUid(false, 3); - sptr bundleOption = new NotificationBundleOption( - TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - bool enabled = false;; - ASSERT_EQ(advancedNotificationService_->GetDistributedEnableInApplicationInfo( - bundleOption, enabled), ERR_ANS_INVALID_PARAM); -} - -void AnsBranchTest::InitNotificationRecord(std::shared_ptr &record, - const NotificationLiveViewContent::LiveViewStatus &status) -{ - NotificationRequest notificationRequest; - notificationRequest.SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - auto liveContent = std::make_shared(); - liveContent->SetLiveViewStatus(status); - auto content = std::make_shared(liveContent); - notificationRequest.SetContent(content); - - record->request = sptr::MakeSptr(notificationRequest); - record->notification = new (std::nothrow) Notification(record->request); -} - -/** - * @tc.number : AnsBranchTest_279000 - * @tc.name : UpdateNotificationTimerInfo_0001 - * @tc.desc : Check set update and finish timer when create notification request - * @tc.require : issue - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_279000, Function | SmallTest | Level1) -{ - using Status = NotificationLiveViewContent::LiveViewStatus; - auto record = std::make_shared(); - InitNotificationRecord(record, Status::LIVE_VIEW_CREATE); - ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); - ASSERT_EQ(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); - auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); - ASSERT_EQ(result, ERR_OK); - EXPECT_NE(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); - EXPECT_NE(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); -} - -/** - * @tc.number : AnsBranchTest_279001 - * @tc.name : UpdateNotificationTimerInfo_0002 - * @tc.desc : Check set update and finish timer when update notification request - * @tc.require : issue - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_279001, Function | SmallTest | Level1) -{ - using Status = NotificationLiveViewContent::LiveViewStatus; - auto record = std::make_shared(); - InitNotificationRecord(record, Status::LIVE_VIEW_INCREMENTAL_UPDATE); - record->notification->SetUpdateTimer(2); - record->notification->SetFinishTimer(3); - auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); - ASSERT_EQ(result, ERR_OK); - /* finish timer not change, but update timer changed */ - EXPECT_NE(record->notification->GetUpdateTimer(), 2); - ASSERT_EQ(record->notification->GetFinishTimer(), 3); -} - -/** - * @tc.number : AnsBranchTest_279002 - * @tc.name : UpdateNotificationTimerInfo_0003 - * @tc.desc : Check cancel update and finish timer when end notification request - * @tc.require : issue - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_279002, Function | SmallTest | Level1) -{ - using Status = NotificationLiveViewContent::LiveViewStatus; - auto record = std::make_shared(); - InitNotificationRecord(record, Status::LIVE_VIEW_END); - record->notification->SetUpdateTimer(2); - record->notification->SetFinishTimer(3); - - auto result = advancedNotificationService_->UpdateNotificationTimerInfo(record); - ASSERT_EQ(result, ERR_OK); - /* finish timer not change, but update timer changed */ - ASSERT_EQ(record->notification->GetUpdateTimer(), NotificationConstant::INVALID_TIMER_ID); - ASSERT_EQ(record->notification->GetFinishTimer(), NotificationConstant::INVALID_TIMER_ID); -} - -/** - * @tc.number : AnsBranchTest_285000 - * @tc.name : IsNeedSilentInDoNotDisturbMode_1000 - * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_NON_SYSTEM_APP. - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_285000, Function | SmallTest | Level1) -{ - MockIsSystemApp(false); - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - - std::string phoneNumber = "11111111111"; - int32_t callerType = 0; - ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( - phoneNumber, callerType), -1); -} - -/** - * @tc.number : AnsBranchTest_286000 - * @tc.name : IsNeedSilentInDoNotDisturbMode_2000 - * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function return ERR_ANS_PERMISSION_DENIED. - */ -HWTEST_F(AnsBranchTest, AnsBranchTest_286000, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(ATokenTypeEnum::TOKEN_HAP); - MockIsVerfyPermisson(false); - - std::string phoneNumber = "11111111111"; - int32_t callerType = 0; - ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode( - phoneNumber, callerType), ERR_ANS_PERMISSION_DENIED); -} -} // namespace Notification -} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_test.cpp b/services/reminder/test/unittest/advanced_notification_service_test.cpp deleted file mode 100644 index 849e0379a..000000000 --- a/services/reminder/test/unittest/advanced_notification_service_test.cpp +++ /dev/null @@ -1,3774 +0,0 @@ -/* - * Copyright (c) 2021-2024 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 "errors.h" -#include "notification_content.h" -#include "notification_record.h" -#include "notification_request.h" -#include -#include -#include -#include - -#include "gtest/gtest.h" -#include - -#define private public - -#include "advanced_notification_service.h" -#include "ans_const_define.h" -#include "ans_inner_errors.h" -#include "ans_log_wrapper.h" -#include "ans_notification.h" -#include "ans_ut_constant.h" -#include "common_event_manager.h" -#include "common_event_support.h" -#include "iremote_object.h" -#include "mock_ipc_skeleton.h" -#include "notification_preferences.h" -#include "notification_subscriber.h" -#include "notification_subscriber_manager.h" -#include "mock_push_callback_stub.h" -#include "system_event_observer.h" -#include "notification_constant.h" -#include "want_agent_info.h" -#include "want_agent_helper.h" -#include "want_params.h" -#include "bundle_manager_helper.h" - -extern void MockIsOsAccountExists(bool mockRet); - -using namespace testing::ext; -using namespace OHOS::Media; - -namespace OHOS { -namespace Notification { -extern void MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum mockRet); -extern void MockIsSystemApp(bool isSystemApp); -extern void MockIsNonBundleName(bool isNonBundleName); -extern void MockIsVerfyPermisson(bool isVerify); - -class AdvancedNotificationServiceTest : public testing::Test { -public: - static void SetUpTestCase(); - static void TearDownTestCase(); - void SetUp(); - void TearDown(); - -private: - void TestAddSlot(NotificationConstant::SlotType type); - void TestAddLiveViewSlot(bool isForceControl); - void MockSystemApp(); - -private: - static sptr advancedNotificationService_; -}; - -sptr AdvancedNotificationServiceTest::advancedNotificationService_ = nullptr; - -void AdvancedNotificationServiceTest::SetUpTestCase() -{ - MockIsOsAccountExists(true); -} - -void AdvancedNotificationServiceTest::TearDownTestCase() {} - -void AdvancedNotificationServiceTest::SetUp() -{ - GTEST_LOG_(INFO) << "SetUp start"; - - advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); - IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); - NotificationPreferences::GetInstance()->ClearNotificationInRestoreFactorySettings(); - IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - advancedNotificationService_->CancelAll(0); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); - GTEST_LOG_(INFO) << "SetUp end"; -} - -void AdvancedNotificationServiceTest::TearDown() -{ - IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - advancedNotificationService_ = nullptr; - GTEST_LOG_(INFO) << "TearDown"; -} - -inline void SleepForFC() -{ - // For ANS Flow Control - std::this_thread::sleep_for(std::chrono::seconds(1)); -} - -class TestAnsSubscriber : public NotificationSubscriber { -public: - void OnDoNotDisturbDateChange(const std::shared_ptr &date) override - {} - void OnConnected() override - {} - void OnDisconnected() override - {} - void OnDied() override - {} - void OnUpdate(const std::shared_ptr &sortingMap) override - {} - void OnBadgeChanged(const std::shared_ptr &badgeData) override - {} - void OnBadgeEnabledChanged( - const sptr &callbackData) override - {} - void OnEnabledNotificationChanged( - const std::shared_ptr &callbackData) override - {} - void OnCanceled(const std::shared_ptr &request, - const std::shared_ptr &sortingMap, int32_t deleteReason) override - {} - void OnConsumed(const std::shared_ptr &request, - const std::shared_ptr &sortingMap) override - {} - void OnBatchCanceled(const std::vector> - &requestList, const std::shared_ptr &sortingMap, int32_t deleteReason) override - {} -}; - -void AdvancedNotificationServiceTest::TestAddSlot(NotificationConstant::SlotType type) -{ - MockSystemApp(); - std::vector> slots; - sptr slot = new NotificationSlot(type); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); -} - -void AdvancedNotificationServiceTest::MockSystemApp() -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); -} - -void AdvancedNotificationServiceTest::TestAddLiveViewSlot(bool isForceControl) -{ - MockSystemApp(); - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::SlotType::LIVE_VIEW); - slot->SetForceControl(isForceControl); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), (int)ERR_OK); -} - - -/** - * @tc.number : AdvancedNotificationServiceTest_01600 - * @tc.name : ANS_GetSlot_0200 - * @tc.desc : Test GetSlots function when add two identical data - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, Function | SmallTest | Level1) -{ - MockSystemApp(); - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - slots.push_back(slot1); - std::vector> slotsResult; - advancedNotificationService_->AddSlots(slots); - advancedNotificationService_->GetSlots(slotsResult); - ASSERT_EQ((int)slots.size(), 2); - ASSERT_EQ((int)slotsResult.size(), 1); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_01800 - * @tc.name : ANS_SetNotificationBadgeNum_0100 - * @tc.desc : Test SetNotificationBadgeNum function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_01900 - * @tc.name : ANS_GetBundleImportance_0100 - * @tc.desc : Test GetBundleImportance function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - int importance; - ASSERT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_02200 - * @tc.name : ANS_UpdateSlots_0100 - * @tc.desc : Test UpdateSlots function when no slot - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_02300 - * @tc.name : ANS_UpdateSlots_0200 - * @tc.desc : Test UpdateSlots function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_02700 - * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_02800 - * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test GetShowBadgeEnabledForBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), - (int)ERR_OK); - bool allow = false; - ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), - (int)ERR_OK); - EXPECT_TRUE(allow); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_02900 - * @tc.name : ANS_GetActiveNotifications_0100 - * @tc.desc : Test GetActiveNotifications function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, Function | SmallTest | Level1) -{ - std::vector> notifications; - ASSERT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications, 0), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03000 - * @tc.name : ANS_SetTargetDeviceStatus_0100 - * @tc.desc : Test SetTargetDeviceStatus function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03000, Function | SmallTest | Level1) -{ - const std::string device = "current"; - const uint32_t status = 1; - ASSERT_EQ((int)advancedNotificationService_->SetTargetDeviceStatus(device, status), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03100 - * @tc.name : ANS_ClearAllNotificationGroupInfo_0100 - * @tc.desc : Test ClearAllNotificationGroupInfo function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03100, Function | SmallTest | Level1) -{ - const std::string localSwitch = "current"; - advancedNotificationService_->ClearAllNotificationGroupInfo(localSwitch); - EXPECT_TRUE(advancedNotificationService_ != nullptr); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03200 - * @tc.name : ANS_UpdateUnifiedGroupInfo_0100 - * @tc.desc : Test UpdateUnifiedGroupInfo function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03200, Function | SmallTest | Level1) -{ - const std::string key = "key"; - std::shared_ptr groupInfo; - advancedNotificationService_->UpdateUnifiedGroupInfo(key, groupInfo); - EXPECT_TRUE(advancedNotificationService_ != nullptr); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03300 - * @tc.name : ANS_RemoveSystemLiveViewNotificationsOfSa_0100 - * @tc.desc : Test RemoveSystemLiveViewNotificationsOfSa function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03300, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - sptr notification = new (std::nothrow) Notification(request); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - int32_t uid = 0; - ASSERT_EQ((int)advancedNotificationService_->RemoveSystemLiveViewNotificationsOfSa(uid), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03400 - * @tc.name : ANS_IsAllowedNotifyForBundle_0100 - * @tc.desc : Test IsAllowedNotifyForBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, Function | SmallTest | Level1) -{ - bool allowed = false; - sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - auto ret = advancedNotificationService_->IsAllowedNotifyForBundle(bundleOption, allowed); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03500 - * @tc.name : ANS_CancelAsBundleWithAgent_0100 - * @tc.desc : Test CancelAsBundleWithAgent function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) -{ - int32_t id = 0; - sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - auto ret = advancedNotificationService_->CancelAsBundleWithAgent(bundleOption, id); - ASSERT_EQ(ret, (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03600 - * @tc.name : ANS_AddDoNotDisturbProfiles_0100 - * @tc.desc : Test AddDoNotDisturbProfiles function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03600, Function | SmallTest | Level1) -{ - sptr date = nullptr; - std::vector> profiles = { date }; - auto ret = advancedNotificationService_->AddDoNotDisturbProfiles(profiles); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03700 - * @tc.name : ANS_Delete_0100 - * @tc.desc : Test Delete function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, Function | SmallTest | Level1) -{ - const std::string key = "key"; - ASSERT_EQ((int)advancedNotificationService_->Delete(key, NotificationConstant::CANCEL_REASON_DELETE), - (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03800 - * @tc.name : ANS_DeleteByBundle_0100 - * @tc.desc : Test DeleteByBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->DeleteByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), - ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03900 - * @tc.name : ANS_DeleteAll_0100 - * @tc.desc : Test DeleteAll function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04000 - * @tc.name : ANS_GetSlotsByBundle_0100 - * @tc.desc : Test GetSlotsByBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - std::vector> slots; - ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), - ERR_OK); - ASSERT_EQ(slots.size(), (size_t)1); -} - - -/** - * @tc.number : AdvancedNotificationServiceTest_04200 - * @tc.name : ANS_AddDoNotDisturbProfiles_0100 - * @tc.desc : Test AddDoNotDisturbProfiles function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04200, Function | SmallTest | Level1) -{ - sptr date = nullptr; - std::vector> profiles = { date }; - auto ret = advancedNotificationService_->RemoveDoNotDisturbProfiles(profiles); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04300 - * @tc.name : ANS_AddDoNotDisturbProfiles_0100 - * @tc.desc : Test AddDoNotDisturbProfiles function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04300, Function | SmallTest | Level1) -{ - sptr request(new NotificationRequest()); - std::string bundleName = "bundleName"; - advancedNotificationService_->SetAgentNotification(request, bundleName); - EXPECT_TRUE(advancedNotificationService_ != nullptr); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_04400 - * @tc.name : ANS_AddDoNotDisturbProfiles_0100 - * @tc.desc : Test AddDoNotDisturbProfiles function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04400, Function | SmallTest | Level1) -{ - std::string enable = "enable"; - auto ret = advancedNotificationService_->GetUnifiedGroupInfoFromDb(enable); - ASSERT_EQ(ret, -1); -} - - -/** - * @tc.number : AdvancedNotificationServiceTest_05100 - * @tc.name : ANS_AddSlots_0100 - * @tc.desc : Test AddSlots function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) -{ - MockSystemApp(); - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - sptr slot1 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - slots.push_back(slot1); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05200 - * @tc.name : ANS_RemoveSlotByType_0100 - * @tc.desc : Test RemoveSlotByType function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ(advancedNotificationService_->RemoveSlotByType(NotificationConstant::OTHER), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05300 - * @tc.name : ANS_RemoveSlotByType_0200 - * @tc.desc : Test RemoveSlotByType function when no type - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ((int)advancedNotificationService_->RemoveSlotByType(NotificationConstant::CUSTOM), 0); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05600 - * @tc.name : ANS_GetSlot_0100 - * @tc.desc : Test GetSlot function for data - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) -{ - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::OTHER); - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - advancedNotificationService_->AddSlots(slots); - ASSERT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), ERR_OK); - ASSERT_EQ(slot->GetName(), slot0->GetName()); - ASSERT_EQ(slot->GetId(), slot0->GetId()); - ASSERT_EQ(slot->GetLevel(), slot0->GetLevel()); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_05900 - * @tc.name : ANS_SetNotificationBadgeNum_0100 - * @tc.desc : Test SetNotificationBadgeNum function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05900, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ((int)advancedNotificationService_->SetNotificationBadgeNum(2), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_06000 - * @tc.name : ANS_GetBundleImportance_0100 - * @tc.desc : Test GetBundleImportance function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06000, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - int importance = 0; - ASSERT_EQ((int)advancedNotificationService_->GetBundleImportance(importance), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_06300 - * @tc.name : ANS_UpdateSlots_0100 - * @tc.desc : Test UpdateSlots function when no slot - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_06400 - * @tc.name : ANS_UpdateSlots_0200 - * @tc.desc : Test UpdateSlots function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06400, Function | SmallTest | Level1) -{ - std::vector> slots; - TestAddSlot(NotificationConstant::SlotType::OTHER); - sptr slot0 = new NotificationSlot(NotificationConstant::OTHER); - slots.push_back(slot0); - ASSERT_EQ((int)advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), slots), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_06800 - * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06800, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( - new NotificationBundleOption("", SYSTEM_APP_UID), true), - (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_06900 - * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, Function | SmallTest | Level1) -{ - bool allow = false; - ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_07000 - * @tc.name : ANS_GetActiveNotifications_0100 - * @tc.desc : Test GetActiveNotifications function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07000, Function | SmallTest | Level1) -{ - std::vector> notifications; - ASSERT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications, 0), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_07800 - * @tc.name : ANS_Delete_0100 - * @tc.desc : Test Delete function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07800, Function | SmallTest | Level1) -{ - const std::string key = "key"; - ASSERT_EQ((int)advancedNotificationService_->Delete(key, NotificationConstant::CANCEL_REASON_DELETE), - (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_07900 - * @tc.name : ANS_DeleteByBundle_0100 - * @tc.desc : Test DeleteByBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07900, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->DeleteByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID)), - ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_08000 - * @tc.name : ANS_DeleteAll_0100 - * @tc.desc : Test DeleteAll function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08000, Function | SmallTest | Level1) -{ - ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_08300 - * @tc.name : ANS_Subscribe_0100 - * @tc.desc : Test Subscribe function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08300, Function | SmallTest | Level1) -{ - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - EXPECT_NE((int)advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), (int)ERR_OK); - ASSERT_EQ((int)advancedNotificationService_->Subscribe(nullptr, info), (int)ERR_ANS_INVALID_PARAM); - EXPECT_NE((int)advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), nullptr), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_08600 - * @tc.name : ANS_GetShowBadgeEnabledForBundle_0200 - * @tc.desc : Test GetShowBadgeEnabledForBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08600, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ((int)advancedNotificationService_->SetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), - (int)ERR_OK); - bool allow = false; - ASSERT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), - (int)ERR_OK); - EXPECT_TRUE(allow); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_08700 - * @tc.name : ANS_GetSlotByType_0100 - * @tc.desc : Test GetSlotByType function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08700, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - ASSERT_EQ((int)advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), (int)ERR_OK); - ASSERT_EQ(slot->GetType(), NotificationConstant::SlotType::OTHER); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09000 - * @tc.name : ANS_GetAllActiveNotifications_0100 - * @tc.desc : Test GetAllActiveNotifications function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09000, Function | SmallTest | Level1) -{ - std::vector> notifications; - ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(notifications), ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09200 - * @tc.name : ANS_SetNotificationsEnabledForAllBundles_0200 - * @tc.desc : Test SetNotificationsEnabledForAllBundles function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09200, Function | SmallTest | Level1) -{ - ASSERT_EQ( - (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09300 - * @tc.name : ANS_SetNotificationsEnabledForSpecialBundle_0100 - * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::OTHER); - std::vector> notifications; - ASSERT_EQ((int)advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( - std::string(), new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09500 - * @tc.name : ANS_IsAllowedNotify_0100 - * @tc.desc : Test IsAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09500, Function | SmallTest | Level1) -{ - ASSERT_EQ( - (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); - bool allowed = false; - ASSERT_EQ((int)advancedNotificationService_->IsAllowedNotify(allowed), (int)ERR_OK); - EXPECT_TRUE(allowed); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09600 - * @tc.name : ANS_IsAllowedNotifySelf_0100 - * @tc.desc : Test IsAllowedNotifySelf function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, Function | SmallTest | Level1) -{ - MockSystemApp(); - ASSERT_EQ( - (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); - bool allowed = false; - ASSERT_EQ((int)advancedNotificationService_->IsAllowedNotifySelf(allowed), (int)ERR_OK); - EXPECT_FALSE(allowed); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09700 - * @tc.name : ANS_IsSpecialBundleAllowedNotify_0100 - * @tc.desc : Test IsSpecialBundleAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09700, Function | SmallTest | Level1) -{ - ASSERT_EQ( - (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); - TestAddSlot(NotificationConstant::SlotType::OTHER); - bool allowed = true; - ASSERT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09800 - * @tc.name : ANS_IsSpecialBundleAllowedNotify_0200 - * @tc.desc : Test IsSpecialBundleAllowedNotify function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, Function | SmallTest | Level1) -{ - ASSERT_EQ( - (int)advancedNotificationService_->SetNotificationsEnabledForAllBundles(std::string(), true), (int)ERR_OK); - std::vector> notifications; - bool allowed = true; - ASSERT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), - (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_09900 - * @tc.name : ANS_GetSlotsByBundle_0200 - * @tc.desc : Test GetSlotsByBundle function when no bundle - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, Function | SmallTest | Level1) -{ - std::vector> slots; - ASSERT_EQ((int)advancedNotificationService_->GetSlotsByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), - (int)ERR_OK); -} - - -/** - * @tc.number : AdvancedNotificationServiceTest_10500 - * @tc.name : ANS_SetDisturbMode_10500 - * @tc.desc : Test SetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10500, Function | SmallTest | Level1) -{ - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); - auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t endDate = endDuration.count(); - date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - timePoint = std::chrono::system_clock::now(); - beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - endDate = endDuration.count(); - date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - timePoint = std::chrono::system_clock::now(); - beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - endDate = endDuration.count(); - date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_10600 - * @tc.name : ANS_GetDisturbMode_10600 - * @tc.desc : Test GetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10600, Function | SmallTest | Level1) -{ - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - sptr result = nullptr; - ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); - ASSERT_NE(result, nullptr); - ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::NONE); - ASSERT_EQ(result->GetBeginDate(), 0); - ASSERT_EQ(result->GetEndDate(), 0); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_10700 - * @tc.name : ANS_GetDisturbMode_10700 - * @tc.desc : Test GetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10700, Function | SmallTest | Level1) -{ - std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); - timePoint = std::chrono::time_point_cast(timePoint); - timePoint += std::chrono::hours(1); - auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t endDate = endDuration.count(); - - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - sptr result = nullptr; - ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); - ASSERT_NE(result, nullptr); - ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::ONCE); - ASSERT_EQ(result->GetBeginDate(), beginDate); - ASSERT_EQ(result->GetEndDate(), endDate); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_10800 - * @tc.name : ANS_GetDisturbMode_10800 - * @tc.desc : Test GetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10800, Function | SmallTest | Level1) -{ - std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); - timePoint = std::chrono::time_point_cast(timePoint); - timePoint += std::chrono::hours(1); - auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t endDate = endDuration.count(); - - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - sptr result = nullptr; - ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); - ASSERT_NE(result, nullptr); - ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); - ASSERT_EQ(result->GetBeginDate(), beginDate); - ASSERT_EQ(result->GetEndDate(), endDate); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_10900 - * @tc.name : ANS_GetDisturbMode_10900 - * @tc.desc : Test GetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10900, Function | SmallTest | Level1) -{ - std::chrono::system_clock::time_point timePoint = std::chrono::system_clock::now(); - timePoint = std::chrono::time_point_cast(timePoint); - timePoint += std::chrono::hours(1); - auto beginDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t beginDate = beginDuration.count(); - timePoint += std::chrono::hours(1); - auto endDuration = std::chrono::duration_cast(timePoint.time_since_epoch()); - int64_t endDate = endDuration.count(); - - sptr date = - new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); - ASSERT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); - - sptr result = nullptr; - ASSERT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); - ASSERT_NE(result, nullptr); - ASSERT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::CLEARLY); - ASSERT_EQ(result->GetBeginDate(), beginDate); - ASSERT_EQ(result->GetEndDate(), endDate); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_12900 - * @tc.name : ANS_HasNotificationPolicyAccessPermission_0100 - * @tc.desc : Test HasNotificationPolicyAccessPermission function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_12900, Function | SmallTest | Level1) -{ - bool granted = true; - ASSERT_EQ(advancedNotificationService_->HasNotificationPolicyAccessPermission(granted), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13000 - * @tc.name : ANS_GetShowBadgeEnabled_0100 - * @tc.desc : Test GetShowBadgeEnabled function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13000, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - bool enabled = false; - ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabled(enabled), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13100 - * @tc.name : ANS_RequestEnableNotification_0100 - * @tc.desc : Test whether to pop dialog - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13100, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - std::string deviceId = "DeviceId"; - sptr callback = nullptr; - sptr callerToken = nullptr; - ASSERT_EQ(advancedNotificationService_->RequestEnableNotification(deviceId, callback, callerToken), - (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13500 - * @tc.name : ANS_GetValidReminders_0100 - * @tc.desc : Test GetValidReminders function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13500, Function | SmallTest | Level1) -{ - std::vector> reminders; - ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), (int)ERR_NO_INIT); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13600 - * @tc.name : ANS_ActiveNotificationDump_0100 - * @tc.desc : Test ActiveNotificationDump function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13600, Function | SmallTest | Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 2; - std::vector dumpInfo; - ASSERT_EQ(advancedNotificationService_->ActiveNotificationDump(bundle, userId, 0, dumpInfo), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13700 - * @tc.name : ANS_RecentNotificationDump_0100 - * @tc.desc : Test RecentNotificationDump function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13700, Function | SmallTest | Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 3; - std::vector dumpInfo; - ASSERT_EQ(advancedNotificationService_->RecentNotificationDump(bundle, userId, 0, dumpInfo), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13800 - * @tc.name : ANS_SetRecentNotificationCount_0100 - * @tc.desc : Test SetRecentNotificationCount function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13800, Function | SmallTest | Level1) -{ - std::string arg = "Arg"; - ASSERT_EQ(advancedNotificationService_->SetRecentNotificationCount(arg), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_13900 - * @tc.name : ANS_RemoveAllSlots_0100 - * @tc.desc : Test RemoveAllSlots function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13900, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - ASSERT_EQ(advancedNotificationService_->RemoveAllSlots(), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14200 - * @tc.name : ANS_DoesSupportDoNotDisturbMode_0100 - * @tc.desc : Test DoesSupportDoNotDisturbMode function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14200, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - bool doesSupport = true; - ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(doesSupport), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14300 - * @tc.name : ANS_IsDistributedEnabled_0100 - * @tc.desc : Test IsDistributedEnabled function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14300, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->IsDistributedEnabled(enabled), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14400 - * @tc.name : ANS_EnableDistributed_0100 - * @tc.desc : Test EnableDistributed function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14400, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->EnableDistributed(enabled), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14600 - * @tc.name : ANS_EnableDistributedSelf_0100 - * @tc.desc : Test EnableDistributedSelf function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14600, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14800 - * @tc.name : ANS_IsSpecialUserAllowedNotify_0100 - * @tc.desc : Test IsSpecialUserAllowedNotify function when the result is ERR_ANS_INVALID_PARAM - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14800, Function | SmallTest | Level1) -{ - int32_t userId = 3; - bool allowed = true; - ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify(userId, allowed), (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_14900 - * @tc.name : ANS_SetNotificationsEnabledByUser_0100 - * @tc.desc : Test SetNotificationsEnabledByUser function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_14900, Function | SmallTest | Level1) -{ - int32_t userId = 3; - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser(userId, enabled), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15000 - * @tc.name : ANS_GetDoNotDisturbDate_0100 - * @tc.desc : Test GetDoNotDisturbDate function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15000, Function | SmallTest | Level1) -{ - int32_t userId = 3; - sptr date = nullptr; - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15200 - * @tc.name : ANS_GetHasPoppedDialog_0100 - * @tc.desc : Test GetHasPoppedDialog function when the result is ERR_ANS_INVALID_PARAM - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15200, Function | SmallTest | Level1) -{ - sptr bundleOption = nullptr; - bool hasPopped = true; - ASSERT_EQ(advancedNotificationService_->GetHasPoppedDialog(bundleOption, hasPopped), (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15300 - * @tc.name : ANS_ShellDump_0100 - * @tc.desc : Test ShellDump function when the result is ERR_ANS_INVALID_PARAM - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15300, Function | SmallTest | Level1) -{ - std::string cmd = "CMD"; - std::string bundle = "Bundle"; - int32_t userId = 4; - std::vector dumpInfo; - ASSERT_EQ(advancedNotificationService_->ShellDump(cmd, bundle, userId, 0, dumpInfo), (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15400 - * @tc.name : ANS_Dump_0100 - * @tc.desc : Test Dump function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15400, Function | SmallTest | Level1) -{ - int fd = 1; - std::vector args; - ASSERT_EQ(advancedNotificationService_->Dump(fd, args), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15700 - * @tc.name : PrepareNotificationRequest_0100 - * @tc.desc : Test PrepareNotificationRequest function when notification is agent. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "PrepareNotificationRequest_0100 test start"; - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - - req->SetSlotType(NotificationConstant::SlotType::OTHER); - req->SetLabel("req's label"); - std::string label = "publish's label"; - std::shared_ptr normalContent = std::make_shared(); - EXPECT_NE(normalContent, nullptr); - - normalContent->SetText("normalContent's text"); - normalContent->SetTitle("normalContent's title"); - std::shared_ptr content = std::make_shared(normalContent); - EXPECT_NE(content, nullptr); - - req->SetContent(content); - req->SetIsAgentNotification(true); - ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_OK); - GTEST_LOG_(INFO) << "PrepareNotificationRequest_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_15800 - * @tc.name : GenerateBundleOption_0100 - * @tc.desc : Test GenerateBundleOption function when bundle name is null. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_15800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GenerateBundleOption_0100 test start"; - MockSystemApp(); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->GenerateBundleOption(), nullptr); - MockIsNonBundleName(false); - GTEST_LOG_(INFO) << "GenerateBundleOption_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16000 - * @tc.name : CancelPreparedNotification_1000 - * @tc.desc : Test CancelPreparedNotification function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test start"; - - int32_t notificationId = 0; - std::string label = "testLabel"; - sptr bundleOption = nullptr; - ASSERT_EQ(advancedNotificationService_->CancelPreparedNotification(notificationId, label, bundleOption, 8), - ERR_ANS_INVALID_BUNDLE); - - GTEST_LOG_(INFO) << "CancelPreparedNotification_1000 test end"; -} - - -/** - * @tc.number : AdvancedNotificationServiceTest_16200 - * @tc.name : ANS_CancelAsBundle_0200 - * @tc.desc : Test CancelAsBundle function - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16200, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0200 test start"; - - TestAddSlot(NotificationConstant::SlotType::OTHER); - int32_t notificationId = 1; - std::string representativeBundle = "RepresentativeBundle"; - int32_t userId = 1; - int result = ERR_ANS_NOTIFICATION_NOT_EXISTS; - ASSERT_EQ(advancedNotificationService_->CancelAsBundle(notificationId, representativeBundle, userId), result); - - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16300 - * @tc.name : ANS_CancelAsBundle_0300 - * @tc.desc : Test CancelAsBundle function when uid is less than 0. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0300 test start"; - - TestAddSlot(NotificationConstant::SlotType::OTHER); - int32_t notificationId = 1; - std::string representativeBundle = "RepresentativeBundle"; - int32_t userId = 0; - int result = ERR_ANS_INVALID_UID; - ASSERT_EQ(advancedNotificationService_->CancelAsBundle(notificationId, representativeBundle, userId), result); - - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0300 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16500 - * @tc.name : ANS_CancelAsBundle_0400 - * @tc.desc : Test CancelAsBundle function - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0400 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - int32_t notificationId = 1; - - int result = ERR_ANS_NOTIFICATION_NOT_EXISTS; - ASSERT_EQ(advancedNotificationService_->CancelAsBundle(bundleOption, notificationId), result); - - GTEST_LOG_(INFO) << "ANS_CancelAsBundle_0400 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16400 - * @tc.name : ANS_AddSlots_0100 - * @tc.desc : Test AddSlots function whith not system app - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16400, Function | SmallTest | Level1) -{ - MockSystemApp(); - GTEST_LOG_(INFO) << "ANS_AddSlots_0100 test start"; - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_OK); - - GTEST_LOG_(INFO) << "ANS_AddSlots_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16600 - * @tc.name : ANS_AddSlots_0300 - * @tc.desc : Test AddSlots function with bundle option is null - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_AddSlots_0300 test start"; - MockIsNonBundleName(true); - MockSystemApp(); - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - GTEST_LOG_(INFO) << "ANS_AddSlots_0300 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16700 - * @tc.name : ANS_AddSlots_0400 - * @tc.desc : Test AddSlots function with invalid bundle option - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_AddSlots_0400 test start"; - - std::vector> slots; - ASSERT_EQ(advancedNotificationService_->AddSlots(slots), ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "ANS_AddSlots_0400 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16800 - * @tc.name : ANS_GetSlots_0100 - * @tc.desc : Test GetSlots function with bundle option is null - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_GetSlots_0100 test start"; - MockIsNonBundleName(true); - MockSystemApp(); - std::vector> slots; - sptr slot = new NotificationSlot(NotificationConstant::SlotType::OTHER); - slots.push_back(slot); - ASSERT_EQ(advancedNotificationService_->GetSlots(slots), ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - GTEST_LOG_(INFO) << "ANS_GetSlots_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_16900 - * @tc.name : ANS_GetActiveNotifications_0100 - * @tc.desc : Test function with bundle option is null - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_16900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test start"; - - MockIsNonBundleName(true); - MockSystemApp(); - std::vector> notifications; - ASSERT_EQ(advancedNotificationService_->GetActiveNotifications(notifications, 0), ERR_ANS_INVALID_BUNDLE); - uint64_t num = 1; - ASSERT_EQ(advancedNotificationService_->GetActiveNotificationNums(num), ERR_ANS_INVALID_BUNDLE); - ASSERT_EQ(advancedNotificationService_->SetNotificationBadgeNum(num), ERR_ANS_INVALID_BUNDLE); - int32_t importance = 2; - ASSERT_EQ(advancedNotificationService_->GetBundleImportance(importance), ERR_ANS_INVALID_BUNDLE); - bool allow = true; - ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabled(allow), ERR_ANS_INVALID_BUNDLE); - - sptr slot = new NotificationSlot(NotificationConstant::OTHER); - ASSERT_EQ(advancedNotificationService_->GetSlotByType(NotificationConstant::OTHER, slot), ERR_ANS_INVALID_BUNDLE); - ASSERT_EQ(advancedNotificationService_->RemoveSlotByType(NotificationConstant::OTHER), ERR_ANS_INVALID_BUNDLE); - - std::string deviceId = "DeviceId"; - bool needPop = false; - ASSERT_EQ(advancedNotificationService_->IsAllowedNotifySelf(needPop), ERR_ANS_INVALID_BUNDLE); - sptr bundleOption; - ASSERT_EQ(advancedNotificationService_->IsAllowedNotifySelf(bundleOption, needPop), ERR_ANS_INVALID_BUNDLE); - - ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, bundleOption), ERR_ANS_INVALID_BUNDLE); - - int32_t reminderId = 1; - ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), ERR_ANS_INVALID_BUNDLE); - - ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), ERR_ANS_INVALID_BUNDLE); - - std::vector> reminders; - ASSERT_EQ(advancedNotificationService_->GetValidReminders(reminders), ERR_ANS_INVALID_BUNDLE); - - ASSERT_EQ(advancedNotificationService_->RemoveAllSlots(), ERR_ANS_INVALID_BUNDLE); - - ASSERT_EQ(advancedNotificationService_->AddSlotByType(NotificationConstant::SlotType::OTHER), - ERR_ANS_INVALID_BUNDLE); - - std::string groupName = "name"; - ASSERT_EQ(advancedNotificationService_->CancelGroup(groupName, 0), ERR_ANS_INVALID_BUNDLE); - - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->EnableDistributedSelf(enabled), ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17100 - * @tc.name : ANS_GetSetActiveNotifications_0100 - * @tc.desc : Test function with NON_SYSTEM_APP_UID - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test start"; - - std::string key = "key"; - int32_t removeReason = 0; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->Delete(key, removeReason), ERR_ANS_NOTIFICATION_NOT_EXISTS); - - ASSERT_EQ(advancedNotificationService_->DeleteByBundle(bundleOption), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->DeleteAll(), ERR_OK); - - bool enable = true; - bool isForceControl = false; - ASSERT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle(bundleOption, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->GetShowBadgeEnabledForBundle(bundleOption, enable), ERR_OK); - - std::vector> notifications; - ASSERT_EQ(advancedNotificationService_->GetAllActiveNotifications(notifications), ERR_OK); - - std::vector keys; - ASSERT_EQ(advancedNotificationService_->GetSpecialActiveNotifications(keys, notifications), - ERR_OK); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForAllBundles(key, enable), - ERR_OK); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledForSpecialBundle( - std::string(), bundleOption, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->IsAllowedNotify(enable), ERR_ANS_INVALID_PARAM); - - int32_t notificationId = 1; - ASSERT_EQ(advancedNotificationService_->RemoveNotification(bundleOption, notificationId, - key, removeReason), ERR_ANS_NOTIFICATION_NOT_EXISTS); - - ASSERT_EQ(advancedNotificationService_->RemoveAllNotifications(bundleOption), ERR_OK); - - uint64_t num = 1; - ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_OK); - - std::string groupName = "group"; - ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_OK); - - sptr date = nullptr; - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(date), ERR_ANS_INVALID_PARAM); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(date), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->DoesSupportDoNotDisturbMode(enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->EnableDistributed(enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); - - NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; - ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_OK); - - int32_t userId = 1; - ASSERT_EQ(advancedNotificationService_->IsSpecialUserAllowedNotify(userId, enable), ERR_ANS_INVALID_PARAM); - - ASSERT_EQ(advancedNotificationService_->SetNotificationsEnabledByUser(userId, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->DeleteAllByUser(userId), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->SetEnabledForBundleSlot(bundleOption, - NotificationConstant::SlotType::OTHER, enable, false), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->GetEnabledForBundleSlot(bundleOption, - NotificationConstant::SlotType::OTHER, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); - - ASSERT_EQ(advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(userId, enable), ERR_OK); - - std::string phoneNumber = "11111111111"; - int32_t callerType = 0; - ASSERT_EQ(advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType), -1); - - GTEST_LOG_(INFO) << "ANS_GetActiveNotifications_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17300 - * @tc.name : ANS_GetSlotsByBundle_0100 - * @tc.desc : Test GetSlotsByBundle function - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_GetSlotsByBundle_0100 test start"; - std::vector> slots; - ASSERT_EQ(advancedNotificationService_->GetSlotsByBundle( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), - ERR_OK); - - ASSERT_EQ(advancedNotificationService_->UpdateSlots( - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), - ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "ANS_GetSlotsByBundle_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17400 - * @tc.name : Subscribe_1000 - * @tc.desc : Test Subscribe function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17400, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "Subscribe_1000 test start"; - - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - EXPECT_NE(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_OK); - EXPECT_NE(advancedNotificationService_->Unsubscribe(subscriber->GetImpl(), info), ERR_OK); - - GTEST_LOG_(INFO) << "Subscribe_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17500 - * @tc.name : Unsubscribe_1000 - * @tc.desc : Test Subscribe function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "Unsubscribe_1000 test start"; - - auto subscriber = new TestAnsSubscriber(); - sptr info = new NotificationSubscribeInfo(); - EXPECT_NE(advancedNotificationService_->Subscribe(subscriber->GetImpl(), info), ERR_OK); - ASSERT_EQ(advancedNotificationService_->Unsubscribe(nullptr, info), ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "Unsubscribe_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17600 - * @tc.name : GetAppTargetBundle_1000 - * @tc.desc : Test GetAppTargetBundle function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; - - sptr bundleOption = nullptr; - - ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, bundleOption), ERR_OK); - - GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17700 - * @tc.name : GetAppTargetBundle_2000 - * @tc.desc : Test GetAppTargetBundle function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test start"; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); - sptr targetBundle = nullptr; - bundleOption->SetBundleName("test"); - ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_OK); - - GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_17800 - * @tc.name : GetAppTargetBundle_3000 - * @tc.desc : Test GetAppTargetBundle function. - * @tc.require : #I60KYN - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAppTargetBundle_3000 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - sptr targetBundle = nullptr; - bundleOption->SetBundleName("test"); - ASSERT_EQ(advancedNotificationService_->GetAppTargetBundle(bundleOption, targetBundle), ERR_OK); - - GTEST_LOG_(INFO) << "GetAppTargetBundle_3000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18100 - * @tc.name : ActiveNotificationDump_1000 - * @tc.desc : Test ActiveNotificationDump function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ActiveNotificationDump_1000 test start"; - - std::string bundle = "Bundle"; - int32_t userId = -1; - std::vector dumpInfo; - - ASSERT_EQ(advancedNotificationService_->ActiveNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); - - GTEST_LOG_(INFO) << "ActiveNotificationDump_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18200 - * @tc.name : RecentNotificationDump_1000 - * @tc.desc : Test RecentNotificationDump function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18200, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RecentNotificationDump_1000 test start"; - - std::string bundle = "Bundle"; - int32_t userId = -1; - std::vector dumpInfo; - - ASSERT_EQ(advancedNotificationService_->RecentNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); - - GTEST_LOG_(INFO) << "RecentNotificationDump_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18300 - * @tc.name : DistributedNotificationDump_1000 - * @tc.desc : Test DistributedNotificationDump function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "DistributedNotificationDump_1000 test start"; - - std::string bundle = "Bundle"; - int32_t userId = -1; - std::vector dumpInfo; - - ASSERT_EQ(advancedNotificationService_->DistributedNotificationDump(bundle, userId, userId, dumpInfo), ERR_OK); - - GTEST_LOG_(INFO) << "DistributedNotificationDump_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18400 - * @tc.name : SetRecentNotificationCount_1000 - * @tc.desc : Test SetRecentNotificationCount function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18400, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "SetRecentNotificationCount_1000 test start"; - - std::string arg = "1100"; - ASSERT_EQ(advancedNotificationService_->SetRecentNotificationCount(arg), ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "SetRecentNotificationCount_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18500 - * @tc.name : OnBundleRemoved_1000 - * @tc.desc : Test OnBundleRemoved function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnBundleRemoved_1000 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnBundleRemoved(bundleOption); - - GTEST_LOG_(INFO) << "OnBundleRemoved_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18600 - * @tc.name : OnScreenOn_1000 - * @tc.desc : Test OnScreenOn function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnScreenOn_1000 test start"; - - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnScreenOn(); - advancedNotificationService_->OnScreenOff(); - - GTEST_LOG_(INFO) << "OnScreenOn_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18700 - * @tc.name : AddSlotByType_1000 - * @tc.desc : Test AddSlotByType function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AddSlotByType_1000 test start"; - MockSystemApp(); - ASSERT_EQ(advancedNotificationService_->AddSlotByType(NotificationConstant::SlotType::SERVICE_REMINDER), - ERR_OK); - - GTEST_LOG_(INFO) << "AddSlotByType_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18800 - * @tc.name : GetSlotNumAsBundle_1000 - * @tc.desc : Test GetSlotNumAsBundle function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetSlotNumAsBundle_1000 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - uint64_t num = 1; - ASSERT_EQ(advancedNotificationService_->GetSlotNumAsBundle(bundleOption, num), ERR_OK); - - GTEST_LOG_(INFO) << "GetSlotNumAsBundle_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_18900 - * @tc.name : CancelGroup_1000 - * @tc.desc : Test CancelGroup function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CancelGroup_1000 test start"; - - std::string groupName = ""; - ASSERT_EQ(advancedNotificationService_->CancelGroup(groupName, 0), ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "CancelGroup_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19000 - * @tc.name : RemoveGroupByBundle_1000 - * @tc.desc : Test RemoveGroupByBundle function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RemoveGroupByBundle_1000 test start"; - - std::string groupName = "group"; - sptr bundleOption = nullptr; - ASSERT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), ERR_ANS_INVALID_PARAM); - - GTEST_LOG_(INFO) << "RemoveGroupByBundle_1000 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19100 - * @tc.name : ANS_IsDistributedEnabled_0100 - * @tc.desc : Test IsDistributedEnabled function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "ANS_IsDistributedEnabled_0100 test start"; - - bool enabled = false; - ASSERT_EQ(advancedNotificationService_->IsDistributedEnabled(enabled), ERR_OK); - - GTEST_LOG_(INFO) << "ANS_IsDistributedEnabled_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19200 - * @tc.name : EnableDistributedByBundle_0100 - * @tc.desc : Test EnableDistributedByBundle function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19200, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "EnableDistributedByBundle_0100 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - bool enabled = false; - ASSERT_EQ(advancedNotificationService_->EnableDistributedByBundle(bundleOption, enabled), ERR_OK); - - GTEST_LOG_(INFO) << "EnableDistributedByBundle_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19300 - * @tc.name : IsDistributedEnableByBundle_0100 - * @tc.desc : Test IsDistributedEnableByBundle function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0100 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - bool enabled = true; - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); - - GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19400 - * @tc.name : IsDistributedEnableByBundle_0200 - * @tc.desc : Test IsDistributedEnableByBundle function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19400, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0200 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - bool enabled = false; - ASSERT_EQ(advancedNotificationService_->IsDistributedEnableByBundle(bundleOption, enabled), ERR_OK); - - GTEST_LOG_(INFO) << "IsDistributedEnableByBundle_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19500 - * @tc.name : GetDeviceRemindType_0100 - * @tc.desc : Test GetDeviceRemindType function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetDeviceRemindType_0100 test start"; - - NotificationConstant::RemindType remindType = NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND; - ASSERT_EQ(advancedNotificationService_->GetDeviceRemindType(remindType), ERR_OK); - - GTEST_LOG_(INFO) << "GetDeviceRemindType_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19600 - * @tc.name : GetLocalNotificationKeys_0100 - * @tc.desc : Test GetLocalNotificationKeys function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetLocalNotificationKeys_0100 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->GetLocalNotificationKeys(bundleOption); - - GTEST_LOG_(INFO) << "GetLocalNotificationKeys_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19700 - * @tc.name : CheckDistributedNotificationType_0100 - * @tc.desc : Test CheckDistributedNotificationType function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test start"; - - sptr req = new NotificationRequest(); - ASSERT_EQ(advancedNotificationService_->CheckDistributedNotificationType(req), true); - - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19800 - * @tc.name : CheckDistributedNotificationType_0200 - * @tc.desc : Test CheckDistributedNotificationType function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0200 test start"; - - sptr req = new NotificationRequest(); - std::vector devices; - devices.push_back("a"); - devices.push_back("b"); - devices.push_back("c"); - req->GetNotificationDistributedOptions().SetDevicesSupportDisplay(devices); - ASSERT_EQ(advancedNotificationService_->CheckDistributedNotificationType(req), true); - - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_19900 - * @tc.name : OnDistributedPublish_0100 - * @tc.desc : Test OnDistributedPublish function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_19900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test start"; - - std::string deviceId = "DeviceId"; - std::string bundleName = "BundleName"; - sptr request = new NotificationRequest(); - - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnDistributedPublish(deviceId, bundleName, request); - - GTEST_LOG_(INFO) << "CheckDistributedNotificationType_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20000 - * @tc.name : OnDistributedUpdate_0100 - * @tc.desc : Test OnDistributedUpdate function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnDistributedUpdate_0100 test start"; - - std::string deviceId = "DeviceId"; - std::string bundleName = "BundleName"; - sptr request = new NotificationRequest(); - - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnDistributedUpdate(deviceId, bundleName, request); - - GTEST_LOG_(INFO) << "OnDistributedUpdate_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20100 - * @tc.name : OnDistributedDelete_0100 - * @tc.desc : Test OnDistributedDelete function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnDistributedDelete_0100 test start"; - - std::string deviceId = "DeviceId"; - std::string bundleName = "BundleName"; - std::string label = "testLabel"; - int32_t id = 1; - - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnDistributedDelete(deviceId, bundleName, label, id); - - GTEST_LOG_(INFO) << "OnDistributedDelete_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20200 - * @tc.name : CheckPublishWithoutApp_0100 - * @tc.desc : Test CheckPublishWithoutApp function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20200, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0100 test start"; - - int32_t userId = 1; - sptr request = new NotificationRequest(); - ASSERT_EQ(advancedNotificationService_->CheckPublishWithoutApp(userId, request), false); - - GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20300 - * @tc.name : CheckPublishWithoutApp_0200 - * @tc.desc : Test CheckPublishWithoutApp function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0200 test start"; - - int32_t userId = SYSTEM_APP_UID; - sptr request = new NotificationRequest(); - ASSERT_EQ(advancedNotificationService_->CheckPublishWithoutApp(userId, request), false); - - GTEST_LOG_(INFO) << "CheckPublishWithoutApp_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20400 - * @tc.name : TriggerRemoveWantAgent_0100 - * @tc.desc : Test TriggerRemoveWantAgent function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20400, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "TriggerRemoveWantAgent_0100 test start"; - - sptr request = new NotificationRequest(); - AbilityRuntime::WantAgent::WantAgentInfo paramsInfo; - std::shared_ptr wantAgent = - AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); - - request->SetRemovalWantAgent(wantAgent); - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->TriggerRemoveWantAgent(request); - - GTEST_LOG_(INFO) << "TriggerRemoveWantAgent_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20500 - * @tc.name : DeleteAllByUser_0100 - * @tc.desc : Test DeleteAllByUser function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "DeleteAllByUser_0100 test start"; - - int32_t userId = -2; - ASSERT_EQ(advancedNotificationService_->DeleteAllByUser(userId), ERR_ANS_INVALID_PARAM); - - sptr date = nullptr; - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); - ASSERT_EQ(advancedNotificationService_->GetDoNotDisturbDate(userId, date), ERR_ANS_INVALID_PARAM); - ASSERT_EQ(advancedNotificationService_->SetDoNotDisturbDateByUser(userId, date), ERR_ANS_INVALID_PARAM); - GTEST_LOG_(INFO) << "DeleteAllByUser_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20600 - * @tc.name : OnResourceRemove_0100 - * @tc.desc : Test OnResourceRemove function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnResourceRemove_0100 test start"; - - int32_t userId = -2; - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnResourceRemove(userId); - - GTEST_LOG_(INFO) << "OnResourceRemove_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20700 - * @tc.name : OnBundleDataCleared_0100 - * @tc.desc : Test OnBundleDataCleared function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "OnBundleDataCleared_0100 test start"; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->OnBundleDataCleared(bundleOption); - - GTEST_LOG_(INFO) << "OnBundleDataCleared_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_20900 - * @tc.name : GetDumpInfo_0100 - * @tc.desc : Test GetDumpInfo function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_20900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetDumpInfo_0100 test start"; - - std::vector args; - args.push_back(Str8ToStr16("args")); - std::string result = "result"; - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->GetDumpInfo(args, result); - - GTEST_LOG_(INFO) << "GetDumpInfo_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21000 - * @tc.name : GetDumpInfo_0200 - * @tc.desc : Test GetDumpInfo function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetDumpInfo_0200 test start"; - - std::vector args; - args.push_back(Str8ToStr16("-h")); - std::string result = "result"; - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->GetDumpInfo(args, result); - - GTEST_LOG_(INFO) << "GetDumpInfo_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21100 - * @tc.name : SendFlowControlOccurHiSysEvent_0100 - * @tc.desc : Test SendFlowControlOccurHiSysEvent function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0100 test start"; - - std::shared_ptr record = nullptr; - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->SendFlowControlOccurHiSysEvent(record); - - GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21200 - * @tc.name : SendFlowControlOccurHiSysEvent_0200 - * @tc.desc : Test SendFlowControlOccurHiSysEvent function - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21200, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0200 test start"; - - std::shared_ptr record = std::make_shared(); - record->request = new NotificationRequest(); - record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_NE(nullptr, advancedNotificationService_); - advancedNotificationService_->SendFlowControlOccurHiSysEvent(record); - - GTEST_LOG_(INFO) << "SendFlowControlOccurHiSysEvent_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21300 - * @tc.name : PrepareNotificationRequest_0200 - * @tc.desc : Test PrepareNotificationRequest function when uid < 0. - * @tc.require : issueI62D8C - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21300, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "PrepareNotificationRequest_0200 test start"; - sptr req = new NotificationRequest(); - int32_t myNotificationId = 10; - bool isAgentTrue = true; - NotificationRequest notificationRequest(myNotificationId); - notificationRequest.SetIsAgentNotification(isAgentTrue); - - std::shared_ptr bundleManager = nullptr; - - ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(req), ERR_OK); - GTEST_LOG_(INFO) << "PrepareNotificationRequest_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21400 - * @tc.name : PrepareNotificationInfo_2000 - * @tc.desc : Test PrepareNotificationInfo function. - * @tc.require : issueI62D8C - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21400, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "PrepareNotificationInfo_2000 test start"; - - sptr req = new (std::nothrow) NotificationRequest(1); - EXPECT_NE(req, nullptr); - sptr bundleOption = nullptr; - - ASSERT_EQ(advancedNotificationService_->PrepareNotificationInfo(req, bundleOption), ERR_OK); - - GTEST_LOG_(INFO) << "PrepareNotificationInfo_2000 test end"; -} - - - -/** - * @tc.number : AdvancedNotificationServiceTest_21600 - * @tc.name : RegisterPushCallback_0100 - * @tc.desc : Test RegisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21600, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RegisterPushCallback_0100 test start"; - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), ERR_OK); - - advancedNotificationService_->UnregisterPushCallback(); - - GTEST_LOG_(INFO) << "RegisterPushCallback_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21700 - * @tc.name : RegisterPushCallback_0200 - * @tc.desc : Test RegisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21700, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test start"; - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), - (int)ERR_OK); - advancedNotificationService_->UnregisterPushCallback(); - - - GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21800 - * @tc.name : RegisterPushCallback_0200 - * @tc.desc : Test RegisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21800, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RegisterPushCallback_0300 test start"; - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr pushCallBack = iface_cast(pushCallback); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - - advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); - - ASSERT_EQ(advancedNotificationService_->RegisterPushCallback(pushCallback, checkRequest), (int)ERR_OK); - - advancedNotificationService_->UnregisterPushCallback(); - - GTEST_LOG_(INFO) << "RegisterPushCallback_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_21900 - * @tc.name : UnregisterPushCallback_0100 - * @tc.desc : Test UnregisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_21900, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "UnregisterPushCallback_0100 test start"; - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr pushCallBack = iface_cast(pushCallback); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - - advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); - - ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), ERR_OK); - - GTEST_LOG_(INFO) << "UnregisterPushCallback_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_22000 - * @tc.name : UnregisterPushCallback_0200 - * @tc.desc : Test UnregisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22000, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "UnregisterPushCallback_0200 test start"; - ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), (int)ERR_ANS_NON_SYSTEM_APP); - - GTEST_LOG_(INFO) << "UnregisterPushCallback_0200 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_22100 - * @tc.name : UnregisterPushCallback_0300 - * @tc.desc : Test UnregisterPushCallback function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22100, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "UnregisterPushCallback_0300 test start"; - - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - ASSERT_EQ(advancedNotificationService_->UnregisterPushCallback(), (int)ERR_INVALID_OPERATION); - - GTEST_LOG_(INFO) << "UnregisterPushCallback_0300 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_22500 - * @tc.name : PushCheck_0100 - * @tc.desc : Test PushCheck function. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22500, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "PushCheck_0100 test start"; - - sptr req = new (std::nothrow) NotificationRequest(); - ASSERT_EQ(advancedNotificationService_->PushCheck(req), ERR_ANS_PUSH_CHECK_UNREGISTERED); - - GTEST_LOG_(INFO) << "PushCheck_0100 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_220000 - * @tc.name : TimeToString_1000 - * @tc.desc : Test TimeToString function. - * @tc.require : #I61RF2 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_220000, Function | SmallTest | Level1) -{ - int64_t time = 60; - int64_t ret = 20; - std::string result = advancedNotificationService_->TimeToString(time); - ASSERT_EQ(result.size(), ret); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_22600 - * @tc.name : ANS_IsNeedSilentInDoNotDisturbMode_0100 - * @tc.desc : Test IsNeedSilentInDoNotDisturbMode function when the result is ERR_OK - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_22600, Function | SmallTest | Level1) -{ - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); - std::string phoneNumber = "11111111111"; - int32_t callerType = 0; - auto ret = advancedNotificationService_->IsNeedSilentInDoNotDisturbMode(phoneNumber, callerType); - ASSERT_EQ(ret, -1); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00001 - * @tc.name : PrepareNotificationRequest - * @tc.desc : Test PrepareNotificationRequest function. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00001 test start"; - ASSERT_EQ(advancedNotificationService_->PrepareNotificationRequest(nullptr), ERR_ANS_INVALID_PARAM); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00001 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00002 - * @tc.name : IsNotificationExists - * @tc.desc : Test IsNotificationExists function. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00002 test start"; - std::string key = "aa"; - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - ASSERT_EQ(advancedNotificationService_->IsNotificationExists(key), false); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00002 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00003 - * @tc.name : UpdateInNotificationList - * @tc.desc : Test UpdateInNotificationList function and notificationList_ is not empty. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00003, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00003 test start"; - std::string key = "aa"; - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - advancedNotificationService_->UpdateInNotificationList(record); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00003 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00004 - * @tc.name : SetBadgeNumber - * @tc.desc : Test SetBadgeNumber function and handler_ is nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00004, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00004 test start"; - int32_t badgeNumber = 1; - ASSERT_EQ(advancedNotificationService_->SetBadgeNumber(badgeNumber, 0), ERR_OK); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00004 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00005 - * @tc.name : SetBadgeNumber - * @tc.desc : Test SetBadgeNumber function and handler_ is not nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00005, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00005 test start"; - int32_t badgeNumber = 1; - advancedNotificationService_->runner_ = OHOS::AppExecFwk::EventRunner::Create("NotificationSvrMain"); - advancedNotificationService_->handler_ = - std::make_shared(advancedNotificationService_->runner_); - ASSERT_EQ(advancedNotificationService_->SetBadgeNumber(badgeNumber, 0), ERR_OK); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00005 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00006 - * @tc.name : ResetPushCallbackProxy - * @tc.desc : Test ResetPushCallbackProxy function and pushCallBack_ is nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00006, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00006 test start"; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->ResetPushCallbackProxy(); - ASSERT_EQ(advancedNotificationService_->pushCallBacks_.empty(), true); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00006 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00007 - * @tc.name : ResetPushCallbackProxy - * @tc.desc : Test ResetPushCallbackProxy function and pushCallBack_ is not nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00007, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00007 test start"; - EXPECT_NE(advancedNotificationService_, nullptr); - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr pushCallBack = iface_cast(pushCallback); - sptr checkRequest = new (std::nothrow) NotificationCheckRequest(); - - advancedNotificationService_->pushCallBacks_.insert_or_assign(checkRequest->GetSlotType(), pushCallBack); - advancedNotificationService_->ResetPushCallbackProxy(); - ASSERT_TRUE(advancedNotificationService_->pushCallBacks_.empty()); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00007 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00008 - * @tc.name : SendEnableNotificationSlotHiSysEvent - * @tc.desc : Test SendEnableNotificationSlotHiSysEvent function and bundleOption is nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00008, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00008 test start"; - sptr bundleOption = nullptr; - NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CONTENT_INFORMATION; - bool enabled = false; - ErrCode errCode = ERR_OK; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00008 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00009 - * @tc.name : SendEnableNotificationSlotHiSysEvent - * @tc.desc : Test SendEnableNotificationSlotHiSysEvent function and errCode != ERR_OK. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00009, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00009 test start"; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - NotificationConstant::SlotType slotType = NotificationConstant::SlotType::CONTENT_INFORMATION; - bool enabled = false; - ErrCode errCode = ERR_ANS_TASK_ERR; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendEnableNotificationSlotHiSysEvent(bundleOption, slotType, enabled, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00009 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00010 - * @tc.name : SendRemoveHiSysEvent - * @tc.desc : Test SendRemoveHiSysEvent function and errCode is ERR_OK bundleOption is not nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00010, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00010 test start"; - int32_t notificationId = 1; - std::string label = "aa"; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ErrCode errCode = ERR_OK; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendRemoveHiSysEvent(notificationId, label, bundleOption, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00010 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00011 - * @tc.name : SendEnableNotificationHiSysEvent - * @tc.desc : Test SendEnableNotificationHiSysEvent function andbundleOption is nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00011, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00011 test start"; - sptr bundleOption = nullptr; - bool enabled = false; - ErrCode errCode = ERR_ANS_TASK_ERR; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendEnableNotificationHiSysEvent(bundleOption, enabled, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00011 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00012 - * @tc.name : SendCancelHiSysEvent - * @tc.desc : Test SendCancelHiSysEvent function and errCode is ERR_OK bundleOption is not nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00012, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00012 test start"; - int32_t notificationId = 1; - std::string label = "aa"; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ErrCode errCode = ERR_OK; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendCancelHiSysEvent(notificationId, label, bundleOption, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00012 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00013 - * @tc.name : SendPublishHiSysEvent - * @tc.desc : Test SendPublishHiSysEvent function and request is nullptr. - * @tc.require : #I6Z5I4 - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00013, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00013 test start"; - sptr request = nullptr; - ErrCode errCode = ERR_OK; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->SendPublishHiSysEvent(request, errCode); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00013 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00014 - * @tc.name : GetTargetRecordList - * @tc.desc : Test GetTargetRecordList function and get empty. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00014, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00014 test start"; - std::shared_ptr record = std::make_shared(); - record->request = new NotificationRequest(); - record->bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - const int32_t uid = 0; - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; - advancedNotificationService_->notificationList_.clear(); - std::vector> recordList; - ASSERT_EQ(advancedNotificationService_->GetTargetRecordList(uid, slotType, contentType, recordList), - ERR_ANS_NOTIFICATION_NOT_EXISTS); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00014 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00015 - * @tc.name : GetTargetRecordList - * @tc.desc : Test GetTargetRecordList function and get success. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00015, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00015 test start"; - std::string bundleName = "testBundle"; - const int32_t uid = 0; - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; - - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - request->SetSlotType(slotType); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - request->SetCreatorUid(uid); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - std::vector> recordList; - ASSERT_EQ(advancedNotificationService_->GetTargetRecordList(uid, slotType, contentType, recordList), - ERR_OK); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00015 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00016 - * @tc.name : RemoveNotificationFromRecordList - * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00016, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test start"; - std::string bundleName = "testBundle"; - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - auto contentType = NotificationContent::Type::LOCAL_LIVE_VIEW; - - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - request->SetSlotType(slotType); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - request->SetOwnerBundleName(bundleName); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - std::vector> recordList; - recordList.push_back(record); - ASSERT_EQ(advancedNotificationService_->RemoveNotificationFromRecordList(recordList), ERR_OK); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00017 - * @tc.name : RemoveSystemLiveViewNotifications - * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00017, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00016 test start"; - std::string bundleName = "testBundle"; - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - request->SetSlotType(slotType); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - request->SetOwnerBundleName(bundleName); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - int32_t uid = 0; - ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), ERR_OK); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00017 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00018 - * @tc.name : RemoveSystemLiveViewNotifications - * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00018, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00018 test start"; - std::string bundleName = "testBundle"; - int32_t uid = 0; - ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), - ERR_ANS_NOTIFICATION_NOT_EXISTS); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00018 test end"; -} - -/** - * @tc.number : AdvancedNotificationServiceTest_00019 - * @tc.name : RemoveSystemLiveViewNotifications - * @tc.desc : Test RemoveNotificationFromRecordList function and remove success. - * @tc.require : #I8B8PI - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00019, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00019 test start"; - std::string bundleName = "testBundle"; - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - sptr request = new (std::nothrow) NotificationRequest(); - EXPECT_NE(request, nullptr); - request->SetSlotType(slotType); - auto liveContent = std::make_shared(); - auto content = std::make_shared(liveContent); - request->SetContent(content); - request->SetOwnerBundleName(bundleName); - sptr notification = new (std::nothrow) Notification(request); - EXPECT_NE(notification, nullptr); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - advancedNotificationService_->notificationSvrQueue_ = nullptr; - int32_t uid = 0; - ASSERT_EQ(advancedNotificationService_->RemoveSystemLiveViewNotifications(bundleName, uid), ERR_ANS_INVALID_PARAM); - GTEST_LOG_(INFO) << "AdvancedNotificationServiceTest_00019 test end"; -} -/** - * @tc.number : IsLiveViewCanRecoverTest_0001 - * @tc.name : IsLiveViewCanRecover - * @tc.desc : Test IsLiveViewCanRecover and liveview is nullptr. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0001 test start"; - ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(nullptr), false); - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0001 test end"; -} - -/** - * @tc.number : IsLiveViewCanRecoverTest_0002 - * @tc.name : IsLiveViewCanRecover - * @tc.desc : Test IsLiveViewCanRecover and liveview status is invalid. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0002 test start"; - sptr request = new NotificationRequest(); - std::shared_ptr liveViewContent = std::make_shared(); - std::shared_ptr content = std::make_shared(liveViewContent); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); - request->SetContent(content); - - ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), false); - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0002 test end"; -} - -/** - * @tc.number : IsLiveViewCanRecoverTest_0003 - * @tc.name : IsLiveViewCanRecover - * @tc.desc : Test IsLiveViewCanRecover and liveview is expired. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0003, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0003 test start"; - sptr request = new NotificationRequest(); - std::shared_ptr liveViewContent = std::make_shared(); - std::shared_ptr content = std::make_shared(liveViewContent); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); - request->SetContent(content); - request->SetFinishDeadLine(0); - - ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), false); - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0003 test end"; -} - -/** - * @tc.number : IsLiveViewCanRecoverTest_0004 - * @tc.name : IsLiveViewCanRecover - * @tc.desc : Test IsLiveViewCanRecover and liveview status is create and not expired. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsLiveViewCanRecoverTest_0004, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0004 test start"; - sptr request = new NotificationRequest(); - std::shared_ptr liveViewContent = std::make_shared(); - std::shared_ptr content = std::make_shared(liveViewContent); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); - request->SetContent(content); - - auto now = std::chrono::system_clock::now(); - auto duration = std::chrono::duration_cast(now.time_since_epoch()); - request->SetFinishDeadLine(duration.count() + NotificationConstant::MAX_FINISH_TIME); - request->SetUpdateDeadLine(duration.count() + NotificationConstant::MAX_UPDATE_TIME); - - ASSERT_EQ(advancedNotificationService_->IsLiveViewCanRecover(request), true); - GTEST_LOG_(INFO) << "IsLiveViewCanRecoverTest_0004 test end"; -} - -/** - * @tc.number : FillNotificationRecordTest_0001 - * @tc.name : FillNotificationRecord - * @tc.desc : Test FillNotificationRecord and request is nullptr. - */ -HWTEST_F(AdvancedNotificationServiceTest, FillNotificationRecordTest_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "FillNotificationRecordTest_0001 test start"; - AdvancedNotificationService::NotificationRequestDb requestDbObj = { .request = nullptr, .bundleOption = nullptr}; - auto record = std::make_shared(); - - EXPECT_NE(advancedNotificationService_->FillNotificationRecord(requestDbObj, record), ERR_OK); - GTEST_LOG_(INFO) << "FillNotificationRecordTest_0001 test end"; -} - -/** - * @tc.number : FillNotificationRecordTest_0002 - * @tc.name : FillNotificationRecord - * @tc.desc : Test FillNotificationRecord and request/bundleOption is valid. - */ -HWTEST_F(AdvancedNotificationServiceTest, FillNotificationRecordTest_0002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "FillNotificationRecordTest_0002 test start"; - sptr request = new NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - std::string bundleName = "BundleName"; - int32_t uid = 10; - sptr bundleOption = new NotificationBundleOption(bundleName, uid); - AdvancedNotificationService::NotificationRequestDb requestDbObj = - { .request = request, .bundleOption = bundleOption }; - auto record = std::make_shared(); - - ASSERT_EQ(advancedNotificationService_->FillNotificationRecord(requestDbObj, record), ERR_OK); - GTEST_LOG_(INFO) << "FillNotificationRecordTest_0002 test end"; -} - -/** - * @tc.number : RecoverLiveViewFromDb_0002 - * @tc.name : RecoverLiveViewFromDb - * @tc.desc : Test RecoverLiveViewFromDb and liveView can't recover from db. - */ -HWTEST_F(AdvancedNotificationServiceTest, RecoverLiveViewFromDb_0002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "RecoverLiveViewFromDb_0002 test start"; - advancedNotificationService_->notificationList_.clear(); - sptr request = new NotificationRequest(1); - std::shared_ptr liveViewContent = std::make_shared(); - std::shared_ptr content = std::make_shared(liveViewContent); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); - request->SetContent(content); - request->SetCreatorUid(1); - request->SetCreatorUserId(2); - request->SetLabel("test_2"); - - std::string bundleName = "BundleName_02"; - int32_t uid = 11; - sptr bundleOption = new NotificationBundleOption(bundleName, uid); - AdvancedNotificationService::NotificationRequestDb requestDbObj = - { .request = request, .bundleOption = bundleOption }; - auto result = advancedNotificationService_->SetNotificationRequestToDb(requestDbObj); - ASSERT_EQ(result, ERR_OK); - - advancedNotificationService_->RecoverLiveViewFromDb(); - ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 0); - - result = advancedNotificationService_->DeleteNotificationRequestFromDb(request->GetKey(), 0); - ASSERT_EQ(result, ERR_OK); - - GTEST_LOG_(INFO) << "RecoverLiveViewFromDb_0002 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0001 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test live view notification need pushCheck. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0001 test start"; - sptr request = new NotificationRequest(); - std::shared_ptr liveViewContent = std::make_shared(); - auto status = NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE; - liveViewContent->SetLiveViewStatus(status); - std::shared_ptr content = std::make_shared(liveViewContent); - request->SetContent(content); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), true); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0001 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0002 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification except live view registered need push check. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0002 test start"; - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr pushCallBack = iface_cast(pushCallback); - - std::shared_ptr normalContent = std::make_shared(); - EXPECT_NE(normalContent, nullptr); - normalContent->SetText("normalContent's text"); - normalContent->SetTitle("normalContent's title"); - std::shared_ptr content = std::make_shared(normalContent); - - advancedNotificationService_->pushCallBacks_.clear(); - advancedNotificationService_->checkRequests_.clear(); - sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); - notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::CUSTOM); - notificationCheckRequest->SetContentType(NotificationContent::Type::BASIC_TEXT); - advancedNotificationService_->pushCallBacks_.insert_or_assign( - notificationCheckRequest->GetSlotType(), pushCallBack); - advancedNotificationService_->checkRequests_.insert_or_assign( - notificationCheckRequest->GetSlotType(), notificationCheckRequest); - - sptr request = new NotificationRequest(); - request->SetContent(content); - request->SetSlotType(NotificationConstant::SlotType::CUSTOM); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), true); - advancedNotificationService_->pushCallBacks_.clear(); - advancedNotificationService_->checkRequests_.clear(); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0002 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0003 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification except live view unregistered don't need push check. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0003, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0003 test start"; - sptr request = new NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::CUSTOM); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0003 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0004 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification published by system app don't need push check. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0004, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0004 test start"; - - sptr request = new NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::CUSTOM); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0004 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0005 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test live view notification except create status don't need pushCheck. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0005, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0005 test start"; - sptr request = new NotificationRequest(); - std::shared_ptr liveViewContent = std::make_shared(); - auto status = NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_INCREMENTAL_UPDATE; - liveViewContent->SetLiveViewStatus(status); - std::shared_ptr content = std::make_shared(liveViewContent); - request->SetContent(content); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0005 test end"; -} - -/** - * @tc.number : IsNeedPushCheckTest_0006 - * @tc.name : IsNeedPushCheckTest - * @tc.desc : Test notification except live view registered but has inconsistent contentType dont't need push check. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedPushCheckTest_0006, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0006 test start"; - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr pushCallBack = iface_cast(pushCallback); - - std::shared_ptr normalContent = std::make_shared(); - EXPECT_NE(normalContent, nullptr); - normalContent->SetText("normalContent's text"); - normalContent->SetTitle("normalContent's title"); - std::shared_ptr content = std::make_shared(normalContent); - - sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); - notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::CUSTOM); - notificationCheckRequest->SetContentType(NotificationContent::Type::PICTURE); - advancedNotificationService_->pushCallBacks_.insert_or_assign( - notificationCheckRequest->GetSlotType(), pushCallBack); - advancedNotificationService_->checkRequests_.insert_or_assign( - notificationCheckRequest->GetSlotType(), notificationCheckRequest); - - sptr request = new NotificationRequest(); - request->SetContent(content); - request->SetSlotType(NotificationConstant::SlotType::CUSTOM); - ASSERT_EQ(advancedNotificationService_->IsNeedPushCheck(request), false); - advancedNotificationService_->pushCallBacks_.clear(); - advancedNotificationService_->checkRequests_.clear(); - - GTEST_LOG_(INFO) << "IsNeedPushCheckTest_0006 test end"; -} -/** - * @tc.number : PushCheckTest_0001 - * @tc.name : PushCheckTest - * @tc.desc : Test registerer of push check is allowed. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, PushCheckTest_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "PushCheckTest_0001 test start"; - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - sptr pushCallback = pushCallbackProxy->AsObject(); - sptr notificationCheckRequest = new (std::nothrow)NotificationCheckRequest(); - notificationCheckRequest->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr pushCallBack = iface_cast(pushCallback); - advancedNotificationService_->pushCallBacks_.insert_or_assign( - notificationCheckRequest->GetSlotType(), pushCallBack); - advancedNotificationService_->checkRequests_.insert_or_assign( - notificationCheckRequest->GetSlotType(), notificationCheckRequest); - - sptr request = new NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - - ASSERT_EQ(advancedNotificationService_->PushCheck(request), ERR_OK); - - advancedNotificationService_->pushCallBacks_.clear(); - advancedNotificationService_->checkRequests_.clear(); - - GTEST_LOG_(INFO) << "PushCheckTest_0001 test end"; -} - -/** - * @tc.number : GetActiveNotificationByFilter_0001 - * @tc.name : GetActiveNotificationByFilter - * @tc.desc : Test get non-existent live view notification request by filter. - * @tc.require : #I6Z5OV - */ -HWTEST_F(AdvancedNotificationServiceTest, GetActiveNotificationByFilter_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetActiveNotificationByFilter_0001 test start"; - - TestAddSlot(NotificationConstant::SlotType::LIVE_VIEW); - sptr req; - - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - int32_t notificationId = 1; - std::string label = "GetActiveNotificationByFilter's label"; - std::vector extraInfoKeys; - - ASSERT_EQ(advancedNotificationService_->GetActiveNotificationByFilter(bundleOption, notificationId, label, - extraInfoKeys, req), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); - - GTEST_LOG_(INFO) << "GetActiveNotificationByFilter_0001 test end"; -} - -/** - * @tc.number : IsAllowedRemoveSlot_0001 - * @tc.name : IsAllowedRemoveSlot - * @tc.desc : Test IsAllowedRemoveSlot and slotType is not liveView. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0001 test start"; - sptr bundleOption = new NotificationBundleOption(); - ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, NotificationConstant::SlotType::OTHER), - (int)ERR_OK); - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0001 test end"; -} - -/** - * @tc.number : IsAllowedRemoveSlot_0002 - * @tc.name : IsAllowedRemoveSlot - * @tc.desc : Test IsAllowedRemoveSlot and slot is not exist. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0002 test start"; - sptr bundleOption = new NotificationBundleOption(); - ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, - NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0002 test end"; -} - -/** - * @tc.number : IsAllowedRemoveSlot_0003 - * @tc.name : IsAllowedRemoveSlot - * @tc.desc : Test IsAllowedRemoveSlot and slot is forcecontrol is false - */ -HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0003, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0003 test start"; - TestAddLiveViewSlot(false); - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, - NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0003 test end"; -} - -/** - * @tc.number : IsAllowedRemoveSlot_0004 - * @tc.name : IsAllowedRemoveSlot - * @tc.desc : Test IsAllowedRemoveSlot and caller not sa or systemapp - */ -HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0004, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0004 test start"; - TestAddLiveViewSlot(true); - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, - NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_ANS_NON_SYSTEM_APP); - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0004 test end"; -} - -/** - * @tc.number : IsAllowedRemoveSlot_0005 - * @tc.name : IsAllowedRemoveSlot - * @tc.desc : Test IsAllowedRemoveSlot and caller is systemapp - */ -HWTEST_F(AdvancedNotificationServiceTest, IsAllowedRemoveSlot_0005, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0005 test start"; - TestAddLiveViewSlot(true); - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_EQ(advancedNotificationService_->IsAllowedRemoveSlot(bundleOption, - NotificationConstant::SlotType::LIVE_VIEW), (int)ERR_OK); - GTEST_LOG_(INFO) << "IsAllowedRemoveSlot_0005 test end"; -} - -/** - * @tc.name: NotificationSvrQueue_00001 - * @tc.desc: Test notificationSvrQueue is nullptr - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - - auto ret = advancedNotificationService_->CancelPreparedNotification(1, "label", bundle, 8); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - std::vector> requests; - ret = advancedNotificationService_->GetActiveNotifications(requests, 0); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - uint64_t num = 0; - ret = advancedNotificationService_->GetActiveNotificationNums(num); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - int importance = 0; - ret = advancedNotificationService_->GetBundleImportance(importance); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - std::vector> notifications; - ret = advancedNotificationService_->GetAllActiveNotifications(notifications); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - std::vector keys; - ret = advancedNotificationService_->GetSpecialActiveNotifications(keys, notifications); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - bool enabled = false; - ret = advancedNotificationService_->IsDistributedEnabled(enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->EnableDistributed(enabled); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: NotificationSvrQueue_00002 - * @tc.desc: Test notificationSvrQueue is nullptr - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, NotificationSvrQueue_00002, Function | SmallTest | Level1) -{ - advancedNotificationService_->notificationSvrQueue_ = nullptr; - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - sptr bundle1 = nullptr; - auto request = new (std::nothrow) NotificationRequest(); - - auto ret = advancedNotificationService_->EnableDistributedSelf(true); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - bool enable = false; - ret = advancedNotificationService_->IsDistributedEnableByBundle(bundle, enable); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->GetHasPoppedDialog(bundle1, enable); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->SetSyncNotificationEnabledWithoutApp(1, enable); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - ret = advancedNotificationService_->GetSyncNotificationEnabledWithoutApp(1, enable); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); - - request->SetIsCoverActionButtons(true); - advancedNotificationService_->FillActionButtons(request); -} - -/** - * @tc.name: AssignToNotificationList_00001 - * @tc.desc: Test AssignToNotificationList - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, AssignToNotificationList_00001, Function | SmallTest | Level1) -{ - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - sptr request = new (std::nothrow) NotificationRequest(); - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto liveViewContent = std::make_shared(); - std::shared_ptr content = std::make_shared(liveViewContent); - request->SetContent(content); - request->SetSlotType(slotType); - request->SetNotificationId(1); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - auto ret = advancedNotificationService_->AssignToNotificationList(record); - - ret = advancedNotificationService_->AssignToNotificationList(record); - ASSERT_EQ(ret, (int)ERR_OK); - ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 1); -} - -/** - * @tc.name: StartArchiveTimer_00001 - * @tc.desc: Test StartArchiveTimer - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, StartArchiveTimer_00001, Function | SmallTest | Level1) -{ - auto slotType = NotificationConstant::SlotType::LIVE_VIEW; - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(slotType); - request->SetAutoDeletedTime(NotificationConstant::NO_DELAY_DELETE_TIME); - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->StartArchiveTimer(record); - ASSERT_EQ(request->GetAutoDeletedTime(), 0); -} - -/** - * @tc.name: Filter_00001 - * @tc.desc: Test Filter - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, Filter_00001, Function | SmallTest | Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - - advancedNotificationService_->notificationSlotFilter_ = nullptr; - auto ret = advancedNotificationService_->Filter(record, true); - ASSERT_EQ(ret, (int)ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: ChangeNotificationByControlFlags_00001 - * @tc.desc: Test ChangeNotificationByControlFlags - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, ChangeNotificationByControlFlags_00001, Function | SmallTest | Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - uint32_t notificationControlFlags = 0; - notificationControlFlags |= NotificationConstant::ReminderFlag::SOUND_FLAG; - notificationControlFlags |= NotificationConstant::ReminderFlag::LOCKSCREEN_FLAG; - notificationControlFlags |= NotificationConstant::ReminderFlag::BANNER_FLAG; - notificationControlFlags |= NotificationConstant::ReminderFlag::LIGHTSCREEN_FLAG; - notificationControlFlags |= NotificationConstant::ReminderFlag::VIBRATION_FLAG; - notificationControlFlags |= NotificationConstant::ReminderFlag::STATUSBAR_ICON_FLAG; - request->SetNotificationControlFlags(notificationControlFlags); - - std::shared_ptr flags = std::make_shared(); - flags->SetSoundEnabled(NotificationConstant::FlagStatus::OPEN); - flags->SetVibrationEnabled(NotificationConstant::FlagStatus::OPEN); - flags->SetLockScreenVisblenessEnabled(true); - flags->SetBannerEnabled(true); - flags->SetLightScreenEnabled(true); - flags->SetStatusIconEnabled(true); - request->SetFlags(flags); - - bool isAgentController = true; - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - advancedNotificationService_->ChangeNotificationByControlFlags(record, isAgentController); - - u_int32_t reminderFlags = flags->GetReminderFlags(); - ASSERT_EQ(reminderFlags, 0); -} - -/** - * @tc.name: CheckPublishPreparedNotification_00001 - * @tc.desc: Test CheckPublishPreparedNotification - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, CheckPublishPreparedNotification_00001, Function | SmallTest | Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - - auto ret = advancedNotificationService_->CheckPublishPreparedNotification(record, true); - ASSERT_EQ(ret, (int)ERR_OK); -} - -/** - * @tc.name: GetRecordFromNotificationList_00001 - * @tc.desc: Test GetRecordFromNotificationList - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, GetRecordFromNotificationList_00001, Function | SmallTest | Level1) -{ - sptr request = new (std::nothrow) NotificationRequest(); - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - request->SetLabel("label"); - request->SetNotificationId(1); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - auto ret = advancedNotificationService_->AssignToNotificationList(record); - - auto res = advancedNotificationService_->GetRecordFromNotificationList( - 1, SYSTEM_APP_UID, "label", TEST_DEFUALT_BUNDLE); - EXPECT_NE(res, nullptr); -} - -/** - * @tc.name: RegisterPushCallback_00001 - * @tc.desc: Test RegisterPushCallback - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, RegisterPushCallback_00001, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - sptr pushCallback = nullptr; - sptr request = nullptr; - - auto ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); - - MockIsVerfyPermisson(true); - ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); - ASSERT_EQ(ret, (int)ERR_INVALID_VALUE); - - auto pushCallbackProxy = new (std::nothrow)MockPushCallBackStub(); - EXPECT_NE(pushCallbackProxy, nullptr); - pushCallback = pushCallbackProxy->AsObject(); - ret = advancedNotificationService_->RegisterPushCallback(pushCallback, request); - ASSERT_EQ(ret, (int)ERR_INVALID_VALUE); -} - -/** - * @tc.name: UnregisterPushCallback_00001 - * @tc.desc: Test UnregisterPushCallback - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, UnregisterPushCallback_00001, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - - auto ret = advancedNotificationService_->UnregisterPushCallback(); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.name: CreateDialogManager_00001 - * @tc.desc: Test CreateDialogManager - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, CreateDialogManager_00001, Function | SmallTest | Level1) -{ - advancedNotificationService_->dialogManager_ = nullptr; - bool ret = advancedNotificationService_->CreateDialogManager(); - ASSERT_EQ(ret, true); - - ret = advancedNotificationService_->CreateDialogManager(); - ASSERT_EQ(ret, true); -} - -/** - * @tc.number : IsNeedNotifyConsumed_00001 - * @tc.name : IsNeedNotifyConsumed - * @tc.desc : Test IsNeedNotifyConsumed function. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00001 test start"; - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), true); - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00001 test end"; -} - -/** - * @tc.number : IsNeedNotifyConsumed_00002 - * @tc.name : IsNeedNotifyConsumed - * @tc.desc : Test IsNeedNotifyConsumed function. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00002, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00002 test start"; - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - auto liveViewContent = std::make_shared(); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_CREATE); - std::shared_ptr content = std::make_shared(liveViewContent); - request->SetContent(content); - ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), true); - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00002 test end"; -} - -/** - * @tc.number : GetAllNotificationEnabledBundles_0001 - * @tc.name : GetAllNotificationEnabledBundles - * @tc.desc : Test GetAllNotificationEnabledBundles function if not systemapp. - * @tc.require : #I92VGR - */ -HWTEST_F(AdvancedNotificationServiceTest, GetAllNotificationEnabledBundles_0001, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "GetAllNotificationEnabledBundles_0001 test start"; - - std::vector vec; - ASSERT_EQ(advancedNotificationService_->GetAllNotificationEnabledBundles(vec), ERR_ANS_NON_SYSTEM_APP); - - GTEST_LOG_(INFO) << "GetAllNotificationEnabledBundles_0001 test end"; -} - -/** - * @tc.number : IsNeedNotifyConsumed_00003 - * @tc.name : IsNeedNotifyConsumed - * @tc.desc : Test IsNeedNotifyConsumed function. - */ -HWTEST_F(AdvancedNotificationServiceTest, IsNeedNotifyConsumed_00003, Function | SmallTest | Level1) -{ - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00003 test start"; - sptr request = new (std::nothrow) NotificationRequest(); - request->SetSlotType(NotificationConstant::SlotType::LIVE_VIEW); - auto liveViewContent = std::make_shared(); - liveViewContent->SetLiveViewStatus(NotificationLiveViewContent::LiveViewStatus::LIVE_VIEW_END); - std::shared_ptr content = std::make_shared(liveViewContent); - request->SetContent(content); - request->SetAutoDeletedTime(0); - ASSERT_EQ(advancedNotificationService_->IsNeedNotifyConsumed(request), false); - GTEST_LOG_(INFO) << "IsNeedNotifyConsumed_00003 test end"; -} - -/** - * @tc.number : SetBadgeNumberByBundle_00001 - * @tc.name : SetBadgeNumberByBundle - * @tc.desc : Test SetBadgeNumberByBundle with valid parameters, expect error code ERR_OK. - */ -HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00001, Function | SmallTest | Level1) -{ - ASSERT_NE(advancedNotificationService_, nullptr); - MockIsSystemApp(true); - MockIsVerfyPermisson(true); - sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - ASSERT_NE(bundleOption, nullptr); - std::string bundleName = "invalidBundleName"; - bundleOption->SetBundleName(bundleName); - int32_t badgeNumber = 1; - ASSERT_EQ(advancedNotificationService_->SetBadgeNumberByBundle(bundleOption, badgeNumber), ERR_OK); -} - -/** - * @tc.number : SetBadgeNumberByBundle_00002 - * @tc.name : SetBadgeNumberByBundle - * @tc.desc : Test SetBadgeNumberByBundle with nullptr bundle option, expect error code ERR_ANS_INVALID_PARAM. - */ -HWTEST_F(AdvancedNotificationServiceTest, SetBadgeNumberByBundle_00002, Function | SmallTest | Level1) -{ - ASSERT_NE(advancedNotificationService_, nullptr); - MockIsSystemApp(true); - sptr bundleOption = nullptr; - int32_t badgeNumber = 1; - ASSERT_EQ(advancedNotificationService_->SetBadgeNumberByBundle(bundleOption, badgeNumber), ERR_ANS_INVALID_PARAM); -} - -/** - * @tc.name: QueryDoNotDisturbProfile_0100 - * @tc.desc: test QueryDoNotDisturbProfile successfully called - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, QueryDoNotDisturbProfile_0100, TestSize.Level1) -{ - std::string enable; - std::string profileId; - int32_t userId = 100; - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->QueryDoNotDisturbProfile(userId, enable, profileId); -} - -/** - * @tc.name: CheckDoNotDisturbProfile_0100 - * @tc.desc: test CheckDoNotDisturbProfile successfully called - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, CheckDoNotDisturbProfile_0100, TestSize.Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - EXPECT_NE(advancedNotificationService_, nullptr); - advancedNotificationService_->CheckDoNotDisturbProfile(record); -} - -/** - * @tc.name: DoNotDisturbUpdataReminderFlags_0100 - * @tc.desc: test DoNotDisturbUpdataReminderFlags can turn off all reminders. - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, DoNotDisturbUpdataReminderFlags_0100, TestSize.Level1) -{ - auto bundle = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - auto request = new (std::nothrow) NotificationRequest(); - auto record = advancedNotificationService_->MakeNotificationRecord(request, bundle); - std::shared_ptr flagsSet = std::make_shared(); - record->request->SetFlags(flagsSet); - sptr notification = new (std::nothrow) Notification(request); - record->request = request; - record->notification = notification; - advancedNotificationService_->DoNotDisturbUpdataReminderFlags(record); - auto flags = record->request->GetFlags(); - EXPECT_NE(flags, nullptr); - auto res = flags->IsStatusIconEnabled(); - ASSERT_EQ(res, false); -} - -#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED -/** - * @tc.name: RegisterSwingCallback_00001 - * @tc.desc: Test RegisterSwingCallback - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, RegisterSwingCallback_00001, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(true); - MockIsVerfyPermisson(false); - sptr swingCallback = nullptr; - auto ret = advancedNotificationService_->RegisterSwingCallback(swingCallback); - ASSERT_EQ(ret, (int)ERR_ANS_PERMISSION_DENIED); -} - -/** - * @tc.name: RegisterSwingCallback_00002 - * @tc.desc: Test RegisterSwingCallback - * @tc.type: FUNC - */ -HWTEST_F(AdvancedNotificationServiceTest, RegisterSwingCallback_00002, Function | SmallTest | Level1) -{ - MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); - MockIsSystemApp(false); - MockIsVerfyPermisson(true); - sptr swingCallback = nullptr; - auto ret = advancedNotificationService_->RegisterSwingCallback(swingCallback); - ASSERT_EQ(ret, (int)ERR_ANS_NON_SYSTEM_APP); -} -#endif - -/** - * @tc.number : AddExcludeDate_00001 - * @tc.name : Test AddExcludeDate - * @tc.desc : Test AddExcludeDate function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, AddExcludeDate_00001, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - uint64_t time = 124325; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->AddExcludeDate(reminderId, time), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - -/** - * @tc.number : DelExcludeDates_00002 - * @tc.name : Test DelExcludeDates - * @tc.desc : Test DelExcludeDates function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->DelExcludeDates(reminderId), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - -/** - * @tc.number : GetExcludeDates_00001 - * @tc.name : Test GetExcludeDates - * @tc.desc : Test GetExcludeDates function when the result is ERR_NO_INIT - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, GetExcludeDates_00001, Function | SmallTest | Level1) -{ - int32_t reminderId = 10; - std::vector times; - MockIsVerfyPermisson(false); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - MockIsNonBundleName(true); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_ANS_INVALID_BUNDLE); - MockIsNonBundleName(false); - ASSERT_EQ(advancedNotificationService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); - MockIsVerfyPermisson(false); -} - -/** - * @tc.number : PublishFlowControl_00001 - * @tc.name : Test PublishFlowControl - * @tc.desc : Test PublishFlowControl function when the record->slot is nullptr - * @tc.require : issueI5S4VP - */ -HWTEST_F(AdvancedNotificationServiceTest, PublishFlowControl_00001, Function | SmallTest | Level1) -{ - for (int i = 0; i < 100; i++) { - sptr request = new (std::nothrow) NotificationRequest(); - sptr notification = new (std::nothrow) Notification(request); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->notificationList_.push_back(record); - } - ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); - sptr request = new (std::nothrow) NotificationRequest(); - sptr notification = new (std::nothrow) Notification(request); - auto record = std::make_shared(); - record->request = request; - record->notification = notification; - advancedNotificationService_->PublishFlowControl(record); - ASSERT_EQ(advancedNotificationService_->notificationList_.size(), 100); -} -} // namespace Notification -} // namespace OHOS diff --git a/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp b/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp index bfc739cfc..6cfa18810 100755 --- a/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp +++ b/services/reminder/test/unittest/bundle_manager_helper_branch_test/bundle_manager_helper_branch_test.cpp @@ -16,10 +16,10 @@ #include #include -#include "ans_ut_constant.h" +#include "reminder_ut_constant.h" #define private public #define protected public -#include "bundle_manager_helper.h" +#include "reminder_bundle_manager_helper.h" #undef private #undef protected @@ -43,7 +43,7 @@ public: */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) { - BundleManagerHelper bundleManagerHelper; + ReminderBundleManagerHelper bundleManagerHelper; MockGetSystemAbilityManager(false); int32_t uid = 1; ASSERT_EQ("", bundleManagerHelper.GetBundleNameByUid(uid)); @@ -56,82 +56,12 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelperTest_00100, Function */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00200, Function | SmallTest | Level1) { - BundleManagerHelper bundleManagerHelper; + ReminderBundleManagerHelper bundleManagerHelper; MockGetSystemAbilityManager(true); int32_t uid = 1; ASSERT_EQ("", bundleManagerHelper.GetBundleNameByUid(uid)); } -/** - * @tc.number : BundleManagerHelper_00300 - * @tc.name : BundleManagerHelper_00300 - * @tc.desc : test IsSystemApp function and bundleMgr_ != nullptr - */ -HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00300, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - MockGetSystemAbilityManager(false); - int32_t uid = 1; - ASSERT_EQ(false, bundleManagerHelper.IsSystemApp(uid)); -} - -/** - * @tc.number : BundleManagerHelper_00400 - * @tc.name : BundleManagerHelper_00400 - * @tc.desc : test IsSystemApp function and bundleMgr_ == nullptr - */ -HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00400, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - MockGetSystemAbilityManager(true); - int32_t uid = 1; - ASSERT_EQ(false, bundleManagerHelper.IsSystemApp(uid)); -} - -/** - * @tc.number : BundleManagerHelper_00500 - * @tc.name : BundleManagerHelper_00500 - * @tc.desc : test GetBundleInfoByBundleName function and bundleMgr_ == nullptr - */ -HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00500, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - MockGetSystemAbilityManager(true); - bundleManagerHelper.Connect(); - std::string bundle = "aa"; - int32_t userId = 1; - AppExecFwk::BundleInfo bundleInfo; - ASSERT_EQ(false, bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo)); -} - -/** - * @tc.number : BundleManagerHelper_00600 - * @tc.name : BundleManagerHelper_00600 - * @tc.desc : test GetBundleInfoByBundleName function and bundleMgr_ != nullptr - */ -HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00600, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - MockGetSystemAbilityManager(false); - bundleManagerHelper.Connect(); - std::string bundle = "aa"; - int32_t userId = 1; - AppExecFwk::BundleInfo bundleInfo; - ASSERT_EQ(false, bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo)); -} - -/** - * @tc.number : BundleManagerHelper_00700 - * @tc.name : BundleManagerHelper_00700 - * @tc.desc : test CheckApiCompatibility function and GetBundleInfoByBundleName is false - */ -HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00700, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); - ASSERT_EQ(false, bundleManagerHelper.CheckApiCompatibility(bundleOption)); -} - /** * @tc.number : BundleManagerHelper_00800 * @tc.name : BundleManagerHelper_00800 @@ -139,7 +69,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00700, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00800, Function | SmallTest | Level1) { - std::shared_ptr bundleManagerHelper = std::make_shared(); + std::shared_ptr bundleManagerHelper = std::make_shared(); ASSERT_NE(nullptr, bundleManagerHelper); MockGetSystemAbilityManager(true); bundleManagerHelper->Connect(); @@ -152,7 +82,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00800, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00900, Function | SmallTest | Level1) { - std::shared_ptr bundleManagerHelper = std::make_shared(); + std::shared_ptr bundleManagerHelper = std::make_shared(); ASSERT_NE(nullptr, bundleManagerHelper); MockGetSystemAbilityManager(false); // test Connect and bundleMgr_ == nullptr @@ -166,7 +96,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_00900, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01000, Function | SmallTest | Level1) { - std::shared_ptr bundleManagerHelper = std::make_shared(); + std::shared_ptr bundleManagerHelper = std::make_shared(); ASSERT_NE(nullptr, bundleManagerHelper); MockGetSystemAbilityManager(false); bundleManagerHelper->Connect(); @@ -181,7 +111,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01000, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01100, Function | SmallTest | Level1) { - std::shared_ptr bundleManagerHelper = std::make_shared(); + std::shared_ptr bundleManagerHelper = std::make_shared(); ASSERT_NE(nullptr, bundleManagerHelper); MockGetSystemAbilityManager(false); bundleManagerHelper->Connect(); @@ -195,7 +125,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01100, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01200, Function | SmallTest | Level1) { - std::shared_ptr bundleManagerHelper = std::make_shared(); + std::shared_ptr bundleManagerHelper = std::make_shared(); ASSERT_NE(nullptr, bundleManagerHelper); bundleManagerHelper->Disconnect(); } @@ -207,7 +137,7 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01200, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01300, Function | SmallTest | Level1) { - BundleManagerHelper bundleManagerHelper; + ReminderBundleManagerHelper bundleManagerHelper; MockGetSystemAbilityManager(true); std::string bundle = "aa"; int32_t userId = 1; @@ -221,25 +151,12 @@ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01300, Function | Sm */ HWTEST_F(BundleManagerHelperBranchTest, BundleManagerHelper_01400, Function | SmallTest | Level1) { - BundleManagerHelper bundleManagerHelper; + ReminderBundleManagerHelper bundleManagerHelper; MockGetSystemAbilityManager(false); std::string bundle = "aa"; int32_t userId = 1; ASSERT_EQ(-1, bundleManagerHelper.GetDefaultUidByBundleName(bundle, userId)); } -/** - * @tc.number : GetBundleInfos_00001 - * @tc.name : GetBundleInfos_00001 - * @tc.desc : test GetBundleInfos - */ -HWTEST_F(BundleManagerHelperBranchTest, GetBundleInfos_00001, Function | SmallTest | Level1) -{ - BundleManagerHelper bundleManagerHelper; - AppExecFwk::BundleFlag flag = AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT; - std::vector bundleInfos; - - ASSERT_EQ(false, bundleManagerHelper.GetBundleInfos(flag, bundleInfos, 1)); -} } // namespace Notification } // namespace OHOS diff --git a/services/reminder/test/unittest/bundle_manager_helper_test.cpp b/services/reminder/test/unittest/bundle_manager_helper_test.cpp index 3f9845635..7c608ec8e 100644 --- a/services/reminder/test/unittest/bundle_manager_helper_test.cpp +++ b/services/reminder/test/unittest/bundle_manager_helper_test.cpp @@ -18,7 +18,7 @@ #define private public #define protected public -#include "bundle_manager_helper.h" +#include "reminder_bundle_manager_helper.h" #undef private #undef protected @@ -26,7 +26,6 @@ #include "ipc_skeleton.h" #include "iservice_registry.h" #include "system_ability_definition.h" -#include "access_token_helper.h" using namespace testing::ext; namespace OHOS { @@ -47,114 +46,9 @@ public: HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) { pid_t callingUid = IPCSkeleton::GetCallingUid(); - std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); + std::shared_ptr bundleManager = ReminderBundleManagerHelper::GetInstance(); ASSERT_EQ(bundleManager->GetBundleNameByUid(callingUid), "bundleName"); } -/** - * @tc.number : BundleManagerHelperTest_00200 - * @tc.name : ANS_IsSystemApp_0100 - * @tc.desc : Test IsSystemApp function - */ -HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) -{ - pid_t callingUid = 100; - std::shared_ptr bundleManager = BundleManagerHelper::GetInstance(); - EXPECT_TRUE(bundleManager->IsSystemApp(callingUid)); -} - -/** - * @tc.number : BundleManagerHelperTest_00300 - * @tc.name : CheckApiCompatibility - * @tc.desc : Test CheckApiCompatibility function when the bundleOption is nullptr,return is true - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00300, Level1) -{ - sptr bundleOption = nullptr; - BundleManagerHelper bundleManagerHelper; - bool result = bundleManagerHelper.CheckApiCompatibility(bundleOption); - ASSERT_EQ(result, true); -} - -/** - * @tc.number : BundleManagerHelperTest_00301 - * @tc.name : CheckApiCompatibility - * @tc.desc : Test CheckApiCompatibility function when the bundleOption is nullptr,return is true - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00301, Level1) -{ - std::string bundleName = "BundleName"; - int32_t uid = 10; - sptr bundleOption = new (std::nothrow) NotificationBundleOption(bundleName, uid); - BundleManagerHelper bundleManagerHelper; - bool result = bundleManagerHelper.CheckApiCompatibility(bundleOption); - ASSERT_EQ(result, true); -} - -/** - * @tc.number : BundleManagerHelperTest_00400 - * @tc.name : GetBundleInfoByBundleName - * @tc.desc : get bundleinfo by bundlename when the parameeter are normal, return is true - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00400, Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 1; - AppExecFwk::BundleInfo bundleInfo; - BundleManagerHelper bundleManagerHelper; - bool result = bundleManagerHelper.GetBundleInfoByBundleName(bundle, userId, bundleInfo); - ASSERT_EQ(result, true); -} - -/** - * @tc.number : BundleManagerHelperTest_00500 - * @tc.name : GetDefaultUidByBundleName - * @tc.desc : Test GetDefaultUidByBundleName function when the parameeter are normal - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00500, Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 1; - BundleManagerHelper bundleManagerHelper; - int32_t result = bundleManagerHelper.GetDefaultUidByBundleName(bundle, userId); - ASSERT_EQ(result, 1000); -} - -/** - * @tc.number : GetDistributedNotificationEnabled_00100 - * @tc.name : GetDistributedNotificationEnabled - * @tc.desc : Test GetDistributedNotificationEnabled function when the parameeter are normal - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, GetDistributedNotificationEnabled_00100, Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 1; - BundleManagerHelper bundleManagerHelper; - bool result = bundleManagerHelper.GetDistributedNotificationEnabled(bundle, userId); - ASSERT_EQ(result, true); -} - -/** - * @tc.number : GetDistributedNotificationEnabled_00101 - * @tc.name : GetDistributedNotificationEnabled - * @tc.desc : Test GetDistributedNotificationEnabled function when the parameeter are normal - * @tc.require : issueI5S4VP - */ -HWTEST_F(BundleManagerHelperTest, GetDistributedNotificationEnabled_00101, Level1) -{ - std::string bundle = "Bundle"; - int32_t userId = 1; - std::shared_ptr bundleManagerHelper = std::make_shared(); - ASSERT_NE(nullptr, bundleManagerHelper); - sptr remoteObject; - bundleManagerHelper->bundleMgr_ = iface_cast(remoteObject); - bool result = bundleManagerHelper->GetDistributedNotificationEnabled(bundle, userId); - ASSERT_EQ(result, true); -} } // namespace Notification } // namespace OHOS diff --git a/services/reminder/test/unittest/mock/blob.cpp b/services/reminder/test/unittest/mock/blob.cpp deleted file mode 100644 index 9acb0f99d..000000000 --- a/services/reminder/test/unittest/mock/blob.cpp +++ /dev/null @@ -1,195 +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. - */ - -#define LOG_TAG "Blob" - -#include "blob.h" -#include - -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()) { - 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; -} - -/* 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/reminder/test/unittest/mock/distributed_kv_data_manager.cpp b/services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp deleted file mode 100644 index fd12f6b0a..000000000 --- a/services/reminder/test/unittest/mock/distributed_kv_data_manager.cpp +++ /dev/null @@ -1,61 +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. - */ - -#define LOG_TAG "DistributedKvDataManager" - -#include "distributed_kv_data_manager.h" -#include "mock_single_kv_store.h" -#include "types.h" - -namespace OHOS { -namespace DistributedKv { -DistributedKvDataManager::DistributedKvDataManager() -{} - -DistributedKvDataManager::~DistributedKvDataManager() -{} - -Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, - std::shared_ptr &kvStore) -{ - std::string storeIdTmp = storeId.storeId; - kvStore = std::make_shared(); - return Status::SUCCESS; -} - -Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId) -{ - return Status::SUCCESS; -} - -Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr &kvStorePtr) -{ - return Status::SUCCESS; -} - -Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId, const std::string &path) -{ - 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/reminder/test/unittest/mock/include/mock_ans_subscriber.h b/services/reminder/test/unittest/mock/include/mock_ans_subscriber.h deleted file mode 100644 index 8914fea6f..000000000 --- a/services/reminder/test/unittest/mock/include/mock_ans_subscriber.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright (c) 2023-2024 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_MOCK_ANS_SUBCRIBER_OBJECT_H -#define BASE_NOTIFICATION_MOCK_ANS_SUBCRIBER_OBJECT_H - -#include "gmock/gmock.h" -#include "ans_subscriber_interface.h" - -namespace OHOS { -namespace Notification { -class MockAnsSubscriber : public AnsSubscriberInterface { -public: - MockAnsSubscriber() {} - ~MockAnsSubscriber() {} - - sptr AsObject() override - { - return nullptr; - } - void OnConnected() override {}; - - void OnDisconnected() override {}; - - void OnConsumed( - const sptr ¬ification, const sptr ¬ificationMap) override {}; - - MOCK_METHOD(void, OnConsumedList, (const std::vector> ¬ifications, - const sptr ¬ificationMap)); - - void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, - int32_t deleteReason) override {}; - - void OnCanceledList(const std::vector> ¬ifications, - const sptr ¬ificationMap, int32_t deleteReason) override {}; - - void OnUpdated(const sptr ¬ificationMap) override {}; - - void OnDoNotDisturbDateChange(const sptr &date) override {}; - - void OnEnabledNotificationChanged(const sptr &callbackData) override {}; - - void OnBadgeChanged(const sptr &badgeData) override {}; - - void OnBadgeEnabledChanged(const sptr &callbackData) override {}; -}; -} // namespace Notification -} // namespace OHOS -#endif diff --git a/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h b/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h deleted file mode 100644 index f514360df..000000000 --- a/services/reminder/test/unittest/mock/include/mock_push_callback_stub.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2023 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_PUSH_CALL_BACK_STUB_H -#define ANS_MOCK_PUSH_CALL_BACK_STUB_H - -#include -#include - -#include "push_callback_interface.h" - -namespace OHOS { -class MockPushCallBackStub : public IRemoteStub { -public: - MockPushCallBackStub(); - virtual ~MockPushCallBackStub(); - virtual int32_t OnCheckNotification(const std::string ¬ificationData, - const std::shared_ptr &pushCallBackParam) override; -}; -} // namespace OHOS -#endif // ANS_MOCK_PUSH_CALL_BACK_STUB_H diff --git a/services/reminder/test/unittest/mock/include/mock_single_kv_store.h b/services/reminder/test/unittest/mock/include/mock_single_kv_store.h deleted file mode 100644 index 844a4ad5a..000000000 --- a/services/reminder/test/unittest/mock/include/mock_single_kv_store.h +++ /dev/null @@ -1,338 +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 ANS_MOCK_SINGLE_KV_STORE_H -#define ANS_MOCK_SINGLE_KV_STORE_H - -#include -#include - -#include "data_query.h" -#include "kvstore.h" -#include "kvstore_observer.h" -#include "kvstore_result_set.h" -#include "kvstore_sync_callback.h" -#include "single_kvstore.h" -#include "types.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 MockSingleKvStore : public SingleKvStore { -public: - /** - * @brief Get all entries in this store which key start with prefixKey. - * - * @param perfixkey Indicates the prefix to be searched. - * @param entries Indicates the entries. - * @return Indicates the status of this GetEntries operation. - */ - Status GetEntries(const Key &prefixKey, std::vector &entries) const override; - - /** - * @brief Get all entries in this store by query. - * - * @param query Indicates the query object. - * @param entries Indicates the entries. - * @return Indicates the status of this GetEntries operation. - */ - Status GetEntries(const DataQuery &query, std::vector &entries) const override; - - /** - * @brief Get ResultSet in this store which key start with prefixKey. - * - * @param perfixkey Indicates the prefix to be searched. - * @param resultSet Indicates the resultSet. - * @return Indicates the status of this GetResultSet operation. - */ - Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; - - /** - * @brief Get ResultSet in this store by Query. - * - * @param query Indicates the query object. - * @param resultSet Indicates the resultSet. - * @return Indicates the status of this GetResultSet operation. - */ - Status GetResultSet(const DataQuery &query, std::shared_ptr &resultSet) const override; - - /** - * @brief Close the ResultSet returned by GetResultSet. - * - * @param resultSet Indicates the resultSet. - * @return Indicates the status of this CloseResultSet operation. - */ - Status CloseResultSet(std::shared_ptr &resultSet) override; - - /** - * @brief Get the number of result by query. - * - * @param query Indicates the query object. - * @param result Indicates the result will be returned in this parameter. - * @return Indicates the status of this CloseResultSet operation. - */ - Status GetCount(const DataQuery &query, int &result) const override; - - /** - * @brief Sync store with other devices. This is an asynchronous method, - * sync will fail if there is a syncing operation in progress. - * - * @param deviceIds Indicates the device list to sync. - * @param mode Indicates the sync 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. - * @param allowedDelayMs Indicates the allowed delay milli-second to sync. default value is 0 for compatibility. - * @return Indicates the status of this Sync operation. - */ - Status Sync(const std::vector &deviceIds, SyncMode mode, uint32_t delayMs) override; - - /** - * @brief Remove the device data synced from remote. - * - * @param device Indicates the device id. - * @return Indicates the status of this remove operation. - */ - Status RemoveDeviceData(const std::string &device) override; - - /** - * @brief Get id of this AppKvStore. - * - * @return Indicates the id of store. - */ - StoreId GetStoreId() const override; - - /** - * @brief Delete an entry by its key. - * - * @param key Indicates the key of the entry to be deleted. - * @return Indicates the status of this delete operation. - */ - Status Delete(const Key &key) override; - - /** - * @brief Write a pair of key and value to this store. - * - * @param key Indicates the key of this entry. Should be less than 256 bytes. key will be trimmed before store. - * @param value Indicates the value of this entry. Should be less than (1024 * 1024) bytes. - * @return Indicates the status of this put operation. - */ - Status Put(const Key &key, const Value &value) override; - - /** - * @brief Get value from AppKvStore by its key. - * - * @param key Indicates the key of this entry. - * @param value Indicates the value will be returned in this parameter. - * @return Indicates the status of this get operation. - */ - Status Get(const Key &key, Value &value) override; - - /** - * @brief Register change of this kvstore to a client-defined observer. - * observer->OnChange method will be called when store changes. - * One observer can subscribe more than one AppKvStore. - * - * @param subscribeType Indicates the subscribe type. - * OBSERVER_CHANGES_NATIVE means native changes of syncable kv store, - * OBSERVER_CHANGES_FOREIGN means synced data changes from remote devices, - * OBSERVER_CHANGES_ALL means both native changes and synced data changes. - * @param observer Indicates the observer to subscribe changes. - * @return Indicates the status of this subscribe operation. - */ - Status SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; - - /** - * @brief Unregister a kvstore to an observer. - * - * @param subscribeType Indicates the subscribe type. - * Reserved parameter. Current is always SubscribeType::DEFAULT. - * @param observer Indicates the observer to unsubscribe this store. - * @return Indicates the status of this unsubscribe operation. - */ - Status UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) override; - - /** - * @brief Register message for sync operation. - * - * @param callback Indicates the callback to register. - * @return Indicates the status of this register operation. - */ - Status RegisterSyncCallback(std::shared_ptr callback) override; - - /** - * @brief Unregister message for sync operation. - * - * @param callback Indicates the callback to register. - * @return Indicates the status of this register operation. - */ - Status UnRegisterSyncCallback() override; - - /** - * @brief 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. - * - * @param entries Indicates the entries. - * The entries's size should be less than 128 and memory size must be less than IPC transport limit. - * @return Indicates the status of this register operation. - */ - Status PutBatch(const std::vector &entries) override; - - /** - * @brief 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. - * - * @param keys Indicates the list of keys. - * The keys memory size should not be greater than IPC transport limit, and can not be empty. - * @return Indicates the status of this register operation. - */ - Status DeleteBatch(const std::vector &keys) override; - - /** - * @brief 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. - * - * @return Indicates the status of this operation. - */ - virtual Status StartTransaction() override; - - /** - * @brief 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. - * - * @return Indicates the status of this operation. - */ - virtual Status Commit() override; - - /** - * @brief 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. - * - * @return Indicates the status of this operation. - */ - virtual Status Rollback() override; - - /** - * @brief Set synchronization parameters of this store. - * - * @param syncParam Indicates the sync policy parameter. - * @return Indicates the status of this operation. - */ - virtual Status SetSyncParam(const KvSyncParam &syncParam) override; - - /** - * @brief Get synchronization parameters of this store. - * - * @param syncParam Indicates the sync policy parameter. - * @return Indicates the status of this operation. - */ - virtual Status GetSyncParam(KvSyncParam &syncParam) override; - - /** - * @brief Set capability parameters of this store. - * - * @param enabled Indicates the capability Enabled status. - * @return Indicates the status of this operation. - */ - virtual Status SetCapabilityEnabled(bool enabled) const override; - - /** - * @brief Set capability parameters of this store. - * - * @param localLabels Indicates the labels of local. - * @param remoteSupportLabels Indicates the labels of remote support. - * @return Indicates the status of this operation. - */ - virtual Status SetCapabilityRange(const std::vector &localLabels, - const std::vector &remoteSupportLabels) const override; - - /** - * @brief Get security level. - * - * @param securityLevel Indicates the security level. - * @return Indicates the status of this operation. - */ - virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; - - /** - * @brief Sync store with other devices only syncing the data which is satisfied with the condition. - * This is an asynchronous method, sync will fail if there is a syncing operation in progress. - * - * @param deviceIds Indicates the device list to sync, this is network id from soft bus. - * @param query Indicates the query condition. - * @param mode Indicates the sync mode, can be set to SyncMode::PUSH, SyncMode::PULL and SyncMode::PUSH_PULL. - * PUSH_PULL will firstly push all not-local store to listed devices, then pull these stores back. - * @return Indicates the status of this operation. - */ - virtual Status Sync(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, - std::shared_ptr syncCallback) override; - - /** - * @brief Subscribe store with other devices consistently Synchronize the data which is satisfied - * with the condition. - * - * @param deviceIds Indicates the device list to sync, this is network id from soft bus. - * @param query Indicates the query condition. - * - * @return Indicates the status of this operation. - */ - virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - - /** - * @brief UnSubscribe store with other devices which is satisfied with the condition. - * - * @param deviceIds Indicates the device list to sync, this is network id from soft bus. - * @param query Indicates the query condition. - * @return Indicates the status of this UnSubscribe operation. - */ - virtual Status UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; - - /** - * @brief backup the store to a specified backup file - * - * @param file target file of backup. - * @param baseDir root path of store manager. - * @return Indicates the status of this backup operation. - */ - virtual Status Backup(const std::string &file, const std::string &baseDir) override; - - /** - * @brief restore the store from a specified backup file - * - * @param file target file of backup. - * @param baseDir root path of store manager. - * @return Indicates the status of this restore operation. - */ - virtual Status Restore(const std::string &file, const std::string &baseDir) override; - - /** - * @brief delete the backup files - * - * @param file target file of backup. - * @param baseDir root path of store manager. - * @param status result of delete backup. - * @return Indicates the status of this delete backup operation. - */ - virtual Status DeleteBackup(const std::vector &files, const std::string &baseDir, - std::map &status) override; -}; -} // namespace DistributedKv -} // namespace OHOS -#endif // SINGLE_KV_STORE_H diff --git a/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h b/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h deleted file mode 100644 index 7bfd08533..000000000 --- a/services/reminder/test/unittest/mock/include/mock_swing_callback_stub.h +++ /dev/null @@ -1,33 +0,0 @@ -/* - * Copyright (c) 2024 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_SWING_CALL_BACK_STUB_H -#define ANS_MOCK_SWING_CALL_BACK_STUB_H -#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED - -#include -#include - -#include "swing_callback_interface.h" - -namespace OHOS { -class MockSwingCallBackStub : public IRemoteStub { -public: - MockSwingCallBackStub(); - virtual ~MockSwingCallBackStub(); - virtual int32_t OnUpdateStatus(bool isEnable, int triggerMode) override; -}; -} // namespace OHOS -#endif // ANS_MOCK_SWING_CALL_BACK_STUB_H -#endif diff --git a/services/reminder/test/unittest/mock/mock_access_token_helper.cpp b/services/reminder/test/unittest/mock/mock_access_token_helper.cpp index ee0061f47..5bc5dfd60 100644 --- a/services/reminder/test/unittest/mock/mock_access_token_helper.cpp +++ b/services/reminder/test/unittest/mock/mock_access_token_helper.cpp @@ -13,24 +13,19 @@ * limitations under the License. */ -#include "access_token_helper.h" -#include "ans_ut_constant.h" +#include "reminder_access_token_helper.h" +#include "reminder_ut_constant.h" #include "ipc_skeleton.h" namespace OHOS { namespace Notification { -bool AccessTokenHelper::VerifyCallerPermission( - const Security::AccessToken::AccessTokenID &tokenCaller, const std::string &permission) -{ - return true; -} -bool AccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) +bool ReminderAccessTokenHelper::VerifyNativeToken(const Security::AccessToken::AccessTokenID &callerToken) { return callerToken == NATIVE_TOKEN; } -bool AccessTokenHelper::IsSystemApp() +bool ReminderAccessTokenHelper::IsSystemApp() { Security::AccessToken::AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); if (tokenId == NATIVE_TOKEN) { @@ -39,9 +34,5 @@ bool AccessTokenHelper::IsSystemApp() return false; } -bool AccessTokenHelper::IsDlpHap(const Security::AccessToken::AccessTokenID &callerToken) -{ - return callerToken == DLP_NATIVE_TOKEN; -} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp b/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp index 721080f62..ea0095d08 100644 --- a/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp +++ b/services/reminder/test/unittest/mock/mock_accesstoken_kit.cpp @@ -15,7 +15,7 @@ #include "accesstoken_kit.h" #include "ans_log_wrapper.h" -#include "ans_ut_constant.h" +#include "reminder_ut_constant.h" #include "ipc_skeleton.h" using namespace OHOS::Security::AccessToken; diff --git a/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp b/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp deleted file mode 100644 index 019ea855e..000000000 --- a/services/reminder/test/unittest/mock/mock_advanced_notification_service.cpp +++ /dev/null @@ -1,51 +0,0 @@ -/* - * Copyright (c) 2023 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 "advanced_notification_service.h" -#include "ans_inner_errors.h" - -namespace { - bool g_mockGetDistributedEnableInApplicationInfoRet = true; - bool g_mockAppInfoEnableRet = true; -} - -void MockGetDistributedEnableInApplicationInfo(bool mockRet, uint8_t mockCase = 0) -{ - g_mockGetDistributedEnableInApplicationInfoRet = mockRet; - switch (mockCase) { - case 1: { // mock for appInfoEnable - g_mockAppInfoEnableRet = true; - break; - } - default:{ - g_mockAppInfoEnableRet = false; - break; - } - } -} - -namespace OHOS { -namespace Notification { -ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo( - const sptr bundleOption, bool &enable) -{ - enable = g_mockAppInfoEnableRet; - if (g_mockGetDistributedEnableInApplicationInfoRet == false) { - return ERR_ANS_INVALID_PARAM; - } - return ERR_OK; -} -} // namespace Notification -} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp index f03a0287d..96f711816 100644 --- a/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/reminder/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -13,30 +13,30 @@ * limitations under the License. */ -#include "bundle_manager_helper.h" +#include "reminder_bundle_manager_helper.h" -#include "ans_ut_constant.h" +#include "reminder_ut_constant.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "system_ability_definition.h" namespace OHOS { namespace Notification { -BundleManagerHelper::BundleManagerHelper() +ReminderBundleManagerHelper::ReminderBundleManagerHelper() {} -BundleManagerHelper::~BundleManagerHelper() +ReminderBundleManagerHelper::~ReminderBundleManagerHelper() {} -void BundleManagerHelper::OnRemoteDied(const wptr &object) +void ReminderBundleManagerHelper::OnRemoteDied(const wptr &object) {} -std::string BundleManagerHelper::GetBundleNameByUid(int uid) +std::string ReminderBundleManagerHelper::GetBundleNameByUid(int uid) { return (uid == NON_BUNDLE_NAME_UID) ? "" : "bundleName"; } -int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) +int ReminderBundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, const int32_t userId) { if (userId == 0) { return -1; @@ -45,38 +45,11 @@ int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle, co } } -bool BundleManagerHelper::IsSystemApp(int uid) -{ - return (uid == SYSTEM_APP_UID || uid == NON_BUNDLE_NAME_UID); -} - -bool BundleManagerHelper::CheckApiCompatibility(const sptr &bundleOption) -{ - return true; -} - -bool BundleManagerHelper::GetBundleInfoByBundleName( - const std::string bundle, const int32_t userId, AppExecFwk::BundleInfo &bundleInfo) -{ - return true; -} - -void BundleManagerHelper::Connect() +void ReminderBundleManagerHelper::Connect() {} -void BundleManagerHelper::Disconnect() +void ReminderBundleManagerHelper::Disconnect() {} -#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) -{ - return true; -} -#endif - -bool BundleManagerHelper::CheckApiCompatibility(const std::string &bundleName, const int32_t &uid) -{ - return true; -} } // namespace Notification } // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp b/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp index 8ebd813fb..6ee523bdf 100644 --- a/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp +++ b/services/reminder/test/unittest/mock/mock_bundle_mgr.cpp @@ -17,7 +17,7 @@ #include #include -#include "ans_ut_constant.h" +#include "reminder_ut_constant.h" namespace OHOS { namespace Notification { diff --git a/services/reminder/test/unittest/mock/mock_event_handler.cpp b/services/reminder/test/unittest/mock/mock_event_handler.cpp deleted file mode 100644 index acc5ca6b9..000000000 --- a/services/reminder/test/unittest/mock/mock_event_handler.cpp +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "event_handler.h" - -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, const std::string &taskName) -{ - return EVENT_HANDLER_ERR_INVALID_PARAM; -} - -void EventHandler::RemoveAllFileDescriptorListeners() -{} - -void EventHandler::RemoveFileDescriptorListener(int32_t fileDescriptor) -{} - -void EventHandler::SetEventRunner(const std::shared_ptr &runner) -{} - -void EventHandler::DistributeEvent(const InnerEvent::Pointer &event) -{} - -void EventHandler::Dump(Dumper &dumper) -{} - -bool EventHandler::HasInnerEvent(uint32_t innerEventId) -{ - return true; -} - -bool EventHandler::HasInnerEvent(int64_t param) -{ - return true; -} - -std::string EventHandler::GetEventName(const InnerEvent::Pointer &event) -{ - return "132123"; -} - -bool EventHandler::IsIdle() -{ - return true; -} - -void EventHandler::ProcessEvent(const InnerEvent::Pointer &) -{} -} // namespace AppExecFwk -} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp b/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp deleted file mode 100644 index db18ddcd2..000000000 --- a/services/reminder/test/unittest/mock/mock_notification_analytics_util.cpp +++ /dev/null @@ -1,141 +0,0 @@ -/* -* Copyright (c) 2021-2024 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_analytics_util.h" - -namespace OHOS { -namespace Notification { - -HaMetaMessage::HaMetaMessage(uint32_t sceneId, uint32_t branchId) - : sceneId_(sceneId), branchId_(branchId) -{ -} - -bool HaMetaMessage::NeedReport() const -{ - return true; -} - -HaMetaMessage& HaMetaMessage::SceneId(uint32_t sceneId) -{ - sceneId_ = sceneId; - return *this; -} - -HaMetaMessage& HaMetaMessage::BranchId(uint32_t branchId) -{ - branchId_ = branchId; - return *this; -} - -HaMetaMessage& HaMetaMessage::ErrorCode(uint32_t errorCode) -{ - errorCode_ = errorCode; - return *this; -} - -HaMetaMessage& HaMetaMessage::Message(const std::string& message, bool print) -{ - message_ = message; - return *this; -} - -HaMetaMessage& HaMetaMessage::Checkfailed(bool checkfailed) -{ - checkfailed_ = checkfailed; - return *this; -} - -HaMetaMessage& HaMetaMessage::BundleName(const std::string& bundleName) -{ - bundleName_ = bundleName; - return *this; -} - -HaMetaMessage& HaMetaMessage::AgentBundleName(const std::string& agentBundleName) -{ - agentBundleName_ = agentBundleName; - return *this; -} - -HaMetaMessage& HaMetaMessage::TypeCode(int32_t typeCode) -{ - typeCode_ = typeCode; - return *this; -} - -HaMetaMessage& HaMetaMessage::NotificationId(int32_t notificationId) -{ - notificationId_ = notificationId; - return *this; -} - -std::string HaMetaMessage::GetMessage() const -{ - return message_; -} - -HaMetaMessage& HaMetaMessage::SlotType(int32_t slotType) -{ - slotType_ = slotType; - return *this; -} - -std::string HaMetaMessage::Build() const -{ - return std::string(""); -} - -void NotificationAnalyticsUtil::ReportPublishFailedEvent(const sptr& request, - const HaMetaMessage& message) -{ - return; -} - -void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const sptr& request, - HaMetaMessage& message) -{ - return; -} - -void NotificationAnalyticsUtil::CommonNotificationEvent(const sptr& request, - int32_t eventCode, const HaMetaMessage& message) -{ - return; -} - -void NotificationAnalyticsUtil::ReportNotificationEvent(const sptr& request, - EventFwk::Want want, int32_t eventCode, const std::string& reason) -{ - return; -} - -void NotificationAnalyticsUtil::ReportModifyEvent(const HaMetaMessage& message) -{ - return; -} - -void NotificationAnalyticsUtil::ReportDeleteFailedEvent(const HaMetaMessage& message) -{ - return; -} - -void NotificationAnalyticsUtil::ReportNotificationEvent(EventFwk::Want want, - int32_t eventCode, const std::string& reason) -{ - return; -} -} // namespace Notification -} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp b/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp deleted file mode 100644 index 450642a7d..000000000 --- a/services/reminder/test/unittest/mock/mock_push_callback_stub.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2023 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_push_callback_stub.h" - -namespace OHOS { -MockPushCallBackStub::MockPushCallBackStub() {} -MockPushCallBackStub::~MockPushCallBackStub() {} -int32_t MockPushCallBackStub::OnCheckNotification(const std::string ¬ificationData, - const std::shared_ptr &pushCallBackParam) -{ - return false; -} -} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_single_kv_store.cpp b/services/reminder/test/unittest/mock/mock_single_kv_store.cpp deleted file mode 100644 index aa774f06b..000000000 --- a/services/reminder/test/unittest/mock/mock_single_kv_store.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#include "mock_single_kv_store.h" -#include "types.h" - -namespace OHOS { -namespace DistributedKv { -Status MockSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetEntries(const DataQuery &query, std::vector &entries) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetResultSet(const DataQuery &query, std::shared_ptr &resultSet) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::CloseResultSet(std::shared_ptr &resultSet) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetCount(const DataQuery &query, int &result) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Sync(const std::vector &deviceIds, SyncMode mode, uint32_t delayMs) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::RemoveDeviceData(const std::string &device) -{ - return Status::SUCCESS; -} - -StoreId MockSingleKvStore::GetStoreId() const -{ - StoreId storeId; - storeId.storeId = ""; - return storeId; -} - -Status MockSingleKvStore::Delete(const Key &key) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Put(const Key &key, const Value &value) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Get(const Key &key, Value &value) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::RegisterSyncCallback(std::shared_ptr callback) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::UnRegisterSyncCallback() -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::PutBatch(const std::vector &entries) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::DeleteBatch(const std::vector &keys) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::StartTransaction() -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Commit() -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Rollback() -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::SetSyncParam(const KvSyncParam &syncParam) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetSyncParam(KvSyncParam &syncParam) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::SetCapabilityEnabled(bool enabled) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::SetCapabilityRange( - const std::vector &localLabels, const std::vector &remoteSupportLabels) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) const -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Sync(const std::vector &deviceIds, SyncMode mode, const DataQuery &query, - std::shared_ptr syncCallback) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::UnsubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Backup(const std::string &file, const std::string &baseDir) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::Restore(const std::string &file, const std::string &baseDir) -{ - return Status::SUCCESS; -} - -Status MockSingleKvStore::DeleteBackup( - const std::vector &files, const std::string &baseDir, - std::map &status) -{ - return Status::SUCCESS; -} -} // namespace DistributedKv -} // namespace OHOS diff --git a/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp b/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp deleted file mode 100644 index ccd224675..000000000 --- a/services/reminder/test/unittest/mock/mock_swing_callback_stub.cpp +++ /dev/null @@ -1,26 +0,0 @@ -/* - * Copyright (c) 2024 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. - */ -#ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED -#include "mock_swing_callback_stub.h" - -namespace OHOS { -MockSwingCallBackStub::MockSwingCallBackStub() {} -MockSwingCallBackStub::~MockSwingCallBackStub() {} -int32_t MockSwingCallBackStub::OnUpdateStatus(bool isEnable, int triggerMode) -{ - return 0; -} -} // namespace OHOS -#endif diff --git a/services/reminder/test/unittest/os_account_manager_helper_test.cpp b/services/reminder/test/unittest/os_account_manager_helper_test.cpp index a13607524..38c892916 100644 --- a/services/reminder/test/unittest/os_account_manager_helper_test.cpp +++ b/services/reminder/test/unittest/os_account_manager_helper_test.cpp @@ -16,14 +16,14 @@ #include #include -#include "os_account_manager_helper.h" +#include "reminder_os_account_manager_helper.h" #include "accesstoken_kit.h" using namespace testing::ext; namespace OHOS { namespace Notification { -class OsAccountManagerHelperTest : public testing::Test { +class ReminderOsAccountManagerHelperTest : public testing::Test { public: static void SetUpTestSuite() {}; static void TearDownTestSuite() {}; @@ -31,27 +31,16 @@ public: void TearDown() override {}; }; -/** - * @tc.number : GetCurrentCallingUserId_00100 - * @tc.name : GetCurrentCallingUserId_00100 - * @tc.desc : test GetCurrentCallingUserId function - */ -HWTEST_F(OsAccountManagerHelperTest, GetCurrentCallingUserId_00100, Function | SmallTest | Level1) -{ - int32_t userId = -1; - ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetCurrentCallingUserId(userId)); -} - /** * @tc.number : GetOsAccountLocalIdFromUid_00100 * @tc.name : GetOsAccountLocalIdFromUid_00100 * @tc.desc : test GetOsAccountLocalIdFromUid function */ -HWTEST_F(OsAccountManagerHelperTest, GetOsAccountLocalIdFromUid_00100, Function | SmallTest | Level1) +HWTEST_F(ReminderOsAccountManagerHelperTest, GetOsAccountLocalIdFromUid_00100, Function | SmallTest | Level1) { int32_t userId = -1; const int uid = 0; - ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId)); + ASSERT_EQ(ERR_OK, ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(uid, userId)); } /** @@ -59,76 +48,10 @@ HWTEST_F(OsAccountManagerHelperTest, GetOsAccountLocalIdFromUid_00100, Function * @tc.name : GetCurrentActiveUserId_00100 * @tc.desc : test GetCurrentActiveUserId function */ -HWTEST_F(OsAccountManagerHelperTest, GetCurrentActiveUserId_00100, Function | SmallTest | Level1) +HWTEST_F(ReminderOsAccountManagerHelperTest, GetCurrentActiveUserId_00100, Function | SmallTest | Level1) { int32_t userId = -1; - ASSERT_EQ(ERR_OK, OsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId)); -} - -/** - * @tc.number : CheckUserExists_00100 - * @tc.name : CheckUserExists_00100 - * @tc.desc : test CheckUserExists function - */ -HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00100, Function | SmallTest | Level1) -{ - int32_t userId = 100; - ASSERT_EQ(true, OsAccountManagerHelper::GetInstance().CheckUserExists(userId)); -} - -/** - * @tc.number : CheckUserExists_00200 - * @tc.name : CheckUserExists_00200 - * @tc.desc : test CheckUserExists function - */ -HWTEST_F(OsAccountManagerHelperTest, CheckUserExists_00200, Function | SmallTest | Level1) -{ - int32_t userId = 1099; - ASSERT_EQ(false, OsAccountManagerHelper::GetInstance().CheckUserExists(userId)); -} - -/** - * @tc.number : IsSystemAccount_0100 - * @tc.name : IsSystemAccount_0100 - * @tc.desc : test IsSystemAccount function, 100 is true(100 <= userId <= 10736) - */ -HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0100, Function | SmallTest | Level1) -{ - int32_t userId = 100; - ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); -} - -/** - * @tc.number : IsSystemAccount_0200 - * @tc.name : IsSystemAccount_0200 - * @tc.desc : test IsSystemAccount function, 1100 is false(100 <= userId <= 10736) - */ -HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0200, Function | SmallTest | Level1) -{ - int32_t userId = 10737; - ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); -} - -/** - * @tc.number : IsSystemAccount_0300 - * @tc.name : IsSystemAccount_0300 - * @tc.desc : test IsSystemAccount function, 0 is false(100 <= userId <= 10736) - */ -HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0300, Function | SmallTest | Level1) -{ - int32_t userId = 0; - ASSERT_EQ(false, OsAccountManagerHelper::IsSystemAccount(userId)); -} - -/** - * @tc.number : IsSystemAccount_0400 - * @tc.name : IsSystemAccount_0400 - * @tc.desc : test IsSystemAccount function, 1099 is true(100 <= userId <= 10736) - */ -HWTEST_F(OsAccountManagerHelperTest, IsSystemAccount_0400, Function | SmallTest | Level1) -{ - int32_t userId = 10736; - ASSERT_EQ(true, OsAccountManagerHelper::IsSystemAccount(userId)); + ASSERT_EQ(ERR_OK, ReminderOsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(userId)); } } } \ No newline at end of file diff --git a/services/reminder/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp index 5ca3295b1..148a3f2ee 100644 --- a/services/reminder/test/unittest/reminder_data_manager_test.cpp +++ b/services/reminder/test/unittest/reminder_data_manager_test.cpp @@ -42,7 +42,7 @@ class ReminderDataManagerTest : public testing::Test { public: static void SetUpTestCase() { - ReminderDataManager::InitInstance(nullptr); + ReminderDataManager::InitInstance(); manager = ReminderDataManager::GetInstance(); manager->Init(false); } @@ -68,12 +68,12 @@ std::shared_ptr ReminderDataManagerTest::manager = nullptr; HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_001, Level1) { sptr reminder = new ReminderRequestTimer(10); - sptr option = new NotificationBundleOption(); - manager->PublishReminder(reminder, option); - manager->CancelReminder(-1, option); - manager->CancelAllReminders("", -1, -1); + int32_t reminderId = -1; + manager->PublishReminder(reminder, reminderId); + manager->CancelReminder(reminderId, -1); + manager->CancelAllReminders(-1, -1); manager->CancelAllReminders(-1); - manager->IsMatched(reminder, "", -1, -1); + manager->IsMatched(reminder, -1, -1, true); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(manager != nullptr); } @@ -86,11 +86,12 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_001, Level1) */ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_002, Level1) { - sptr option = new NotificationBundleOption(); - std::vector> vec; - manager->GetValidReminders(option, vec); + int32_t callingUid = -1; + std::vector vec; + manager->GetValidReminders(callingUid, vec); sptr reminder = new ReminderRequestTimer(10); - manager->CheckReminderLimitExceededLocked(option, reminder); + + manager->CheckReminderLimitExceededLocked(callingUid, reminder); manager->CancelNotification(reminder); reminder->SetReminderId(10); manager->AddToShowedReminders(reminder); @@ -132,18 +133,17 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_003, Level1) */ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_004, Level1) { - sptr option = new NotificationBundleOption(); - manager->OnProcessDiedLocked(option); + int32_t callingUid = -1; + manager->OnProcessDiedLocked(callingUid); sptr reminder = new ReminderRequestTimer(10); manager->CreateTimerInfo(ReminderDataManager::TimerType::TRIGGER_TIMER, reminder); manager->CreateTimerInfo(ReminderDataManager::TimerType::ALERTING_TIMER, reminder); - manager->FindReminderRequestLocked(0, ""); + manager->FindReminderRequestLocked(0); reminder->SetReminderId(10); manager->reminderVector_.push_back(reminder); - manager->FindReminderRequestLocked(10, ""); - option->SetBundleName("test"); - manager->FindReminderRequestLocked(10, ""); - manager->FindReminderRequestLocked(10, "test"); + manager->FindReminderRequestLocked(10); + manager->FindReminderRequestLocked(10); + manager->FindReminderRequestLocked(10); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(manager != nullptr); } @@ -244,14 +244,12 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_008, Level1) */ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_009, Level1) { + int32_t callingUid = -1; sptr reminder = new ReminderRequestTimer(10); - sptr option = new NotificationBundleOption(); - manager->UpdateAndSaveReminderLocked(reminder, option); - sptr service(new AdvancedNotificationService); - manager->SetService(service); + manager->UpdateAndSaveReminderLocked(reminder, callingUid); + sptr service(new ReminderService); manager->ShouldAlert(nullptr); manager->currentUserId_ = 0; - option->SetUid(1); manager->ShouldAlert(reminder); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(manager != nullptr); @@ -447,22 +445,17 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_017, Level1) sptr reminder1 = new ReminderRequestTimer(10); sptr reminder2 = new ReminderRequestTimer(10); sptr reminder3 = new ReminderRequestTimer(10); - int32_t oldReminderId = 1; + int32_t callingUid = 1; reminder1->SetReminderId(1); reminder2->SetReminderId(2); reminder3->SetReminderId(3); reminder1->SetGroupId("123"); reminder2->SetGroupId("123"); reminder3->SetGroupId("124"); - sptr option1 = new NotificationBundleOption(); - sptr option2 = new NotificationBundleOption(); - sptr option3 = new NotificationBundleOption(); - option1->SetBundleName("test"); - option2->SetBundleName("test"); - manager->PublishReminder(reminder1, option1); - manager->PublishReminder(reminder2, option2); - manager->PublishReminder(reminder3, option3); - manager->CloseRemindersByGroupId(oldReminderId, "test", "123"); + manager->PublishReminder(reminder1, callingUid); + manager->PublishReminder(reminder2, callingUid); + manager->PublishReminder(reminder3, callingUid); + manager->CloseRemindersByGroupId(1, "test", "123"); system("rm -rf /data/service/el1/public/notification/"); EXPECT_TRUE(reminder2->isExpired_); } @@ -632,16 +625,12 @@ HWTEST_F(ReminderDataManagerTest, StartExtensionAbilityTest_001, Level1) */ HWTEST_F(ReminderDataManagerTest, IsBelongToSameAppTest_001, Level1) { - sptr option1 = new NotificationBundleOption("test", 100); - sptr option2 = new NotificationBundleOption("test", 100); - EXPECT_TRUE(manager->IsBelongToSameApp(option1, option2)); - - option2->SetUid(101); - EXPECT_FALSE(manager->IsBelongToSameApp(option1, option2)); + int32_t uidSrc = 100; + int32_t uidTar = 100; + EXPECT_TRUE(manager->IsBelongToSameApp(uidSrc, uidTar)); - option2->SetUid(100); - option2->SetBundleName("test1"); - EXPECT_FALSE(manager->IsBelongToSameApp(option1, option2)); + uidTar = 101; + EXPECT_FALSE(manager->IsBelongToSameApp(uidSrc, uidTar)); } /** @@ -654,12 +643,12 @@ HWTEST_F(ReminderDataManagerTest, CheckIsSameAppTest_001, Level1) { sptr reminder = new ReminderRequestTimer(10); reminder->InitCreatorBundleName("test"); - reminder->InitUserId(-1); - sptr option = new NotificationBundleOption("test", -1); - EXPECT_TRUE(manager->CheckIsSameApp(reminder, option)); + int32_t callingUid = 100; + reminder->InitCreatorUid(callingUid); + EXPECT_TRUE(manager->CheckIsSameApp(reminder, callingUid)); - reminder->InitCreatorBundleName("test1"); - EXPECT_FALSE(manager->CheckIsSameApp(reminder, option)); + reminder->InitCreatorUid(-1); + EXPECT_FALSE(manager->CheckIsSameApp(reminder, callingUid)); } /** @@ -671,13 +660,13 @@ HWTEST_F(ReminderDataManagerTest, CheckIsSameAppTest_001, Level1) HWTEST_F(ReminderDataManagerTest, CheckPulishReminder_0001, Level1) { sptr reminder = new ReminderRequestTimer(10); - sptr option = new NotificationBundleOption(); + int32_t callingUid = -1; IPCSkeleton::SetCallingTokenID(0); - ErrCode ret = manager->PublishReminder(reminder, option); + ErrCode ret = manager->PublishReminder(reminder, callingUid); ASSERT_EQ(ret, ERR_REMINDER_CALLER_TOKEN_INVALID); IPCSkeleton::SetCallingTokenID(1); - ret = manager->PublishReminder(reminder, option); + ret = manager->PublishReminder(reminder, callingUid); EXPECT_NE(ret, ERR_REMINDER_DATA_SHARE_PERMISSION_DENIED); } @@ -711,17 +700,18 @@ HWTEST_F(ReminderDataManagerTest, OnLanguageChanged_0001, Level1) */ HWTEST_F(ReminderDataManagerTest, ExcludeDate_0001, Level1) { - std::vector dates; - auto result = manager->CheckExcludeDateParam(9999, nullptr); + std::vector dates; + int32_t callingUid = -1; + auto result = manager->CheckExcludeDateParam(9999, callingUid); EXPECT_TRUE(result == nullptr); - auto ret = manager->AddExcludeDate(9999, 100, nullptr); + auto ret = manager->AddExcludeDate(9999, 100, callingUid); EXPECT_TRUE(ret == ERR_REMINDER_NOT_EXIST); - ret = manager->DelExcludeDates(9999, nullptr); + ret = manager->DelExcludeDates(9999, callingUid); EXPECT_TRUE(ret == ERR_REMINDER_NOT_EXIST); - ret = manager->GetExcludeDates(9999, nullptr, dates); + ret = manager->GetExcludeDates(9999, callingUid, dates); EXPECT_TRUE(ret == ERR_REMINDER_NOT_EXIST); sptr reminder = new ReminderRequestCalendar(10); @@ -729,30 +719,29 @@ HWTEST_F(ReminderDataManagerTest, ExcludeDate_0001, Level1) reminder->InitUserId(-1); reminder->reminderId_ = 100; manager->reminderVector_.push_back(reminder); - sptr option = new NotificationBundleOption("test", -1); - result = manager->CheckExcludeDateParam(100, option); + result = manager->CheckExcludeDateParam(100, callingUid); EXPECT_TRUE(result == nullptr); reminder->InitCreatorBundleName("test"); reminder->reminderType_ = ReminderRequest::ReminderType::TIMER; - result = manager->CheckExcludeDateParam(100, option); + result = manager->CheckExcludeDateParam(100, callingUid); EXPECT_TRUE(result == nullptr); reminder->reminderType_ = ReminderRequest::ReminderType::CALENDAR; - result = manager->CheckExcludeDateParam(100, option); + result = manager->CheckExcludeDateParam(100, callingUid); EXPECT_TRUE(result == nullptr); reminder->repeatDaysOfWeek_ = 1; - result = manager->CheckExcludeDateParam(100, option); + result = manager->CheckExcludeDateParam(100, callingUid); EXPECT_TRUE(result != nullptr); - ret = manager->AddExcludeDate(100, 100, option); + ret = manager->AddExcludeDate(100, 100, callingUid); EXPECT_TRUE(ret == ERR_OK); - ret = manager->DelExcludeDates(100, option); + ret = manager->DelExcludeDates(100, callingUid); EXPECT_TRUE(ret == ERR_OK); - ret = manager->GetExcludeDates(100, option, dates); + ret = manager->GetExcludeDates(100, callingUid, dates); EXPECT_TRUE(ret == ERR_OK); } @@ -775,48 +764,6 @@ HWTEST_F(ReminderDataManagerTest, InitStartExtensionAbility_0001, Level1) EXPECT_TRUE(!manager->reminderVector_.empty()); } -/** - * @tc.name: ReminderNotificationSubscriber_00001 - * @tc.desc: Reminder data manager test - * @tc.type: FUNC - * @tc.require: issue#I9IIDE - */ -HWTEST_F(ReminderDataManagerTest, ReminderNotificationSubscriber_00001, Level1) -{ - ReminderEventManager::ReminderNotificationSubscriber test(manager); - sptr notificationReq = new NotificationRequest(); - std::shared_ptr notification = std::make_shared(notificationReq); - test.OnCanceled(notification, nullptr, NotificationConstant::CANCEL_REASON_DELETE); - SUCCEED(); - - test.OnCanceled(nullptr, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel(""); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel("TEST_1"); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel("TEST_NOTIFICATION_1"); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel("REMINDER_NOTIFICATION_1"); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel("REMINDER_AGENT_INFO"); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); - - notificationReq->SetLabel("REMINDER_AGENT_0"); - test.OnCanceled(notification, nullptr, NotificationConstant::APP_CANCEL_REASON_DELETE); - SUCCEED(); -} - /** * @tc.name: CancelAllReminders_00001 * @tc.desc: Reminder data manager test @@ -825,10 +772,10 @@ HWTEST_F(ReminderDataManagerTest, ReminderNotificationSubscriber_00001, Level1) */ HWTEST_F(ReminderDataManagerTest, CancelAllReminders_00001, Level1) { - int32_t ret = manager->CancelAllReminders("", -1, -1); + int32_t ret = manager->CancelAllReminders(-1, -1); EXPECT_TRUE(ret == ERR_OK); - ret = manager->CancelAllReminders("com.example.simple", 100, 20020152); + ret = manager->CancelAllReminders(100, 20020152); EXPECT_TRUE(ret == ERR_OK); } @@ -845,8 +792,8 @@ HWTEST_F(ReminderDataManagerTest, GetVaildReminders_00001, Level1) reminder1->InitCreatorUid(98765); reminder1->InitBundleName("test_getvalid"); reminder1->InitUid(98765); - sptr option1 = new NotificationBundleOption("test_getvalid", 98765); - manager->PublishReminder(reminder1, option1); + int32_t callingUid = -1; + manager->PublishReminder(reminder1, callingUid); reminder1->SetExpired(false); sptr reminder2 = new ReminderRequestTimer(51); @@ -855,11 +802,10 @@ HWTEST_F(ReminderDataManagerTest, GetVaildReminders_00001, Level1) reminder2->InitBundleName("test_getvalid"); reminder2->InitUid(98765); reminder2->SetExpired(true); - sptr option2 = new NotificationBundleOption("test_getvalid", 98765); - manager->PublishReminder(reminder2, option2); + manager->PublishReminder(reminder2, callingUid); - std::vector> reminders; - manager->GetValidReminders(option2, reminders); + std::vector reminders; + manager->GetValidReminders(callingUid, reminders); EXPECT_TRUE(reminders.size() == 1); } @@ -877,17 +823,17 @@ HWTEST_F(ReminderDataManagerTest, IsMatched_00001, Level1) reminder->InitBundleName("test_IsMatched"); reminder->InitUid(98765); reminder->InitUserId(100); - bool ret = manager->IsMatched(reminder, "test_IsMatched", 101, 98765); + bool ret = manager->IsMatched(reminder, 101, 98765, true); EXPECT_EQ(ret, false); - ret = manager->IsMatched(reminder, "allPackages", 100, 98765); + ret = manager->IsMatched(reminder, 100, 98765, true); EXPECT_EQ(ret, true); - ret = manager->IsMatched(reminder, "test_IsMatched2", 100, 98765); + ret = manager->IsMatched(reminder, 100, 98765, true); EXPECT_EQ(ret, false); - ret = manager->IsMatched(reminder, "test_IsMatched", 100, -1); + ret = manager->IsMatched(reminder, 100, -1, true); EXPECT_EQ(ret, false); - ret = manager->IsMatched(reminder, "test_IsMatched", 100, 98766); + ret = manager->IsMatched(reminder, 100, 98766, true); EXPECT_EQ(ret, false); - ret = manager->IsMatched(reminder, "test_IsMatched", 100, 98765); + ret = manager->IsMatched(reminder, 100, 98765, true); EXPECT_EQ(ret, true); } } // namespace Notification diff --git a/services/reminder/test/unittest/reminder_service_test.cpp b/services/reminder/test/unittest/reminder_service_test.cpp new file mode 100644 index 000000000..2e1c72b73 --- /dev/null +++ b/services/reminder/test/unittest/reminder_service_test.cpp @@ -0,0 +1,193 @@ +/* + * Copyright (c) 2021-2024 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 "errors.h" +#include +#include +#include +#include + +#include "gtest/gtest.h" +#include + +#define private public + +#include "reminder_service.h" +#include "ans_const_define.h" +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" +#include "reminder_ut_constant.h" +#include "iremote_object.h" +#include "accesstoken_kit.h" +#include "mock_ipc_skeleton.h" + +extern void MockIsOsAccountExists(bool mockRet); + +using namespace testing::ext; +using namespace OHOS::Media; + +namespace OHOS { +namespace Notification { +extern void MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum mockRet); +extern void MockIsSystemApp(bool isSystemApp); +extern void MockIsNonBundleName(bool isNonBundleName); +extern void MockIsVerfyPermisson(bool isVerify); + +class ReminderServiceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + +private: + void TestAddSlot(NotificationConstant::SlotType type); + void TestAddLiveViewSlot(bool isForceControl); + void MockSystemApp(); + +private: + static sptr ReminderService_; +}; + +sptr ReminderServiceTest::ReminderService_ = nullptr; + +void ReminderServiceTest::SetUpTestCase() +{ + MockIsOsAccountExists(true); +} + +void ReminderServiceTest::TearDownTestCase() {} + +void ReminderServiceTest::SetUp() +{ + GTEST_LOG_(INFO) << "SetUp start"; + + ReminderService_ = new (std::nothrow) ReminderService(); + IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + ReminderService_->CancelAllReminders(); + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_NATIVE); + GTEST_LOG_(INFO) << "SetUp end"; +} + +void ReminderServiceTest::TearDown() +{ + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + ReminderService_ = nullptr; + GTEST_LOG_(INFO) << "TearDown"; +} + +inline void SleepForFC() +{ + // For Reminder Flow Control + std::this_thread::sleep_for(std::chrono::seconds(1)); +} + +/** + * @tc.number : ReminderServiceTest_13500 + * @tc.name : Reminder_GetValidReminders_0100 + * @tc.desc : Test GetValidReminders function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(ReminderServiceTest, ReminderServiceTest_13500, Function | SmallTest | Level1) +{ + std::vector reminders; + ASSERT_EQ(ReminderService_->GetValidReminders(reminders), (int)ERR_NO_INIT); +} + +/** + * @tc.number : ReminderServiceTest_16900 + * @tc.name : Reminder_GetActiveNotifications_0100 + * @tc.desc : Test function with bundle option is null + * @tc.require : #I60KYN + */ +HWTEST_F(ReminderServiceTest, ReminderServiceTest_16900, Function | SmallTest | Level1) +{ + GTEST_LOG_(INFO) << "Reminder_GetActiveNotifications_0100 test start"; + + MockIsNonBundleName(true); + MockSystemApp(); + int32_t reminderId = 1; + ASSERT_EQ(ReminderService_->CancelReminder(reminderId), ERR_ANS_INVALID_BUNDLE); + + ASSERT_EQ(ReminderService_->CancelAllReminders(), ERR_ANS_INVALID_BUNDLE); + + std::vector reminders; + ASSERT_EQ(ReminderService_->GetValidReminders(reminders), ERR_ANS_INVALID_BUNDLE); + + MockIsNonBundleName(false); + GTEST_LOG_(INFO) << "Reminder_GetActiveNotifications_0100 test end"; +} + +/** + * @tc.number : AddExcludeDate_00001 + * @tc.name : Test AddExcludeDate + * @tc.desc : Test AddExcludeDate function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(ReminderServiceTest, AddExcludeDate_00001, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + uint64_t time = 124325; + MockIsVerfyPermisson(false); + ASSERT_EQ(ReminderService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(ReminderService_->AddExcludeDate(reminderId, time), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(ReminderService_->AddExcludeDate(reminderId, time), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} + +/** + * @tc.number : DelExcludeDates_00002 + * @tc.name : Test DelExcludeDates + * @tc.desc : Test DelExcludeDates function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(ReminderServiceTest, DelExcludeDates_00002, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + MockIsVerfyPermisson(false); + ASSERT_EQ(ReminderService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(ReminderService_->DelExcludeDates(reminderId), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(ReminderService_->DelExcludeDates(reminderId), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} + +/** + * @tc.number : GetExcludeDates_00001 + * @tc.name : Test GetExcludeDates + * @tc.desc : Test GetExcludeDates function when the result is ERR_NO_INIT + * @tc.require : issueI5S4VP + */ +HWTEST_F(ReminderServiceTest, GetExcludeDates_00001, Function | SmallTest | Level1) +{ + int32_t reminderId = 10; + std::vector times; + MockIsVerfyPermisson(false); + ASSERT_EQ(ReminderService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); + TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + MockIsNonBundleName(true); + ASSERT_EQ(ReminderService_->GetExcludeDates(reminderId, times), (int)ERR_ANS_INVALID_BUNDLE); + MockIsNonBundleName(false); + ASSERT_EQ(ReminderService_->GetExcludeDates(reminderId, times), (int)ERR_NO_INIT); + MockIsVerfyPermisson(false); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp similarity index 57% rename from services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp rename to services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp index 2b31af2cc..931de2426 100644 --- a/services/reminder/test/unittest/advanced_notification_service_test/advanced_notification_service_publish_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp @@ -15,7 +15,6 @@ #include "errors.h" #include "notification_content.h" -#include "notification_record.h" #include "notification_request.h" #include #include @@ -27,26 +26,15 @@ #define private public -#include "advanced_notification_service.h" +#include "reminder_service.h" #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" -#include "ans_notification.h" -#include "ans_ut_constant.h" -#include "common_event_manager.h" -#include "common_event_support.h" +#include "reminder_ut_constant.h" #include "iremote_object.h" #include "mock_ipc_skeleton.h" -#include "notification_preferences.h" -#include "notification_subscriber.h" -#include "notification_subscriber_manager.h" -#include "mock_push_callback_stub.h" -#include "system_event_observer.h" -#include "notification_constant.h" -#include "want_agent_info.h" -#include "want_agent_helper.h" -#include "want_params.h" -#include "bundle_manager_helper.h" + +#include "reminder_bundle_manager_helper.h" extern void MockIsOsAccountExists(bool mockRet); @@ -60,7 +48,7 @@ extern void MockIsSystemApp(bool isSystemApp); extern void MockIsNonBundleName(bool isNonBundleName); extern void MockIsVerfyPermisson(bool isVerify); -class AdvancedNotificationServiceTest : public testing::Test { +class ReminderServicePublishTest : public testing::Test { public: static void SetUpTestCase(); static void TearDownTestCase(); @@ -73,23 +61,23 @@ private: void MockSystemApp(); private: - static sptr advancedNotificationService_; + static sptr reminderService_; }; -sptr AdvancedNotificationServiceTest::advancedNotificationService_ = nullptr; +sptr ReminderServicePublishTest::reminderService_ = nullptr; -void AdvancedNotificationServiceTest::SetUpTestCase() +void ReminderServicePublishTest::SetUpTestCase() { MockIsOsAccountExists(true); } -void AdvancedNotificationServiceTest::TearDownTestCase() {} +void ReminderServicePublishTest::TearDownTestCase() {} -void AdvancedNotificationServiceTest::SetUp() +void ReminderServicePublishTest::SetUp() { GTEST_LOG_(INFO) << "SetUp start"; - advancedNotificationService_ = new (std::nothrow) AdvancedNotificationService(); + reminderService_ = new (std::nothrow) ReminderService(); IPCSkeleton::SetCallingTokenID(NATIVE_TOKEN); IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); @@ -97,10 +85,10 @@ void AdvancedNotificationServiceTest::SetUp() GTEST_LOG_(INFO) << "SetUp end"; } -void AdvancedNotificationServiceTest::TearDown() +void ReminderServicePublishTest::TearDown() { IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); - advancedNotificationService_ = nullptr; + reminderService_ = nullptr; GTEST_LOG_(INFO) << "TearDown"; } @@ -110,7 +98,7 @@ inline void SleepForFC() std::this_thread::sleep_for(std::chrono::seconds(1)); } -void AdvancedNotificationServiceTest::MockSystemApp() +void ReminderServicePublishTest::MockSystemApp() { MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); MockIsSystemApp(true); @@ -118,79 +106,80 @@ void AdvancedNotificationServiceTest::MockSystemApp() } /** - * @tc.number : AdvancedNotificationServiceTest_13200 + * @tc.number : ReminderServicePublishTest_13200 * @tc.name : ANS_PublishReminder_0100 * @tc.desc : Test PublishReminder function * @tc.require : issueI5S4VP */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13200, Function | SmallTest | Level1) +HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13200, Function | SmallTest | Level1) { - sptr reminder = nullptr; - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_PARAM); + int32_t reminderId = 0; + ReminderRequest reminder = new ReminderRequest(reminderId); + ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_ANS_INVALID_PARAM); } /** - * @tc.number : AdvancedNotificationServiceTest_13300 + * @tc.number : ReminderServicePublishTest_13300 * @tc.name : ANS_CancelReminder_0100 * @tc.desc : Test CancelReminder function when the result is ERR_NO_INIT * @tc.require : issueI5S4VP */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13300, Function | SmallTest | Level1) +HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13300, Function | SmallTest | Level1) { TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr req = new NotificationRequest(); EXPECT_NE(req, nullptr); int32_t reminderId = 1; - ASSERT_EQ(advancedNotificationService_->CancelReminder(reminderId), (int)ERR_NO_INIT); + ASSERT_EQ(reminderService_->CancelReminder(reminderId), (int)ERR_NO_INIT); } /** - * @tc.number : AdvancedNotificationServiceTest_13400 + * @tc.number : ReminderServicePublishTest_13400 * @tc.name : ANS_CancelAllReminders_0100 * @tc.desc : Test CancelAllReminders function when the result is ERR_NO_INIT * @tc.require : issueI5S4VP */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_13400, Function | SmallTest | Level1) +HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13400, Function | SmallTest | Level1) { TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr req = new NotificationRequest(); EXPECT_NE(req, nullptr); - ASSERT_EQ(advancedNotificationService_->CancelAllReminders(), (int)ERR_NO_INIT); + ASSERT_EQ(reminderService_->CancelAllReminders(), (int)ERR_NO_INIT); } /** - * @tc.number : AdvancedNotificationServiceTest_17900 + * @tc.number : ReminderServicePublishTest_17900 * @tc.name : PublishReminder_1000 * @tc.desc : Test PublishReminder function. * @tc.require : #I61RF2 */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_17900, Function | SmallTest | Level1) +HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_17900, Function | SmallTest | Level1) { GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; int32_t reminderId = 1; - sptr reminder = new ReminderRequest(reminderId); - reminder->InitNotificationRequest(); - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); + ReminderRequest reminder = new ReminderRequest(reminderId); + reminder.InitNotificationRequest(); + ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; } /** - * @tc.number : AdvancedNotificationServiceTest_18000 + * @tc.number : ReminderServicePublishTest_18000 * @tc.name : PublishReminder_2000 * @tc.desc : Test PublishReminder function. * @tc.require : #I61RF2 */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_18000, Function | SmallTest | Level1) +HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_18000, Function | SmallTest | Level1) { GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test start"; MockIsNonBundleName(true); int32_t reminderId = 1; - sptr reminder = new ReminderRequest(reminderId); - reminder->InitNotificationRequest(); - ASSERT_EQ(advancedNotificationService_->PublishReminder(reminder), ERR_ANS_INVALID_BUNDLE); + ReminderRequest reminder = new ReminderRequest(reminderId); + reminder.InitNotificationRequest(); + ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; } diff --git a/services/ans/test/unittest/ans_ut_constant.h b/services/reminder/test/unittest/reminder_ut_constant.h similarity index 100% rename from services/ans/test/unittest/ans_ut_constant.h rename to services/reminder/test/unittest/reminder_ut_constant.h diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 1c3e9f6ca..83a2800e3 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -26,7 +26,6 @@ ohos_moduletest("ans_module_test") { "${services_path}/ans/test/unittest", "${services_path}/ans/test/unittest/mock/include", "${services_path}/test/moduletest/mock/include", - "${ffrt_path}/interfaces/kits", ] sources = [ diff --git a/test/bechmarktest/notification_services_test/BUILD.gn b/test/bechmarktest/notification_services_test/BUILD.gn index 3d7d39163..d19d933ca 100644 --- a/test/bechmarktest/notification_services_test/BUILD.gn +++ b/test/bechmarktest/notification_services_test/BUILD.gn @@ -25,7 +25,6 @@ ohos_benchmarktest("Benchmark_Notification_Servece_Test") { "${access_token_path}/interfaces/innerkits/nativetoken/include", "${access_token_path}/interfaces/innerkits/accesstoken/include", "${services_path}/ans/include", - "${ffrt_path}/interfaces/kits", ] sources = [ diff --git a/test/fuzztest/advancednotificationservice_fuzzer/BUILD.gn b/test/fuzztest/advancednotificationservice_fuzzer/BUILD.gn index c93255c1a..cf431ff4a 100644 --- a/test/fuzztest/advancednotificationservice_fuzzer/BUILD.gn +++ b/test/fuzztest/advancednotificationservice_fuzzer/BUILD.gn @@ -24,7 +24,6 @@ ohos_fuzztest("AdvancedNotificationServiceFuzzTest") { include_dirs = [ "${services_path}/ans/include", "${core_path}/include", - "${ffrt_path}/interfaces/kits", ] cflags = [ diff --git a/test/fuzztest/ansmanagerstub_fuzzer/BUILD.gn b/test/fuzztest/ansmanagerstub_fuzzer/BUILD.gn index dcfbae6c6..3f90b7d79 100644 --- a/test/fuzztest/ansmanagerstub_fuzzer/BUILD.gn +++ b/test/fuzztest/ansmanagerstub_fuzzer/BUILD.gn @@ -24,7 +24,6 @@ ohos_fuzztest("AnsManagerStubFuzzTest") { include_dirs = [ "${services_path}/ans/include", "${core_path}/include", - "${ffrt_path}/interfaces/kits", ] defines = [] cflags = [ diff --git a/test/fuzztest/ansmanagerstubannex_fuzzer/BUILD.gn b/test/fuzztest/ansmanagerstubannex_fuzzer/BUILD.gn index cfbac6226..c755413d7 100644 --- a/test/fuzztest/ansmanagerstubannex_fuzzer/BUILD.gn +++ b/test/fuzztest/ansmanagerstubannex_fuzzer/BUILD.gn @@ -25,7 +25,6 @@ ohos_fuzztest("AnsManagerStubAnnexFuzzTest") { include_dirs = [ "${services_path}/ans/include", "${core_path}/include", - "${ffrt_path}/interfaces/kits", ] cflags = [ -- Gitee From e19517b18c15e75da006817d9c6f43fc25f8c246 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 22 Nov 2024 16:54:40 +0800 Subject: [PATCH 15/29] push Signed-off-by: fengyang --- services/ans/test/unittest/BUILD.gn | 1 + .../test/unittest/ans_ut_constant.h} | 0 services/reminder/BUILD.gn | 13 -- services/reminder/test/unittest/BUILD.gn | 6 +- .../reminder_service_publish_test.cpp | 1 + .../test/unittest/reminder_store_test.cpp | 9 +- test/fuzztest/BUILD.gn | 1 + .../advancednotificationservice_fuzzer.cpp | 14 +- .../ansmanagerstub_fuzzer.cpp | 24 --- .../ansmanagerstubannex_fuzzer.cpp | 24 --- .../ansmanagerstubannexthree_fuzzer.cpp | 24 --- .../reminderdatamanager_fuzzer/BUILD.gn | 6 +- .../reminderdatamanager_fuzzer.cpp | 40 +++-- test/fuzztest/reminderhelper_fuzzer/BUILD.gn | 2 +- .../reminderhelper_fuzzer.cpp | 22 +-- test/fuzztest/reminderrequest_fuzzer/BUILD.gn | 2 +- .../reminderrequestalarm_fuzzer/BUILD.gn | 2 +- .../reminderrequestannex_fuzzer/BUILD.gn | 2 +- .../reminderrequestannexthree_fuzzer/BUILD.gn | 2 +- .../reminderrequestcalendar_fuzzer/BUILD.gn | 2 +- .../reminderrequestcontinuate_fuzzer/BUILD.gn | 2 +- .../reminderrequesttimer_fuzzer/BUILD.gn | 2 +- test/fuzztest/reminderservice_fuzzer/BUILD.gn | 145 ++++++++++++++++++ .../reminderservice_fuzzer/corpus/init | 13 ++ .../reminderservice_fuzzer/project.xml | 25 +++ .../reminderservice_fuzzer.cpp | 67 ++++++++ .../reminderservice_fuzzer.h | 27 ++++ test/fuzztest/reminderstore_fuzzer/BUILD.gn | 6 +- .../reminderstoreannex_fuzzer/BUILD.gn | 6 +- 29 files changed, 326 insertions(+), 164 deletions(-) rename services/{reminder/test/unittest/reminder_ut_constant.h => ans/test/unittest/ans_ut_constant.h} (100%) rename {frameworks => services}/reminder/test/unittest/reminder_store_test.cpp (98%) create mode 100644 test/fuzztest/reminderservice_fuzzer/BUILD.gn create mode 100644 test/fuzztest/reminderservice_fuzzer/corpus/init create mode 100644 test/fuzztest/reminderservice_fuzzer/project.xml create mode 100644 test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.cpp create mode 100644 test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.h diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 67a8e4ea2..9d8b3d288 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -1004,6 +1004,7 @@ ohos_unittest("notification_preferences_database_branch_test") { "c_utils:utils", "common_event_service:cesfwk_innerkits", "eventhandler:libeventhandler", + "ffrt:libffrt", "hilog:libhilog", "hitrace:hitrace_meter", "hitrace:libhitracechain", diff --git a/services/reminder/test/unittest/reminder_ut_constant.h b/services/ans/test/unittest/ans_ut_constant.h similarity index 100% rename from services/reminder/test/unittest/reminder_ut_constant.h rename to services/ans/test/unittest/ans_ut_constant.h diff --git a/services/reminder/BUILD.gn b/services/reminder/BUILD.gn index 7074a6bbb..16a5b0f3e 100644 --- a/services/reminder/BUILD.gn +++ b/services/reminder/BUILD.gn @@ -278,16 +278,3 @@ ohos_shared_library("libreminder") { part_name = "${component_name}" } -ohos_prebuilt_etc("ans.para") { - source = "etc/ans.para" - relative_install_dir = "param" - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} - -ohos_prebuilt_etc("ans.para.dac") { - source = "etc/ans.para.dac" - relative_install_dir = "param" - subsystem_name = "${subsystem_name}" - part_name = "${component_name}" -} diff --git a/services/reminder/test/unittest/BUILD.gn b/services/reminder/test/unittest/BUILD.gn index 2e0afb4db..0e660e47b 100644 --- a/services/reminder/test/unittest/BUILD.gn +++ b/services/reminder/test/unittest/BUILD.gn @@ -40,7 +40,6 @@ ohos_unittest("reminder_unit_test") { "${frameworks_module_ans_path}:ans_innerkits", "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] if (distributed_notification_supported) { @@ -131,7 +130,6 @@ ohos_unittest("reminder_service_publish_test") { deps = [ "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] if (distributed_notification_supported) { @@ -258,7 +256,6 @@ ohos_unittest("reminder_bundle_manager_helper_branch_test") { deps = [ "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -308,7 +305,6 @@ ohos_unittest("reminder_os_account_manager_helper_test") { deps = [ "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] external_deps = [ @@ -366,6 +362,7 @@ ohos_unittest("reminder_service_test") { sources = [ "${test_path}/mock/mock_tokenid_kit.cpp", "reminder_service_test.cpp", + "reminder_store_test.cpp", "mock/mock_access_token_helper.cpp", "mock/mock_accesstoken_kit.cpp", "mock/mock_bundle_manager_helper.cpp", @@ -376,7 +373,6 @@ ohos_unittest("reminder_service_test") { deps = [ "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:libreminder", - "//third_party/googletest:gtest_main", ] if (distributed_notification_supported) { diff --git a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp index 931de2426..04cf5555d 100644 --- a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp @@ -25,6 +25,7 @@ #include #define private public +#define protected public #include "reminder_service.h" #include "ans_const_define.h" diff --git a/frameworks/reminder/test/unittest/reminder_store_test.cpp b/services/reminder/test/unittest/reminder_store_test.cpp similarity index 98% rename from frameworks/reminder/test/unittest/reminder_store_test.cpp rename to services/reminder/test/unittest/reminder_store_test.cpp index d50879009..edcda766a 100644 --- a/frameworks/reminder/test/unittest/reminder_store_test.cpp +++ b/services/reminder/test/unittest/reminder_store_test.cpp @@ -68,11 +68,8 @@ public: NativeRdb::RdbHelper::ClearCache(); NativeRdb::RdbHelper::DeleteRdbStore(ReminderStore::REMINDER_DB_DIR + "notification_test.db"); } - static sptr bundleOption_; }; -sptr ReminderStoreTest::bundleOption_ = - new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID); /** * @tc.name: Init_00001 @@ -153,7 +150,7 @@ HWTEST_F(ReminderStoreTest, Insert_00001, Function | SmallTest | Level1) { sptr reminder = nullptr; ReminderStore reminderStore; - int64_t ret = reminderStore.Insert(reminder, bundleOption_); + int64_t ret = reminderStore.Insert(reminder_); EXPECT_EQ(ret, -1); } @@ -167,7 +164,7 @@ HWTEST_F(ReminderStoreTest, Update_00001, Function | SmallTest | Level1) { sptr reminder = nullptr; ReminderStore reminderStore; - int64_t ret = reminderStore.Update(reminder, bundleOption_); + int64_t ret = reminderStore.Update(reminder); EXPECT_EQ(ret, -1); } @@ -282,7 +279,7 @@ HWTEST_F(ReminderStoreTest, UpdateOrInsert_00001, Function | SmallTest | Level1) { sptr reminder = nullptr; ReminderStore reminderStore; - int64_t ret = reminderStore.UpdateOrInsert(reminder, bundleOption_); + int64_t ret = reminderStore.UpdateOrInsert(reminder); EXPECT_EQ(ret, -1); } diff --git a/test/fuzztest/BUILD.gn b/test/fuzztest/BUILD.gn index 9c4a7e461..41863d197 100644 --- a/test/fuzztest/BUILD.gn +++ b/test/fuzztest/BUILD.gn @@ -82,6 +82,7 @@ group("fuzztest") { "reminderrequestcalendar_fuzzer:ReminderRequestCalendarFuzzTest", "reminderrequestcontinuate_fuzzer:ReminderRequestContinuateFuzzTest", "reminderrequesttimer_fuzzer:ReminderRequestTimerFuzzTest", + "reminderservice_fuzzer:ReminderServiceFuzzTest", "reminderstore_fuzzer:ReminderStoreFuzzTest", "reminderstoreannex_fuzzer:ReminderStoreAnnexFuzzTest", "removenotification_fuzzer:RemoveNotificationFuzzTest", diff --git a/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp b/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp index 33c0ef038..1c8b5bee8 100644 --- a/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp +++ b/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp @@ -126,18 +126,6 @@ namespace OHOS { sptr request = new Notification::NotificationRequest(); service->PublishContinuousTaskNotification(request); service->CancelContinuousTaskNotification(stringData, notificationId); - sptr reminder = new Notification::ReminderRequest(); - service->PublishReminder(reminder); - int32_t reminderId = fuzzData->ConsumeIntegral(); - service->CancelReminder(reminderId); - std::vector> reminders; - service->GetValidReminders(reminders); - service->CancelAllReminders(); - uint64_t excludeDate = fuzzData->ConsumeIntegral(); - service->AddExcludeDate(reminderId, excludeDate); - service->DelExcludeDates(reminderId); - std::vector excludeDates; - service->GetExcludeDates(reminderId, excludeDates); bool support = fuzzData->ConsumeBool(); service->IsSupportTemplate(stringData, support); service->IsSpecialUserAllowedNotify(userId, allowed); @@ -277,7 +265,7 @@ namespace OHOS { service->ChangeNotificationByControlFlags(record, fuzzData->ConsumeBool()); service->CheckPublishPreparedNotification(record, fuzzData->ConsumeBool()); service->UpdateInNotificationList(record); - service->PublishFlowControl(record); + service->PublishInNotificationList(record); service->IsNeedPushCheck(request); return true; } diff --git a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp index 53fd43acf..d2c8fec6a 100644 --- a/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstub_fuzzer/ansmanagerstub_fuzzer.cpp @@ -251,18 +251,6 @@ namespace OHOS { datas.WriteInt32(intData); datas.WriteInt32(intData); ansManagerStub.HandleShellDump(datas, reply); - ansManagerStub.HandlePublishReminder(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleCancelReminder(datas, reply); - ansManagerStub.HandleCancelAllReminders(datas, reply); - ansManagerStub.HandleGetValidReminders(datas, reply); - datas.WriteInt32(intData); - datas.WriteUint64(intData); - ansManagerStub.HandleAddExcludeDate(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleDelExcludeDates(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleGetExcludeDates(datas, reply); datas.WriteString(stringData); ansManagerStub.HandleIsSupportTemplate(datas, reply); datas.WriteInt32(intData); @@ -396,18 +384,6 @@ namespace OHOS { sptr request = new Notification::NotificationRequest(); ansManagerStub.PublishContinuousTaskNotification(request); ansManagerStub.CancelContinuousTaskNotification(stringData, notificationId); - sptr reminder = new Notification::ReminderRequest(); - ansManagerStub.PublishReminder(reminder); - int32_t reminderId = fuzzData->ConsumeIntegral(); - ansManagerStub.CancelReminder(reminderId); - std::vector> reminders; - ansManagerStub.GetValidReminders(reminders); - ansManagerStub.CancelAllReminders(); - uint64_t excludeDate = fuzzData->ConsumeIntegral(); - ansManagerStub.AddExcludeDate(reminderId, excludeDate); - ansManagerStub.DelExcludeDates(reminderId); - std::vector excludeDates; - ansManagerStub.GetExcludeDates(reminderId, excludeDates); bool support = fuzzData->ConsumeBool(); ansManagerStub.IsSupportTemplate(stringData, support); ansManagerStub.IsSpecialUserAllowedNotify(userId, allowed); diff --git a/test/fuzztest/ansmanagerstubannex_fuzzer/ansmanagerstubannex_fuzzer.cpp b/test/fuzztest/ansmanagerstubannex_fuzzer/ansmanagerstubannex_fuzzer.cpp index eac344776..60d5c977c 100644 --- a/test/fuzztest/ansmanagerstubannex_fuzzer/ansmanagerstubannex_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstubannex_fuzzer/ansmanagerstubannex_fuzzer.cpp @@ -250,18 +250,6 @@ namespace OHOS { datas.WriteInt32(intData); datas.WriteInt32(intData); ansManagerStub.HandleShellDump(datas, reply); - ansManagerStub.HandlePublishReminder(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleCancelReminder(datas, reply); - ansManagerStub.HandleCancelAllReminders(datas, reply); - ansManagerStub.HandleGetValidReminders(datas, reply); - datas.WriteInt32(intData); - datas.WriteUint64(intData); - ansManagerStub.HandleAddExcludeDate(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleDelExcludeDates(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleGetExcludeDates(datas, reply); datas.WriteString(stringData); ansManagerStub.HandleIsSupportTemplate(datas, reply); datas.WriteInt32(intData); @@ -395,18 +383,6 @@ namespace OHOS { sptr request = new Notification::NotificationRequest(); ansManagerStub.PublishContinuousTaskNotification(request); ansManagerStub.CancelContinuousTaskNotification(stringData, notificationId); - sptr reminder = new Notification::ReminderRequest(); - ansManagerStub.PublishReminder(reminder); - int32_t reminderId = fuzzData->ConsumeIntegral(); - ansManagerStub.CancelReminder(reminderId); - std::vector> reminders; - ansManagerStub.GetValidReminders(reminders); - ansManagerStub.CancelAllReminders(); - uint64_t excludeDate = fuzzData->ConsumeIntegral(); - ansManagerStub.AddExcludeDate(reminderId, excludeDate); - ansManagerStub.DelExcludeDates(reminderId); - std::vector excludeDates; - ansManagerStub.GetExcludeDates(reminderId, excludeDates); bool support = fuzzData->ConsumeBool(); ansManagerStub.IsSupportTemplate(stringData, support); ansManagerStub.IsSpecialUserAllowedNotify(userId, allowed); diff --git a/test/fuzztest/ansmanagerstubannexthree_fuzzer/ansmanagerstubannexthree_fuzzer.cpp b/test/fuzztest/ansmanagerstubannexthree_fuzzer/ansmanagerstubannexthree_fuzzer.cpp index ebac94b90..3b5c56152 100644 --- a/test/fuzztest/ansmanagerstubannexthree_fuzzer/ansmanagerstubannexthree_fuzzer.cpp +++ b/test/fuzztest/ansmanagerstubannexthree_fuzzer/ansmanagerstubannexthree_fuzzer.cpp @@ -242,18 +242,6 @@ namespace OHOS { datas.WriteInt32(intData); datas.WriteInt32(intData); ansManagerStub.HandleShellDump(datas, reply); - ansManagerStub.HandlePublishReminder(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleCancelReminder(datas, reply); - ansManagerStub.HandleCancelAllReminders(datas, reply); - ansManagerStub.HandleGetValidReminders(datas, reply); - datas.WriteInt32(intData); - datas.WriteUint64(intData); - ansManagerStub.HandleAddExcludeDate(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleDelExcludeDates(datas, reply); - datas.WriteInt32(intData); - ansManagerStub.HandleGetExcludeDates(datas, reply); datas.WriteString(stringData); ansManagerStub.HandleIsSupportTemplate(datas, reply); datas.WriteInt32(intData); @@ -387,18 +375,6 @@ namespace OHOS { sptr request = new Notification::NotificationRequest(); ansManagerStub.PublishContinuousTaskNotification(request); ansManagerStub.CancelContinuousTaskNotification(stringData, notificationId); - sptr reminder = new Notification::ReminderRequest(); - ansManagerStub.PublishReminder(reminder); - int32_t reminderId = fuzzData->ConsumeIntegral(); - ansManagerStub.CancelReminder(reminderId); - std::vector> reminders; - ansManagerStub.GetValidReminders(reminders); - ansManagerStub.CancelAllReminders(); - uint64_t excludeDate = fuzzData->ConsumeIntegral(); - ansManagerStub.AddExcludeDate(reminderId, excludeDate); - ansManagerStub.DelExcludeDates(reminderId); - std::vector excludeDates; - ansManagerStub.GetExcludeDates(reminderId, excludeDates); bool support = fuzzData->ConsumeBool(); ansManagerStub.IsSupportTemplate(stringData, support); ansManagerStub.IsSpecialUserAllowedNotify(userId, allowed); diff --git a/test/fuzztest/reminderdatamanager_fuzzer/BUILD.gn b/test/fuzztest/reminderdatamanager_fuzzer/BUILD.gn index 29f362f31..44df209c6 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderdatamanager_fuzzer/BUILD.gn @@ -24,7 +24,7 @@ ohos_fuzztest("ReminderDataManagerFuzzTest") { include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base", - "${component_path}/services/ans/include", + "${component_path}/services/reminder/include", ] cflags = [ "-g", @@ -38,8 +38,8 @@ ohos_fuzztest("ReminderDataManagerFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", ] external_deps = [ diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index e157d2a88..ea7c1dacb 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -21,34 +21,32 @@ namespace OHOS { bool DoSomethingInterestingWithManager(FuzzedDataProvider* fdp) { - std::string bundleName = fdp->ConsumeRandomLengthString(); int32_t userId = fdp->ConsumeIntegral(); int32_t uid = fdp->ConsumeIntegral(); int32_t reminderId = fdp->ConsumeIntegral(); uint64_t date = fdp->ConsumeIntegral(); bool value = fdp->ConsumeBool(); uint8_t type = fdp->ConsumeIntegral(); + int32_t callingUid = fdp->ConsumeIntegral(); EventFwk::Want want; constexpr uint64_t seconds = 1200; sptr reminder = new Notification::ReminderRequestTimer(seconds); - Notification::ReminderDataManager::InitInstance(nullptr); + Notification::ReminderDataManager::InitInstance(); auto manager = Notification::ReminderDataManager::GetInstance(); manager->Init(false); manager->Dump(); - manager->CancelAllReminders(bundleName, userId, uid); - sptr option = new Notification::NotificationBundleOption( - bundleName, uid); - manager->CancelReminder(reminderId, option); - manager->CheckExcludeDateParam(reminderId, option); - manager->AddExcludeDate(reminderId, date, option); - manager->DelExcludeDates(reminderId, option); + manager->CancelAllReminders(userId, uid); + manager->CancelReminder(reminderId, callingUid); + manager->CheckExcludeDateParam(reminderId, callingUid); + manager->AddExcludeDate(reminderId, date, callingUid); + manager->DelExcludeDates(reminderId, callingUid); - std::vector dates; - manager->GetExcludeDates(reminderId, option, dates); + std::vector dates; + manager->GetExcludeDates(reminderId, callingUid, dates); manager->CloseReminder(want, value); - std::vector> reminders; - manager->GetValidReminders(option, reminders); + std::vector reminders; + manager->GetValidReminders(callingUid, reminders); manager->Init(value); manager->InitUserId(); std::vector> immediatelyReminders; @@ -60,7 +58,7 @@ namespace OHOS { manager->OnBundleMgrServiceStart(); manager->OnAbilityMgrServiceStart(); manager->OnUserSwitch(userId); - manager->OnProcessDiedLocked(option); + manager->OnProcessDiedLocked(callingUid); manager->RefreshRemindersDueToSysTimeChange(type); manager->ShouldAlert(reminder); manager->ShowActiveReminder(want); @@ -79,22 +77,21 @@ namespace OHOS { int32_t uid = fdp->ConsumeIntegral(); int32_t reminderId = fdp->ConsumeIntegral(); bool value = fdp->ConsumeBool(); + int32_t callingUid = fdp->ConsumeIntegral(); constexpr uint64_t seconds = 1200; sptr reminder = new Notification::ReminderRequestTimer(seconds); auto manager = Notification::ReminderDataManager::GetInstance(); - sptr option = new Notification::NotificationBundleOption( - bundleName, uid); manager->OnLanguageChanged(); manager->OnRemoveAppMgr(); manager->CancelAllReminders(userId); manager->CheckUpdateConditions(reminder, Notification::ReminderRequest::ActionButtonType::INVALID, reminder->GetActionButtons()); manager->GetCustomRingUri(reminder); - manager->CancelRemindersImplLocked(bundleName, userId, uid); + manager->CancelRemindersImplLocked(userId, uid, value); manager->CloseRemindersByGroupId(reminderId, bundleName, bundleName); manager->CancelNotification(reminder); - manager->CheckReminderLimitExceededLocked(option, reminder); + manager->CheckReminderLimitExceededLocked(callingUid, reminder); std::vector> reminders; manager->GetImmediatelyShowRemindersLocked(reminders); manager->GetSoundUri(reminder); @@ -113,15 +110,14 @@ namespace OHOS { std::vector> extensionReminders; std::vector> immediatelyReminders; - manager->PublishReminder(reminder, option); + manager->PublishReminder(reminder, callingUid); manager->FindReminderRequestLocked(reminderId); - manager->FindReminderRequestLocked(reminderId, bundleName); manager->GetRecentReminderLocked(); manager->HandleImmediatelyShow(immediatelyReminders, value); manager->HandleExtensionReminder(extensionReminders); manager->HandleSameNotificationIdShowing(reminder); - manager->IsBelongToSameApp(option, option); - manager->CheckIsSameApp(reminder, option); + manager->IsBelongToSameApp(uid, uid); + manager->CheckIsSameApp(reminder, uid); manager->ShowReminder(reminder, value, value, value, value); return true; } diff --git a/test/fuzztest/reminderhelper_fuzzer/BUILD.gn b/test/fuzztest/reminderhelper_fuzzer/BUILD.gn index 106b694e8..88159ad75 100644 --- a/test/fuzztest/reminderhelper_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderhelper_fuzzer/BUILD.gn @@ -32,7 +32,7 @@ ohos_fuzztest("ReminderHelperFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderhelper_fuzzer/reminderhelper_fuzzer.cpp b/test/fuzztest/reminderhelper_fuzzer/reminderhelper_fuzzer.cpp index c45972467..557bc304d 100644 --- a/test/fuzztest/reminderhelper_fuzzer/reminderhelper_fuzzer.cpp +++ b/test/fuzztest/reminderhelper_fuzzer/reminderhelper_fuzzer.cpp @@ -22,34 +22,24 @@ #include namespace OHOS { - namespace { - constexpr uint8_t SLOT_TYPE_NUM = 5; - } bool DoSomethingInterestingWithMyAPI(FuzzedDataProvider* fdp) { std::string stringData = fdp->ConsumeRandomLengthString(); Notification::ReminderRequest reminder; reminder.SetContent(stringData); reminder.SetExpiredContent(stringData); - Notification::ReminderHelper::PublishReminder(reminder); + int32_t reminderId2 = 0; + Notification::ReminderHelper::PublishReminder(reminder, reminderId2); int32_t reminderId = fdp->ConsumeIntegral(); Notification::ReminderHelper::CancelReminder(reminderId); - sptr valid = new Notification::ReminderRequest(); - std::vector> validReminders; + Notification::ReminderRequest valid; + std::vector validReminders; validReminders.emplace_back(valid); Notification::ReminderHelper::GetValidReminders(validReminders); - Notification::NotificationSlot notificationSlot; - bool enabled = fdp->ConsumeBool(); - notificationSlot.SetEnableLight(enabled); - notificationSlot.SetEnableVibration(enabled); - Notification::ReminderHelper::AddNotificationSlot(notificationSlot); - uint8_t type = fdp->ConsumeIntegral() % SLOT_TYPE_NUM; - Notification::NotificationConstant::SlotType slotType = Notification::NotificationConstant::SlotType(type); - Notification::ReminderHelper::RemoveNotificationSlot(slotType); - uint64_t excludeDate = static_cast(reminderId); + uint64_t excludeDate = static_cast(reminderId); Notification::ReminderHelper::AddExcludeDate(reminderId, excludeDate); Notification::ReminderHelper::DelExcludeDates(reminderId); - std::vector dates; + std::vector dates; Notification::ReminderHelper::GetExcludeDates(reminderId, dates); return Notification::ReminderHelper::CancelAllReminders(); } diff --git a/test/fuzztest/reminderrequest_fuzzer/BUILD.gn b/test/fuzztest/reminderrequest_fuzzer/BUILD.gn index 3bc258ff0..e467478ea 100644 --- a/test/fuzztest/reminderrequest_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequest_fuzzer/BUILD.gn @@ -32,7 +32,7 @@ ohos_fuzztest("ReminderRequestFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequestalarm_fuzzer/BUILD.gn b/test/fuzztest/reminderrequestalarm_fuzzer/BUILD.gn index bb166c3a8..1a1d90e9a 100644 --- a/test/fuzztest/reminderrequestalarm_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequestalarm_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestAlarmFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequestannex_fuzzer/BUILD.gn b/test/fuzztest/reminderrequestannex_fuzzer/BUILD.gn index bb4b6750f..ef0d6d50e 100644 --- a/test/fuzztest/reminderrequestannex_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequestannex_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestAnnexFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequestannexthree_fuzzer/BUILD.gn b/test/fuzztest/reminderrequestannexthree_fuzzer/BUILD.gn index 5c19e4084..41b58748c 100644 --- a/test/fuzztest/reminderrequestannexthree_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequestannexthree_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestAnnexThreeFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequestcalendar_fuzzer/BUILD.gn b/test/fuzztest/reminderrequestcalendar_fuzzer/BUILD.gn index befcba816..fec148d00 100644 --- a/test/fuzztest/reminderrequestcalendar_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequestcalendar_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestCalendarFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequestcontinuate_fuzzer/BUILD.gn b/test/fuzztest/reminderrequestcontinuate_fuzzer/BUILD.gn index cc3ee4043..b9d0ef779 100644 --- a/test/fuzztest/reminderrequestcontinuate_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequestcontinuate_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestContinuateFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderrequesttimer_fuzzer/BUILD.gn b/test/fuzztest/reminderrequesttimer_fuzzer/BUILD.gn index df1be7306..6fb5013e6 100644 --- a/test/fuzztest/reminderrequesttimer_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderrequesttimer_fuzzer/BUILD.gn @@ -33,7 +33,7 @@ ohos_fuzztest("ReminderRequestTimerFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", + "${frameworks_module_reminder_path}:reminder_innerkits", ] external_deps = [ diff --git a/test/fuzztest/reminderservice_fuzzer/BUILD.gn b/test/fuzztest/reminderservice_fuzzer/BUILD.gn new file mode 100644 index 000000000..4cef50cd2 --- /dev/null +++ b/test/fuzztest/reminderservice_fuzzer/BUILD.gn @@ -0,0 +1,145 @@ +# Copyright (c) 2023 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. + +#####################hydra-fuzz################### +import("//base/notification/distributed_notification_service/notification.gni") +import("//build/config/features.gni") +import("//build/test.gni") + +##############################fuzztest########################################## +ohos_fuzztest("ReminderServiceFuzzTest") { + module_out_path = service_fuzz_test_path + fuzz_config_file = + "${component_path}/test/fuzztest/reminderservice_fuzzer" + include_dirs = [ + "${services_path}/reminder/include", + "${core_path}/include", + ] + + cflags = [ + "-g", + "-O0", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + sources = [ "reminderservice_fuzzer.cpp" ] + defines = [] + deps = [ + "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:reminder_service_sources", + "//third_party/icu/icu4c:shared_icuuc", + "//third_party/libxml2:libxml2", + ] + + if (is_double_framework) { + cflags += [ "-DCONFIG_DUAL_FRAMEWORK" ] + } + + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + if (notification_smart_reminder_supported) { + defines += [ "NOTIFICATION_SMART_REMINDER_SUPPORTED" ] + } + + external_deps = [ + "ability_base:configuration", + "ability_runtime:ability_manager", + "ability_runtime:app_manager", + "ability_runtime:appkit_native", + "ability_runtime:dataobs_manager", + "ability_runtime:extension_manager", + "ability_runtime:wantagent_innerkits", + "access_token:libaccesstoken_sdk", + "access_token:libtokenid_sdk", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "c_utils:utils", + "common_event_service:cesfwk_innerkits", + "config_policy:configpolicy_util", + "data_share:datashare_common", + "data_share:datashare_consumer", + "data_share:datashare_permission", + "device_manager:devicemanagersdk", + "ffrt:libffrt", + "hilog:libhilog", + "i18n:intl_util", + "image_framework:image_native", + "init:libbegetutil", + "kv_store:distributeddata_inner", + "openssl:libcrypto_shared", + "os_account:os_account_innerkits", + "relational_store:native_rdb", + "resource_management:global_resmgr", + "time_service:time_client", + ] + external_deps += component_external_deps + + if (device_usage) { + external_deps += [ "device_usage_statistics:usagestatsinner" ] + defines += [ "DEVICE_USAGE_STATISTICS_ENABLE" ] + } + + if (hisysevent_usage) { + cflags += [ "-DHAS_HISYSEVENT_PART" ] + external_deps += [ "hisysevent:libhisysevent" ] + } + + if (standby_enable) { + external_deps += [ "device_standby:standby_innerkits" ] + defines += [ "DEVICE_STANDBY_ENABLE" ] + } + + if (player_framework) { + external_deps += [ "player_framework:media_client" ] + defines += [ "PLAYER_FRAMEWORK_ENABLE" ] + } + + if (ans_hitrace_usage) { + external_deps += [ "hitrace:hitrace_meter" ] + defines += [ "HITRACE_METER_ENABLE" ] + } + + if (ans_config_policy_enable) { + external_deps += [ "config_policy:configpolicy_util" ] + defines += [ "CONFIG_POLICY_ENABLE" ] + } + + if (screenlock_mgr_enable) { + external_deps += [ "screenlock_mgr:screenlock_client" ] + defines += [ "SCREENLOCK_MGR_ENABLE" ] + } + + if (distributed_notification_service_feature_summary) { + defines += [ "ENABLE_ANS_EXT_WRAPPER" ] + } + + if (telephony_cust) { + defines += [ "ENABLE_ANS_TELEPHONY_CUST_WRAPPER" ] + } + + if (distributed_notification_service_feature_disable_fa_model) { + defines += [ "ANS_DISABLE_FA_MODEL" ] + } +} + +############################################################################### +group("fuzztest") { + testonly = true + deps = [ ":ReminderServiceFuzzTest" ] +} +############################################################################### diff --git a/test/fuzztest/reminderservice_fuzzer/corpus/init b/test/fuzztest/reminderservice_fuzzer/corpus/init new file mode 100644 index 000000000..d6a927d54 --- /dev/null +++ b/test/fuzztest/reminderservice_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# Copyright (c) 2023 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. +100 \ No newline at end of file diff --git a/test/fuzztest/reminderservice_fuzzer/project.xml b/test/fuzztest/reminderservice_fuzzer/project.xml new file mode 100644 index 000000000..4fdbc407f --- /dev/null +++ b/test/fuzztest/reminderservice_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + diff --git a/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.cpp b/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.cpp new file mode 100644 index 000000000..39c92f136 --- /dev/null +++ b/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.cpp @@ -0,0 +1,67 @@ +/* + * Copyright (c) 2023 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include +#define private public +#define protected public +#include "reminder_service.h" +#undef private +#undef protected +#include "reminderservice_fuzzer.h" +#include "ans_permission_def.h" + +constexpr uint8_t SLOT_TYPE_NUM = 5; + +namespace OHOS { + + bool DoSomethingInterestingWithMyAPI(FuzzedDataProvider *fuzzData) + { + auto service = std::make_shared(); + std::string stringData = fuzzData->ConsumeRandomLengthString(); + int32_t userId = fuzzData->ConsumeIntegral(); + Notification::ReminderRequest reminder; + int32_t reminderId2 = 0; + service->PublishReminder(reminder, reminderId2); + int32_t reminderId = fuzzData->ConsumeIntegral(); + service->CancelReminder(reminderId); + std::vector reminders; + service->GetValidReminders(reminders); + service->CancelAllReminders(); + int64_t excludeDate = fuzzData->ConsumeIntegral(); + service->AddExcludeDate(reminderId, excludeDate); + service->DelExcludeDates(reminderId); + std::vector excludeDates; + service->GetExcludeDates(reminderId, excludeDates); + return true; + } +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + FuzzedDataProvider fdp(data, size); + std::vector requestPermission = { + OHOS::Notification::OHOS_PERMISSION_NOTIFICATION_CONTROLLER, + OHOS::Notification::OHOS_PERMISSION_NOTIFICATION_AGENT_CONTROLLER, + OHOS::Notification::OHOS_PERMISSION_SET_UNREMOVABLE_NOTIFICATION + }; + SystemHapTokenGet(requestPermission); + OHOS::DoSomethingInterestingWithMyAPI(&fdp); + return 0; +} diff --git a/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.h b/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.h new file mode 100644 index 000000000..350a6904c --- /dev/null +++ b/test/fuzztest/reminderservice_fuzzer/reminderservice_fuzzer.h @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2023 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 TEST_FUZZTEST_ADVANCEDNOTIFICATIONSERVICE_FUZZER_REMINDERSERVICE_FUZZER_H +#define TEST_FUZZTEST_ADVANCEDNOTIFICATIONSERVICE_FUZZER_REMINDERSERVICE_FUZZER_H + +#include "fuzz_common_base.h" +#include + +#define FUZZ_PROJECT_NAME "reminderservice_fuzzer" + +namespace OHOS { +} + +#endif // TEST_FUZZTEST_ADVANCEDNOTIFICATIONSERVICE_FUZZER_REMINDERSERVICE_FUZZER_H \ No newline at end of file diff --git a/test/fuzztest/reminderstore_fuzzer/BUILD.gn b/test/fuzztest/reminderstore_fuzzer/BUILD.gn index 28132be53..4e256fc3c 100644 --- a/test/fuzztest/reminderstore_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstore_fuzzer/BUILD.gn @@ -23,7 +23,7 @@ ohos_fuzztest("ReminderStoreFuzzTest") { include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base", - "${component_path}/services/ans/include", + "${component_path}/services/reminder/include", ] cflags = [ "-g", @@ -35,8 +35,8 @@ ohos_fuzztest("ReminderStoreFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", ] external_deps = [ diff --git a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn index 74b52ec22..45dce5041 100644 --- a/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderstoreannex_fuzzer/BUILD.gn @@ -23,7 +23,7 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { include_dirs = [ "${component_path}/test/fuzztest/fuzz_common_base", - "${component_path}/services/ans/include", + "${component_path}/services/reminder/include", ] cflags = [ "-g", @@ -35,8 +35,8 @@ ohos_fuzztest("ReminderStoreAnnexFuzzTest") { deps = [ "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", - "${frameworks_module_ans_path}:ans_innerkits", - "${services_path}/ans:libans", + "${frameworks_module_reminder_path}:reminder_innerkits", + "${services_path}/reminder:libreminder", ] external_deps = [ -- Gitee From e64c3e24eccd0116f2b7509750d9c332bd682aee Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 25 Nov 2024 14:49:53 +0800 Subject: [PATCH 16/29] push Signed-off-by: fengyang --- frameworks/reminder/test/unittest/BUILD.gn | 11 +-- services/reminder/BUILD.gn | 1 + services/reminder/libreminder.map | 38 ++++++++ services/reminder/test/unittest/BUILD.gn | 2 + .../mock/mock_os_account_manager_annex.cpp | 97 +++++++++++++++++++ .../test/unittest/reminder_service_test.cpp | 11 ++- .../reminder_service_publish_test.cpp | 12 +-- .../test/unittest/reminder_store_test.cpp | 21 ++-- .../test/unittest/reminder_ut_constant.h | 34 +++++++ .../advancednotificationservice_fuzzer.cpp | 2 +- test/fuzztest/reminderservice_fuzzer/BUILD.gn | 4 +- 11 files changed, 197 insertions(+), 36 deletions(-) create mode 100644 services/reminder/libreminder.map create mode 100644 services/reminder/test/unittest/mock/mock_os_account_manager_annex.cpp create mode 100644 services/reminder/test/unittest/reminder_ut_constant.h diff --git a/frameworks/reminder/test/unittest/BUILD.gn b/frameworks/reminder/test/unittest/BUILD.gn index ed116e6d8..e669f2a86 100644 --- a/frameworks/reminder/test/unittest/BUILD.gn +++ b/frameworks/reminder/test/unittest/BUILD.gn @@ -33,7 +33,6 @@ ohos_unittest("reminder_test") { "${frameworks_module_reminder_path}/test/unittest/reminder_request_alarm_test.cpp", "${frameworks_module_reminder_path}/test/unittest/reminder_request_calendar_test.cpp", "${frameworks_module_reminder_path}/test/unittest/reminder_request_timer_test.cpp", - "${frameworks_module_reminder_path}/test/unittest/reminder_store_test.cpp", ] deps = [ @@ -90,7 +89,7 @@ ohos_unittest("reminder_request_test") { "include", "/${services_path}/ans/include", "/${services_path}/reminder/include", - "${services_path}/ans/test/unittest/mock/include", + "${services_path}/reminder/test/unittest/mock/include", ] sources = [ @@ -121,13 +120,13 @@ ohos_unittest("reminder_request_branch_test") { include_dirs = [ ".", "include", - "/${services_path}/ans/include", - "${services_path}/ans/test/unittest/mock/include", + "/${services_path}/reminder/include", + "${services_path}/reminder/test/unittest/mock/include", ] sources = [ - "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", - "${frameworks_module_ans_path}/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_branch_test/mock_reminder_request.cpp", + "${frameworks_module_reminder_path}/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp", ] deps = [ diff --git a/services/reminder/BUILD.gn b/services/reminder/BUILD.gn index 16a5b0f3e..f4d1518a5 100644 --- a/services/reminder/BUILD.gn +++ b/services/reminder/BUILD.gn @@ -185,6 +185,7 @@ ohos_shared_library("libreminder") { branch_protector_ret = "pac_ret" shlib_type = "sa" + version_script = "libreminder.map" cflags = [ "-fno-math-errno", "-fno-unroll-loops", diff --git a/services/reminder/libreminder.map b/services/reminder/libreminder.map new file mode 100644 index 000000000..d9c548487 --- /dev/null +++ b/services/reminder/libreminder.map @@ -0,0 +1,38 @@ +# Copyright (c) 2023 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. + +1.0 { + global: + *BundleInfo*; + *BundleManagerHelper*; + *Connect*; + *Delete*; + *Disconnect*; + *GetBundle*; + *GetDefaultUidByBundleName*; + *GetDoNotDisturb*; + *GetInstance*; + *Init*; + *IsAllowedNotify*; + *IsSystemApp*; + *Notification*; + *Notify*; + *OnRemoteDied*; + *Publish*; + *Put*; + *Query*; + *Remove*; + *Subscribe*; + local: + *; +}; diff --git a/services/reminder/test/unittest/BUILD.gn b/services/reminder/test/unittest/BUILD.gn index 0e660e47b..f9aafd57c 100644 --- a/services/reminder/test/unittest/BUILD.gn +++ b/services/reminder/test/unittest/BUILD.gn @@ -125,6 +125,7 @@ ohos_unittest("reminder_service_publish_test") { "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr.cpp", "mock/mock_ipc.cpp", + "mock/mock_os_account_manager_annex.cpp", ] deps = [ @@ -368,6 +369,7 @@ ohos_unittest("reminder_service_test") { "mock/mock_bundle_manager_helper.cpp", "mock/mock_bundle_mgr.cpp", "mock/mock_ipc.cpp", + "mock/mock_os_account_manager_annex.cpp", ] deps = [ diff --git a/services/reminder/test/unittest/mock/mock_os_account_manager_annex.cpp b/services/reminder/test/unittest/mock/mock_os_account_manager_annex.cpp new file mode 100644 index 000000000..8be5780b3 --- /dev/null +++ b/services/reminder/test/unittest/mock/mock_os_account_manager_annex.cpp @@ -0,0 +1,97 @@ +/* + * Copyright (c) 2023 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 "os_account_manager.h" + +namespace { +int32_t g_mockId = 100; // default id when there is no os_account part +bool g_mockQueryForgroundOsAccountRet = true; +bool g_mockGetOsAccountLocalIdFromUidRet = true; +int32_t g_mockIdForGetOsAccountLocalIdFromUid = 100; +bool g_mockOsAccountExists = true; +} + +void MockQueryForgroundOsAccountId(bool mockRet, uint8_t mockCase) +{ + g_mockQueryForgroundOsAccountRet = mockRet; + switch (mockCase) { + case 1: { + g_mockId = 101; // 101 mockcase1 + break; + } + default: { + g_mockId = 100; // 100 mockdefault + break; + } + } +} + +void MockIsOsAccountExists(bool mockRet) +{ + g_mockOsAccountExists = mockRet; +} + +void ResetAccountMock() +{ + g_mockId = 100; // 100 mockId + g_mockQueryForgroundOsAccountRet = true; + g_mockGetOsAccountLocalIdFromUidRet = true; + g_mockIdForGetOsAccountLocalIdFromUid = 100; + g_mockOsAccountExists = true; +} + +void MockGetOsAccountLocalIdFromUid(bool mockRet, uint8_t mockCase = 0) +{ + g_mockGetOsAccountLocalIdFromUidRet = mockRet; + switch (mockCase) { + case 1: { // mock for invalid id + g_mockIdForGetOsAccountLocalIdFromUid = -2; // -2 mock for invalid id + break; + } + case 2: { // mock for system id + g_mockIdForGetOsAccountLocalIdFromUid = 88; // 88 mock for system id + break; + } + default: { + g_mockIdForGetOsAccountLocalIdFromUid = 100; // 100 mock for system id + break; + } + } +} + +namespace OHOS { +namespace AccountSA { +ErrCode OsAccountManager::GetForegroundOsAccountLocalId(int32_t &id) +{ + if (!g_mockQueryForgroundOsAccountRet) { + return ERR_INVALID_OPERATION; + } + id = g_mockId; + return ERR_OK; +} + +ErrCode OsAccountManager::GetOsAccountLocalIdFromUid(const int32_t uid, int32_t &id) +{ + id = g_mockIdForGetOsAccountLocalIdFromUid; + return g_mockGetOsAccountLocalIdFromUidRet ? ERR_OK : ERR_INVALID_OPERATION; +} + +ErrCode OsAccountManager::IsOsAccountExists(const int id, bool &isOsAccountExists) +{ + isOsAccountExists = g_mockOsAccountExists; + return ERR_OK; +} +} // namespace EventFwk +} // namespace OHOS \ No newline at end of file diff --git a/services/reminder/test/unittest/reminder_service_test.cpp b/services/reminder/test/unittest/reminder_service_test.cpp index 2e1c72b73..88a68eb9e 100644 --- a/services/reminder/test/unittest/reminder_service_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test.cpp @@ -53,7 +53,6 @@ public: void TearDown(); private: - void TestAddSlot(NotificationConstant::SlotType type); void TestAddLiveViewSlot(bool isForceControl); void MockSystemApp(); @@ -89,6 +88,13 @@ void ReminderServiceTest::TearDown() GTEST_LOG_(INFO) << "TearDown"; } +void ReminderServiceTest::MockSystemApp() +{ + MockGetTokenTypeFlag(Security::AccessToken::ATokenTypeEnum::TOKEN_HAP); + MockIsSystemApp(true); + MockIsVerfyPermisson(true); +} + inline void SleepForFC() { // For Reminder Flow Control @@ -143,7 +149,6 @@ HWTEST_F(ReminderServiceTest, AddExcludeDate_00001, Function | SmallTest | Level uint64_t time = 124325; MockIsVerfyPermisson(false); ASSERT_EQ(ReminderService_->AddExcludeDate(reminderId, time), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); ASSERT_EQ(ReminderService_->AddExcludeDate(reminderId, time), (int)ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); @@ -162,7 +167,6 @@ HWTEST_F(ReminderServiceTest, DelExcludeDates_00002, Function | SmallTest | Leve int32_t reminderId = 10; MockIsVerfyPermisson(false); ASSERT_EQ(ReminderService_->DelExcludeDates(reminderId), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); ASSERT_EQ(ReminderService_->DelExcludeDates(reminderId), (int)ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); @@ -182,7 +186,6 @@ HWTEST_F(ReminderServiceTest, GetExcludeDates_00001, Function | SmallTest | Leve std::vector times; MockIsVerfyPermisson(false); ASSERT_EQ(ReminderService_->GetExcludeDates(reminderId, times), (int)ERR_REMINDER_PERMISSION_DENIED); - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); MockIsNonBundleName(true); ASSERT_EQ(ReminderService_->GetExcludeDates(reminderId, times), (int)ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); diff --git a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp index 04cf5555d..bfbb20638 100644 --- a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp @@ -115,7 +115,7 @@ void ReminderServicePublishTest::MockSystemApp() HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13200, Function | SmallTest | Level1) { int32_t reminderId = 0; - ReminderRequest reminder = new ReminderRequest(reminderId); + ReminderRequest reminder; ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_ANS_INVALID_PARAM); } @@ -127,9 +127,6 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13200, Function */ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13300, Function | SmallTest | Level1) { - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); int32_t reminderId = 1; ASSERT_EQ(reminderService_->CancelReminder(reminderId), (int)ERR_NO_INIT); } @@ -142,9 +139,6 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13300, Function */ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_13400, Function | SmallTest | Level1) { - TestAddSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - sptr req = new NotificationRequest(); - EXPECT_NE(req, nullptr); ASSERT_EQ(reminderService_->CancelAllReminders(), (int)ERR_NO_INIT); } @@ -159,7 +153,7 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_17900, Function GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test start"; int32_t reminderId = 1; - ReminderRequest reminder = new ReminderRequest(reminderId); + ReminderRequest reminder; reminder.InitNotificationRequest(); ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); @@ -178,7 +172,7 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_18000, Function MockIsNonBundleName(true); int32_t reminderId = 1; - ReminderRequest reminder = new ReminderRequest(reminderId); + ReminderRequest reminder; reminder.InitNotificationRequest(); ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); diff --git a/services/reminder/test/unittest/reminder_store_test.cpp b/services/reminder/test/unittest/reminder_store_test.cpp index edcda766a..12e7dd96a 100644 --- a/services/reminder/test/unittest/reminder_store_test.cpp +++ b/services/reminder/test/unittest/reminder_store_test.cpp @@ -26,7 +26,6 @@ #undef private #undef protected #include "reminder_helper.h" -#include "notification_preferences.h" using namespace testing::ext; namespace OHOS { @@ -150,7 +149,7 @@ HWTEST_F(ReminderStoreTest, Insert_00001, Function | SmallTest | Level1) { sptr reminder = nullptr; ReminderStore reminderStore; - int64_t ret = reminderStore.Insert(reminder_); + int64_t ret = reminderStore.Insert(reminder); EXPECT_EQ(ret, -1); } @@ -348,8 +347,7 @@ HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00001, Function | SmallTes ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); timer->countDownTimeInSeconds_ = 10001; - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { @@ -409,8 +407,7 @@ HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00002, Function | SmallTes ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); timer->countDownTimeInSeconds_ = 10001; - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { @@ -464,8 +461,7 @@ HWTEST_F(ReminderStoreTest, ReminderTimerStrategyTest_00003, Function | SmallTes ReminderRequestTimer* timer = static_cast(reminder.GetRefPtr()); timer->countDownTimeInSeconds_ = 10001; - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { @@ -505,8 +501,7 @@ HWTEST_F(ReminderStoreTest, ReminderAlarmStrategyTest_00001, Function | SmallTes alarm->hour_ = 12; alarm->minute_ = 30; - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { @@ -554,8 +549,7 @@ HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00001, Function | Small calendar->repeatMonth_ = 13; calendar->AddExcludeDate(ts); - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { @@ -607,8 +601,7 @@ HWTEST_F(ReminderStoreTest, ReminderCalendarStrategyTest_00002, Function | Small calendar->rruleWantAgentInfo_->abilityName = "abilityName"; calendar->rruleWantAgentInfo_->uri = "uri"; - sptr bundleOption = new NotificationBundleOption("test", 101); - reminderStore.UpdateOrInsert(reminder, bundleOption); + reminderStore.UpdateOrInsert(reminder); auto reminders = reminderStore.GetAllValidReminders(); bool succeed = false; for (auto each : reminders) { diff --git a/services/reminder/test/unittest/reminder_ut_constant.h b/services/reminder/test/unittest/reminder_ut_constant.h new file mode 100644 index 000000000..676455b87 --- /dev/null +++ b/services/reminder/test/unittest/reminder_ut_constant.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_TEST_UNITEST_REMINDER_UT_CONSTANT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_TEST_UNITEST_REMINDER_UT_CONSTANT_H + +#include + +namespace OHOS { +namespace Notification { +constexpr uint32_t NATIVE_TOKEN = 0; +constexpr uint32_t NON_NATIVE_TOKEN = 1; +constexpr uint32_t DLP_NATIVE_TOKEN = 2; +constexpr int32_t SYSTEM_APP_UID = 100; +constexpr int32_t NON_SYSTEM_APP_UID = 1000; +constexpr int32_t NON_BUNDLE_NAME_UID = 2000; +const std::string TEST_DEFUALT_BUNDLE = "bundleName"; +constexpr int32_t TEST_SUBSCRIBE_USER_INIT = -1; +} // namespace Notification +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp b/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp index 1c8b5bee8..104eb45ed 100644 --- a/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp +++ b/test/fuzztest/advancednotificationservice_fuzzer/advancednotificationservice_fuzzer.cpp @@ -265,7 +265,7 @@ namespace OHOS { service->ChangeNotificationByControlFlags(record, fuzzData->ConsumeBool()); service->CheckPublishPreparedNotification(record, fuzzData->ConsumeBool()); service->UpdateInNotificationList(record); - service->PublishInNotificationList(record); + service->PublishFlowControl(record); service->IsNeedPushCheck(request); return true; } diff --git a/test/fuzztest/reminderservice_fuzzer/BUILD.gn b/test/fuzztest/reminderservice_fuzzer/BUILD.gn index 4cef50cd2..5b277ca2a 100644 --- a/test/fuzztest/reminderservice_fuzzer/BUILD.gn +++ b/test/fuzztest/reminderservice_fuzzer/BUILD.gn @@ -38,8 +38,6 @@ ohos_fuzztest("ReminderServiceFuzzTest") { "${component_path}/test/fuzztest/fuzz_common_base:fuzz_common_base", "${frameworks_module_reminder_path}:reminder_innerkits", "${services_path}/reminder:reminder_service_sources", - "//third_party/icu/icu4c:shared_icuuc", - "//third_party/libxml2:libxml2", ] if (is_double_framework) { @@ -80,6 +78,8 @@ ohos_fuzztest("ReminderServiceFuzzTest") { "i18n:intl_util", "image_framework:image_native", "init:libbegetutil", + "icu:shared_icuuc", + "libxml2:libxml2", "kv_store:distributeddata_inner", "openssl:libcrypto_shared", "os_account:os_account_innerkits", -- Gitee From 905a568f31239cbb56d11d06a47d45abe25f6e41 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 25 Nov 2024 15:38:52 +0800 Subject: [PATCH 17/29] push Signed-off-by: fengyang --- services/reminder/include/reminder_data_manager.h | 2 +- services/reminder/src/reminder_data_manager.cpp | 3 +-- services/reminder/src/reminder_store.cpp | 10 ++++------ services/reminder/src/reminder_store_strategy.cpp | 2 +- 4 files changed, 7 insertions(+), 10 deletions(-) diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 383187fdc..293ce29ac 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -388,7 +388,7 @@ private: */ bool CheckReminderLimitExceededLocked(const int32_t callingUid, const sptr& reminder) const; - void CloseReminder(const sptr &reminder, bool cancelNotification); + void CloseReminder(const sptr &reminder, bool cancelNotification, bool isButtonClick = true); /** * Create a information for timer, such as timer type, repeat policy, interval and want agent. diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 0c0f5faba..c3c7b42c8 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -1217,15 +1217,14 @@ sptr ReminderDataManager::GetRecentReminderLocked() sort(reminderVector_.begin(), reminderVector_.end(), cmp); for (auto it = reminderVector_.begin(); it != reminderVector_.end();) { if (!(*it)->IsExpired()) { - ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); time_t now; (void)time(&now); // unit is seconds. if (now < 0 || ReminderRequest::GetDurationSinceEpochInMilli(now) > (*it)->GetTriggerTimeInMilli()) { - ANSR_LOGE("Get recent reminder while the trigger time is overdue."); it++; continue; } + ANSR_LOGI("GetRecentReminderLocked: %{public}s", (*it)->Dump().c_str()); return *it; } if (!(*it)->CanRemove()) { diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index 7bedc5055..363e37217 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -720,14 +720,14 @@ std::vector> ReminderStore::GetReminders(const std::string return reminders; } bool isAtLastRow = false; - queryResultSet->IsAtLastRow(isAtLastRow); - while (!isAtLastRow) { + int32_t ret = queryResultSet->IsAtLastRow(isAtLastRow); + while (ret == NativeRdb::E_OK && !isAtLastRow) { queryResultSet->GoToNextRow(); sptr reminder = BuildReminder(queryResultSet); if (reminder != nullptr) { reminders.push_back(reminder); } - queryResultSet->IsAtLastRow(isAtLastRow); + ret = queryResultSet->IsAtLastRow(isAtLastRow); } ANSR_LOGD("Size=%{public}zu", reminders.size()); return reminders; @@ -766,9 +766,7 @@ sptr ReminderStore::BuildReminder(const std::shared_ptr& reminder, } ReminderStrategy::RecoverFromDb(reminder, baseResult); ReminderCalendarStrategy::RecoverTime(reminder, resultSet); - if (reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { + if (reminder != nullptr && reminder->GetReminderType() == ReminderRequest::ReminderType::CALENDAR) { ReminderRequestCalendar* calendar = static_cast(reminder.GetRefPtr()); uint32_t repeatDay = 0; -- Gitee From aac3e2e7cf11cc4abe7c3de30033b0a35a6285e4 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 25 Nov 2024 16:38:54 +0800 Subject: [PATCH 18/29] push Signed-off-by: fengyang --- services/reminder/include/reminder_data_manager.h | 2 +- services/reminder/src/reminder_data_manager.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 293ce29ac..383187fdc 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -388,7 +388,7 @@ private: */ bool CheckReminderLimitExceededLocked(const int32_t callingUid, const sptr& reminder) const; - void CloseReminder(const sptr &reminder, bool cancelNotification, bool isButtonClick = true); + void CloseReminder(const sptr &reminder, bool cancelNotification); /** * Create a information for timer, such as timer type, repeat policy, interval and want agent. diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index c3c7b42c8..76a0ecbbe 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -941,7 +941,7 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & } uint64_t tempTriggerTime = (*it)->GetTriggerTimeInMilli(); if (tempTriggerTime < triggerTime) { - ANSR_LOGE("this reminder triggerTime is less than target triggerTime."); + ANSR_LOGD("this reminder triggerTime is less than target triggerTime."); continue; } if (tempTriggerTime - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { -- Gitee From a9a0819dab6f57646058736181abc4a25a8859a7 Mon Sep 17 00:00:00 2001 From: fengyang Date: Thu, 28 Nov 2024 11:26:14 +0800 Subject: [PATCH 19/29] push Signed-off-by: fengyang --- frameworks/ans/src/notification_helper.cpp | 5 + .../core/include/ans_manager_interface.h | 9 ++ frameworks/core/include/ans_manager_proxy.h | 9 ++ frameworks/core/include/ans_manager_stub.h | 10 ++ frameworks/core/include/ans_notification.h | 9 ++ ..._notification_service_ipc_interface_code.h | 1 + frameworks/core/src/ans_notification.cpp | 12 ++ .../src/manager/ans_manager_proxy_utils.cpp | 35 +++++ .../core/src/manager/ans_manager_stub.cpp | 27 ++++ .../src/manager/ans_manager_stub_invalid.cpp | 6 + frameworks/reminder/BUILD.gn | 1 + frameworks/reminder/src/reminder_request.cpp | 13 +- interfaces/inner_api/notification_helper.h | 9 ++ .../include/advanced_notification_service.h | 9 ++ .../ans/src/advanced_notification_utils.cpp | 6 + .../reminder/include/reminder_data_manager.h | 6 +- .../reminder/src/reminder_data_manager.cpp | 143 ++++++------------ .../reminder/src/reminder_event_manager.cpp | 2 +- .../src/reminder_notification_inline.cpp | 9 ++ services/reminder/src/reminder_service.cpp | 44 +++--- 20 files changed, 232 insertions(+), 133 deletions(-) diff --git a/frameworks/ans/src/notification_helper.cpp b/frameworks/ans/src/notification_helper.cpp index 45f7340a3..a98e65bd3 100644 --- a/frameworks/ans/src/notification_helper.cpp +++ b/frameworks/ans/src/notification_helper.cpp @@ -587,5 +587,10 @@ ErrCode NotificationHelper::UpdateNotificationTimerByUid(const int32_t uid, cons { return DelayedSingleton::GetInstance()->UpdateNotificationTimerByUid(uid, isPaused); } + +ErrCode NotificationHelper::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) +{ + return DelayedSingleton::GetInstance()->AllowUseReminder(bundleName, isAllowUseReminder); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/include/ans_manager_interface.h b/frameworks/core/include/ans_manager_interface.h index b7b2ac909..04909ffbb 100644 --- a/frameworks/core/include/ans_manager_interface.h +++ b/frameworks/core/include/ans_manager_interface.h @@ -891,6 +891,15 @@ public: * @return Returns ERR_OK on success, others on failure. */ virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) = 0; + + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) = 0; #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. diff --git a/frameworks/core/include/ans_manager_proxy.h b/frameworks/core/include/ans_manager_proxy.h index 231adbd1d..186c2efd5 100644 --- a/frameworks/core/include/ans_manager_proxy.h +++ b/frameworks/core/include/ans_manager_proxy.h @@ -880,6 +880,15 @@ public: */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. diff --git a/frameworks/core/include/ans_manager_stub.h b/frameworks/core/include/ans_manager_stub.h index 5545d0469..dd74da5e4 100644 --- a/frameworks/core/include/ans_manager_stub.h +++ b/frameworks/core/include/ans_manager_stub.h @@ -882,6 +882,15 @@ public: */ virtual ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile) override; + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + virtual ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) override; + #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED /** * @brief Register Swing Callback. @@ -994,6 +1003,7 @@ private: ErrCode HandleRemoveDoNotDisturbProfiles(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetTargetDeviceStatus(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDoNotDisturbProfile(MessageParcel &data, MessageParcel &reply); + ErrCode HandleAllowUseReminder(MessageParcel &data, MessageParcel &reply); #ifdef NOTIFICATION_SMART_REMINDER_SUPPORTED ErrCode HandleRegisterSwingCallback(MessageParcel &data, MessageParcel &reply); #endif diff --git a/frameworks/core/include/ans_notification.h b/frameworks/core/include/ans_notification.h index acf4db37e..f79d62b09 100644 --- a/frameworks/core/include/ans_notification.h +++ b/frameworks/core/include/ans_notification.h @@ -1127,6 +1127,15 @@ public: */ ErrCode GetDoNotDisturbProfile(int32_t id, sptr &profile); + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder); + /** * @brief Ans service died, OnRemoteDied called. */ diff --git a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h index fc620668a..70c5e62f3 100644 --- a/frameworks/core/include/distributed_notification_service_ipc_interface_code.h +++ b/frameworks/core/include/distributed_notification_service_ipc_interface_code.h @@ -152,6 +152,7 @@ namespace Notification { GET_EXCLUDE_DATES_REMINDER, GET_DONOTDISTURB_PROFILE, UPDATE_NOTIFICATION_TIMER, + ALLOW_USE_REMINDER, }; } } diff --git a/frameworks/core/src/ans_notification.cpp b/frameworks/core/src/ans_notification.cpp index 93d3561f0..fb0f7a3da 100644 --- a/frameworks/core/src/ans_notification.cpp +++ b/frameworks/core/src/ans_notification.cpp @@ -1882,6 +1882,18 @@ ErrCode AnsNotification::GetDoNotDisturbProfile(int32_t id, sptrGetDoNotDisturbProfile(id, profile); } +ErrCode AnsNotification::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) +{ + ANS_LOGD("enter"); + sptr proxy = GetAnsManagerProxy(); + if (!proxy) { + ANS_LOGE("AllowUseReminder fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return proxy->AllowUseReminder(bundleName, isAllowUseReminder); +} + void AnsNotification::CreateSubscribeListener(const std::shared_ptr &subscriber, sptr &listener) { diff --git a/frameworks/core/src/manager/ans_manager_proxy_utils.cpp b/frameworks/core/src/manager/ans_manager_proxy_utils.cpp index b0236fef5..b479d9b74 100644 --- a/frameworks/core/src/manager/ans_manager_proxy_utils.cpp +++ b/frameworks/core/src/manager/ans_manager_proxy_utils.cpp @@ -278,6 +278,41 @@ ErrCode AnsManagerProxy::IsSmartReminderEnabled(const std::string &deviceType, b return result; } +ErrCode AnsManagerProxy::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) +{ + ANS_LOGD("enter"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGE("[AllowUseReminder] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(bundleName)) { + ANS_LOGE("[AllowUseReminder] fail: write deviceType failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(NotificationInterfaceCode::ALLOW_USE_REMINDER, option, data, reply); + if (result != ERR_OK) { + ANS_LOGE("[AllowUseReminder] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGE("[AllowUseReminder] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(isAllowUseReminder)) { + ANS_LOGE("[AllowUseReminder] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + ErrCode AnsManagerProxy::ShellDump(const std::string &cmd, const std::string &bundle, int32_t userId, int32_t recvUserId, std::vector &dumpInfo) { diff --git a/frameworks/core/src/manager/ans_manager_stub.cpp b/frameworks/core/src/manager/ans_manager_stub.cpp index 771b10c8b..bde8fbdeb 100644 --- a/frameworks/core/src/manager/ans_manager_stub.cpp +++ b/frameworks/core/src/manager/ans_manager_stub.cpp @@ -425,6 +425,10 @@ int32_t AnsManagerStub::OnRemoteRequest(uint32_t code, MessageParcel &data, Mess result = HandleUpdateNotificationTimerByUid(data, reply); break; } + case static_cast(NotificationInterfaceCode::ALLOW_USE_REMINDER): { + result = HandleAllowUseReminder(data, reply); + break; + } default: { ANS_LOGE("[OnRemoteRequest] fail: unknown code!"); return IPCObjectStub::OnRemoteRequest(code, data, reply, flags); @@ -2469,5 +2473,28 @@ ErrCode AnsManagerStub::HandleUpdateNotificationTimerByUid(MessageParcel &data, } return ERR_OK; } + +ErrCode AnsManagerStub::HandleAllowUseReminder(MessageParcel &data, MessageParcel &reply) +{ + ANS_LOGD("enter"); + std::string bundleName; + if (!data.ReadString(bundleName)) { + ANS_LOGE("[HandleAllowUseReminder] fail: read deviceId failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool isAllowUseReminder = false; + ErrCode result = AllowUseReminder(bundleName, isAllowUseReminder); + if (!reply.WriteInt32(result)) { + ANS_LOGE("[HandleAllowUseReminder] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(isAllowUseReminder)) { + ANS_LOGE("[HandleAllowUseReminder] fail: write enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp index fc9d81ac4..e8880ba25 100644 --- a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp @@ -610,6 +610,12 @@ ErrCode AnsManagerStub::GetDoNotDisturbProfile(int32_t id, sptr& swingCallback) { diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index 82581eb23..120677814 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -91,6 +91,7 @@ ohos_shared_library("reminder_innerkits") { public_external_deps = [ "ability_runtime:wantagent_innerkits", + "ffrt:libffrt", "image_framework:image_native", ] diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index caaa54b51..aa68bda18 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -44,6 +44,7 @@ const int32_t BUTTON_PKG_INDEX = 2; const int32_t BUTTON_ABILITY_INDEX = 3; const int32_t WANT_AGENT_URI_INDEX = 2; const int32_t INDENT = -1; +const int32_t FOUDATION_UID = 5523; const char* const PARAM_EXTRA_KEY = "NotificationRequest_extraInfo"; } @@ -1687,16 +1688,8 @@ void ReminderRequest::UpdateNotificationCommon(bool isSnooze) void ReminderRequest::UpdateNotificationBundleInfo() { - std::string ownerBundleName = notificationRequest_->GetOwnerBundleName(); - if (!(ownerBundleName.empty())) { - return; - } - ANSR_LOGD("ownerBundleName=%{public}s, bundleName_=%{public}s", - ownerBundleName.c_str(), bundleName_.c_str()); - notificationRequest_->SetOwnerBundleName(bundleName_); - notificationRequest_->SetCreatorBundleName(bundleName_); - notificationRequest_->SetCreatorUid(uid_); - notificationRequest_->SetCreatorUserId(userId_); + notificationRequest_->SetOwnerUid(uid_); + notificationRequest_->SetCreatorUid(FOUDATION_UID); } void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) diff --git a/interfaces/inner_api/notification_helper.h b/interfaces/inner_api/notification_helper.h index 6b021c875..0dc96c34c 100644 --- a/interfaces/inner_api/notification_helper.h +++ b/interfaces/inner_api/notification_helper.h @@ -1109,6 +1109,15 @@ public: * @return Returns Update result. */ static ErrCode UpdateNotificationTimerByUid(const int32_t uid, const bool isPaused); + + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + static ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder); }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index b7934dbd2..e9f300416 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1075,6 +1075,15 @@ public: */ bool AllowUseReminder(const std::string& bundleName); + /** + * @brief Whether reminders are allowed. + * + * @param bundleName bundleName + * @param isAllowUseReminder isAllowUseReminder + * @return Returns ERR_OK on success, others on failure. + */ + ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder); + /** * @brief Get do not disturb profile by id. * diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index e05796ebe..a6349a672 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -2019,6 +2019,12 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName #endif } +ErrorCode AdvancedNotificationService::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) +{ + isAllowUseReminder = AllowUseReminder(bundleName); + return ERR_OK; +} + void AdvancedNotificationService::ResetDistributedEnabled() { if (notificationSvrQueue_ == nullptr) { diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 383187fdc..c60b77149 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -404,8 +404,6 @@ private: void GetImmediatelyShowRemindersLocked(std::vector> &reminders) const; - std::string GetSoundUri(const sptr &reminder); - /** * Find the reminder from reminderVector_ by reminder id. * @@ -594,10 +592,8 @@ private: * @brief Assign unique reminder id and save reminder in memory. * * @param reminder Indicates a reminder. - * @param bundleOption Indicates bundle option relative to the reminder. */ - void UpdateAndSaveReminderLocked( - const sptr &reminder, const int32_t callingUid); + void UpdateAndSaveReminderLocked(const sptr &reminder); void UpdateNotification(const sptr &reminder, bool isSnooze); diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 76a0ecbbe..ba84c2dca 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -49,6 +49,8 @@ #ifdef HAS_HISYSEVENT_PART #include "hisysevent.h" #endif +#include "reminder_notification_inline.cpp" +#include "notification_helper.h" namespace OHOS { namespace Notification { @@ -311,13 +313,9 @@ void ReminderDataManager::CancelNotification(const sptr &remind return; } ANSR_LOGD("Cancel notification"); - // if (advancedNotificationService_ == nullptr) { - // ANSR_LOGE("Cancel notification fail"); - // return; - // } - // sptr bundleOption = reminder->GetNotificationBundleOption(); - // advancedNotificationService_->CancelPreparedNotification(notification->GetNotificationId(), - // ReminderRequest::NOTIFICATION_LABEL, bundleOption, NotificationConstant::APP_CANCEL_REMINDER_REASON_DELETE); + std::string identity = IPCSkeleton::ResetCallingIdentity(); + NotificationHelper::CancelNotification(ReminderRequest::NOTIFICATION_LABEL, reminder->GetNotificationId()); + IPCSkeleton::SetCallingIdentity(identity); } bool ReminderDataManager::CheckReminderLimitExceededLocked(const int32_t callingUid, @@ -792,53 +790,31 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde sptr notificationRequest = reminder->GetNotificationRequest(); ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); UpdateNotification(reminder, false); - // if (advancedNotificationService_ == nullptr) { - // ANSR_LOGE("Ans instance is null."); - // return; - // } - // // Set the notification SoundEnabled and VibrationEnabled by soltType + NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - // advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); store_->UpdateOrInsert(reminder); } -void ReminderDataManager::UpdateAndSaveReminderLocked( - const sptr& reminder, const int32_t callingUid) +void ReminderDataManager::UpdateAndSaveReminderLocked(const sptr& reminder) { std::lock_guard lock(ReminderDataManager::MUTEX); reminder->InitReminderId(); - int32_t userId = -1; - ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(callingUid, userId); - reminder->InitUserId(userId); - reminder->InitUid(callingUid); - // reminder->InitBundleName(bundleOption->GetBundleName()); if (reminder->GetTriggerTimeInMilli() == ReminderRequest::INVALID_LONG_LONG_VALUE) { ANSR_LOGW("now publish reminder is expired. reminder is =%{public}s", reminder->Dump().c_str()); reminder->SetExpired(true); } - // reminder->SetNotificationBundleOption(bundleOption); reminderVector_.push_back(reminder); totalCount_++; store_->UpdateOrInsert(reminder); } -// void ReminderDataManager::SetService(sptr &advancedNotificationService) -// { -// advancedNotificationService_ = advancedNotificationService; -// } - bool ReminderDataManager::ShouldAlert(const sptr &reminder) const { if (reminder == nullptr) { return false; } int32_t reminderId = reminder->GetReminderId(); - // sptr bundleOption = reminder->GetNotificationBundleOption(); - // if (bundleOption == nullptr) { - // ANSR_LOGD("The reminder (reminderId=%{public}d) is silent", reminderId); - // return false; - // } int32_t userId = -1; ReminderOsAccountManagerHelper::GetInstance().GetOsAccountLocalIdFromUid(reminder->GetUid(), userId); if (currentUserId_ != userId) { @@ -847,21 +823,22 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con return false; } - sptr date; - // ErrCode errCode = advancedNotificationService_->GetDoNotDisturbDate(date); - // if (errCode != ERR_OK) { - // ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); - // return true; - // } + NotificationDoNotDisturbDate date; + ErrCode errCode = NotificationHelper::GetDoNotDisturbDate(date); + if (errCode != ERR_OK) { + ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); + return true; + } if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { return true; } + auto bundleOption = CreateBundleOption(reminder->GetBundleName, reminder->GetUid()); std::vector> slots; - // errCode = advancedNotificationService_->GetSlotsByBundle(bundleOption, slots); - // if (errCode != ERR_OK) { - // ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); - // return false; - // } + errCode = NotificationHelper::GetSlotsByBundle(bundleOption, slots); + if (errCode != ERR_OK) { + ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); + return false; + } for (auto slot : slots) { if (slot->GetType() != reminder->GetSlotType()) { continue; @@ -1021,12 +998,6 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co static_cast(isNeedToPlaySound), reminder->Dump().c_str()); int32_t reminderId = reminder->GetReminderId(); sptr notificationRequest = reminder->GetNotificationRequest(); - // if (advancedNotificationService_ == nullptr) { - // ANSR_LOGE("ShowReminder fail"); - // reminder->OnShow(false, isSysTimeChanged, false); - // store_->UpdateOrInsert(reminder, bundleOption); - // return; - // } if (!IsAllowedNotify(reminder)) { ANSR_LOGE("Not allow to notify."); reminder->OnShow(false, isSysTimeChanged, false); @@ -1042,23 +1013,23 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co if (alertingReminderId_ != -1) { TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); } - // Set the notification SoundEnabled and VibrationEnabled by soltType + ErrCode errCode = NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); // ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - // if (errCode != ERR_OK) { - // reminder->OnShowFail(); - // RemoveFromShowedReminders(reminder); - // } else { - // if (toPlaySound) { - // PlaySoundAndVibration(reminder); // play sound and vibration - // if (needScheduleTimeout) { - // StartTimer(reminder, TimerType::ALERTING_TIMER); - // } else { - // TerminateAlerting(1, reminder); - // } - // } - // HandleSameNotificationIdShowing(reminder); - // } + if (errCode != ERR_OK) { + reminder->OnShowFail(); + RemoveFromShowedReminders(reminder); + } else { + if (toPlaySound) { + PlaySoundAndVibration(reminder); // play sound and vibration + if (needScheduleTimeout) { + StartTimer(reminder, TimerType::ALERTING_TIMER); + } else { + TerminateAlerting(1, reminder); + } + } + HandleSameNotificationIdShowing(reminder); + } store_->UpdateOrInsert(reminder); if (isNeedToStartNext) { @@ -1117,13 +1088,11 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) sptr notificationRequest = reminder->GetNotificationRequest(); ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); UpdateNotification(reminder, true); - // if (advancedNotificationService_ == nullptr) { - // ANSR_LOGE("Ans instance is null"); - // return; - // } // // Set the notification SoundEnabled and VibrationEnabled by soltType // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); + // advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); StartRecentReminder(); } @@ -1428,17 +1397,14 @@ bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) if (reminder == nullptr) { return false; } - // auto option = reminder->GetNotificationBundleOption(); - // if (option == nullptr) { - // ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminder->GetReminderId()); - // return false; - // } bool isAllowed = false; - // ErrCode errCode = advancedNotificationService_->IsSpecialBundleAllowedNotify(option, isAllowed); - // if (errCode != ERR_OK) { - // ANSR_LOGE("Failed to call IsSpecialBundleAllowedNotify, errCode=%{public}d", errCode); - // return false; - // } + auto bundleOption = CreateBundleOption(reminder->GetBundleName, reminder->GetUid()); + + ErrCode errCode = NotificationHelper::IsAllowedNotify(bundleOption, isAllowed); + if (errCode != ERR_OK) { + ANSR_LOGE("Failed to call IsAllowedNotify, errCode=%{public}d", errCode); + return false; + } return isAllowed; } @@ -1560,29 +1526,6 @@ void ReminderDataManager::PlaySoundAndVibration(const sptr &rem SetAlertingReminder(reminder); } -std::string ReminderDataManager::GetSoundUri(const sptr &reminder) -{ - Uri uri = DEFAULT_NOTIFICATION_SOUND; - // if (advancedNotificationService_ == nullptr) { - // ANSR_LOGE("Ans instance is null."); - // return uri.GetSchemeSpecificPart(); - // } - // sptr bundle = reminder->GetNotificationBundleOption(); - std::vector> slots; - // ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); - // if (errCode != ERR_OK) { - // ANSR_LOGW("Get sound uri fail, use default sound instead."); - // return uri.GetSchemeSpecificPart(); - // } - for (auto it = slots.begin(); it != slots.end(); ++it) { - if ((*it)->GetType() == reminder->GetSlotType()) { - uri = (*it)->GetSound(); - break; - } - } - return uri.GetSchemeSpecificPart(); -} - void ReminderDataManager::StopSoundAndVibrationLocked(const sptr &reminder) { std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); diff --git a/services/reminder/src/reminder_event_manager.cpp b/services/reminder/src/reminder_event_manager.cpp index 57f165554..51a6ef21e 100644 --- a/services/reminder/src/reminder_event_manager.cpp +++ b/services/reminder/src/reminder_event_manager.cpp @@ -78,7 +78,7 @@ void ReminderEventManager::init(std::shared_ptr &reminderDa IPCSkeleton::SetCallingIdentity(identity); subscriber_ = std::make_shared(reminderDataManager); - if (NotificationHelper::SubscribeNotification(*subscriber_) != ERR_OK) { + if (NotificationHelper::SubscribeNotificationSelf(*subscriber_) != ERR_OK) { ANSR_LOGD("SubscribeNotification failed"); } diff --git a/services/reminder/src/reminder_notification_inline.cpp b/services/reminder/src/reminder_notification_inline.cpp index b6093427c..a981b64a4 100644 --- a/services/reminder/src/reminder_notification_inline.cpp +++ b/services/reminder/src/reminder_notification_inline.cpp @@ -25,6 +25,10 @@ #include "errors.h" #include "ipc_skeleton.h" #include "notification_constant.h" +#include "notification_bundle_option.h" +#include "reminder_request.h" +#include "notification_request.h" +#include namespace OHOS { namespace Notification { @@ -68,5 +72,10 @@ inline tm GetLocalTime(time_t time) return ret; } +inline NotificationBundleOption CreateBundleOption(const std::string& bundleName, const int32_t uid) +{ + return NotificationBundleOption(bundleName, uid); +} + } // namespace Notification } // namespace OHOS diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index 51f8cddaf..391a97ab4 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -38,6 +38,8 @@ #include "os_account_manager.h" #include "hitrace_meter_adapter.h" #include "reminder_data_manager.h" +#include "notification_helper.h" +#include "reminder_os_account_manager_helper.h" #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED #include "distributed_notification_manager.h" #include "distributed_preferences.h" @@ -110,10 +112,12 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); return ERR_REMINDER_PERMISSION_DENIED; } - // if (!AllowUseReminder(bundle)) { - // ANSR_LOGW("The number of reminders exceeds the limit[0]."); - // return ERR_REMINDER_NUMBER_OVERLOAD; - // } + bool isAllowUseReminder = false; + NotificationHelper::AllowUseReminder(bundle, isAllowUseReminder); + if (isAllowUseReminder) { + ANSR_LOGW("The number of reminders exceeds the limit[0]."); + return ERR_REMINDER_NUMBER_OVERLOAD; + } ANSR_LOGD("is system app: %{public}d", ReminderAccessTokenHelper::IsSystemApp()); tarReminder->SetSystemApp(ReminderAccessTokenHelper::IsSystemApp()); sptr notificationRequest = reminder.GetNotificationRequest(); @@ -130,26 +134,32 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ wantAgentName.c_str(), msWantAgentName.c_str()); return ERR_ANS_INVALID_PARAM; } + std::string bundleName = bundle; if (wantAgentName != bundle && wantAgentName != "") { ANSR_LOGI("Set agent reminder, bundle:%{public}s, wantAgentName:%{public}s", bundle.c_str(), wantAgentName.c_str()); - // SetAgentNotification(notificationRequest, wantAgentName); + bundleName = wantAgentName; } else if (msWantAgentName != bundle && msWantAgentName != "") { ANSR_LOGI("Set agent reminder, bundle:%{public}s, msWantAgentName:%{public}s", bundle.c_str(), msWantAgentName.c_str()); - // SetAgentNotification(notificationRequest, msWantAgentName); + bundleName = msWantAgentName; + } + tarReminder->InitBundleName(bundleName); + int32_t activeUserId = -1; + if (ReminderOsAccountManagerHelper::GetInstance().GetCurrentActiveUserId(activeUserId) != ERR_OK) { + ANSR_LOGE("failed to get active user id"); + return ERR_ANS_INVALID_BUNDLE; + } + tarReminder->InitUserId(activeUserId); + tarReminder->InitUid(ReminderBundleManagerHelper::GetInstance()->GetDefaultUidByBundleName( + tarReminder->GetBundleName(), tarReminder->GetUserId())); + auto bundleOption = CreateBundleOption(tarReminder->GetBundleName(), tarReminder->GetUid()); + bool allowedNotify = false; + result = NotificationHelper::IsAllowedNotify(bundleOption, allowedNotify); + if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { + ANSR_LOGW("The application does not request enable notification"); + return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; } - // ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); - // if (result != ERR_OK) { - // ANSR_LOGW("PrepareNotificationInfo fail"); - // return result; - // } - // bool allowedNotify = false; - // result = IsAllowedNotifySelf(bundleOption, allowedNotify); - // if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { - // ANSR_LOGW("The application does not request enable notification"); - // return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; - // } auto rdm = ReminderDataManager::GetInstance(); if (rdm == nullptr) { return ERR_NO_INIT; -- Gitee From 10bb2c5c95a234fec9c6a96b552d051d7492b573 Mon Sep 17 00:00:00 2001 From: fengyang Date: Thu, 28 Nov 2024 14:37:28 +0800 Subject: [PATCH 20/29] push Signed-off-by: fengyang --- services/ans/include/advanced_notification_service.h | 2 +- services/ans/src/advanced_notification_utils.cpp | 2 +- services/reminder/src/reminder_data_manager.cpp | 10 +++++----- services/reminder/src/reminder_service.cpp | 2 +- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index e9f300416..a543cfcaa 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -1082,7 +1082,7 @@ public: * @param isAllowUseReminder isAllowUseReminder * @return Returns ERR_OK on success, others on failure. */ - ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder); + ErrCode AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) override; /** * @brief Get do not disturb profile by id. diff --git a/services/ans/src/advanced_notification_utils.cpp b/services/ans/src/advanced_notification_utils.cpp index a6349a672..87cbeb26e 100644 --- a/services/ans/src/advanced_notification_utils.cpp +++ b/services/ans/src/advanced_notification_utils.cpp @@ -2019,7 +2019,7 @@ bool AdvancedNotificationService::AllowUseReminder(const std::string& bundleName #endif } -ErrorCode AdvancedNotificationService::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) +ErrCode AdvancedNotificationService::AllowUseReminder(const std::string& bundleName, bool& isAllowUseReminder) { isAllowUseReminder = AllowUseReminder(bundleName); return ERR_OK; diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index ba84c2dca..3d2af1417 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -99,7 +99,7 @@ ErrCode ReminderDataManager::PublishReminder(const sptr &remind if (CheckReminderLimitExceededLocked(callingUid, reminder)) { return ERR_REMINDER_NUMBER_OVERLOAD; } - UpdateAndSaveReminderLocked(reminder, callingUid); + UpdateAndSaveReminderLocked(reminder); queue_->submit([this, reminder]() { StartRecentReminder(); }); @@ -829,12 +829,12 @@ bool ReminderDataManager::ShouldAlert(const sptr &reminder) con ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get disturbDate error", reminderId); return true; } - if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { + if (date.GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { return true; } - auto bundleOption = CreateBundleOption(reminder->GetBundleName, reminder->GetUid()); + auto bundleOption = CreateBundleOption(reminder->GetBundleName(), reminder->GetUid()); std::vector> slots; - errCode = NotificationHelper::GetSlotsByBundle(bundleOption, slots); + errCode = NotificationHelper::GetNotificationSlotsForBundle(bundleOption, slots); if (errCode != ERR_OK) { ANSR_LOGE("The reminder (reminderId=%{public}d) is silent for get slots error", reminderId); return false; @@ -1398,7 +1398,7 @@ bool ReminderDataManager::IsAllowedNotify(const sptr &reminder) return false; } bool isAllowed = false; - auto bundleOption = CreateBundleOption(reminder->GetBundleName, reminder->GetUid()); + auto bundleOption = CreateBundleOption(reminder->GetBundleName(), reminder->GetUid()); ErrCode errCode = NotificationHelper::IsAllowedNotify(bundleOption, isAllowed); if (errCode != ERR_OK) { diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index 391a97ab4..353f0771a 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -155,7 +155,7 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ tarReminder->GetBundleName(), tarReminder->GetUserId())); auto bundleOption = CreateBundleOption(tarReminder->GetBundleName(), tarReminder->GetUid()); bool allowedNotify = false; - result = NotificationHelper::IsAllowedNotify(bundleOption, allowedNotify); + ErrCode result = NotificationHelper::IsAllowedNotify(bundleOption, allowedNotify); if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { ANSR_LOGW("The application does not request enable notification"); return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; -- Gitee From c9729144e8d334378ea2cf376dba8734b6307471 Mon Sep 17 00:00:00 2001 From: fengyang Date: Fri, 29 Nov 2024 17:30:29 +0800 Subject: [PATCH 21/29] push Signed-off-by: fengyang --- .../src/manager/ans_manager_stub_invalid.cpp | 2 +- .../ans_notification_branch_test.cpp | 5 + frameworks/reminder/BUILD.gn | 1 + frameworks/reminder/src/reminder_request.cpp | 188 +++++++----------- .../reminder/src/reminder_request_client.cpp | 85 ++++++-- .../src/reminder_service_load_callback.cpp | 40 ++++ .../reminder_request_branch_test.cpp | 94 +++++---- .../test/unittest/reminder_request_test.cpp | 89 ++++----- interfaces/inner_api/reminder_request.h | 44 ++-- interfaces/inner_api/reminder_request_alarm.h | 2 +- .../inner_api/reminder_request_calendar.h | 2 +- .../inner_api/reminder_request_client.h | 9 + interfaces/inner_api/reminder_request_timer.h | 2 +- .../reminder_service_load_callback.h | 36 ++++ .../reminder/include/reminder_data_manager.h | 6 +- services/reminder/include/reminder_service.h | 12 ++ services/reminder/include/reminder_store.h | 4 +- services/reminder/sa_profile/1930.json | 10 +- .../reminder/src/reminder_data_manager.cpp | 124 +++++++----- .../reminder/src/reminder_event_manager.cpp | 4 + .../src/reminder_notification_inline.cpp | 15 ++ services/reminder/src/reminder_service.cpp | 137 +++++++++---- .../reminder/src/reminder_service_ability.cpp | 2 + services/reminder/src/reminder_store.cpp | 44 +++- .../unittest/reminder_data_manager_test.cpp | 2 +- .../reminder_service_publish_test.cpp | 3 +- .../notificationrequest_fuzzer.cpp | 1 - .../reminderdatamanager_fuzzer.cpp | 1 - .../reminderrequestannex_fuzzer.cpp | 4 +- 29 files changed, 602 insertions(+), 366 deletions(-) create mode 100644 frameworks/reminder/src/reminder_service_load_callback.cpp create mode 100644 interfaces/inner_api/reminder_service_load_callback.h diff --git a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp index e8880ba25..4fd138321 100644 --- a/frameworks/core/src/manager/ans_manager_stub_invalid.cpp +++ b/frameworks/core/src/manager/ans_manager_stub_invalid.cpp @@ -610,7 +610,7 @@ ErrCode AnsManagerStub::GetDoNotDisturbProfile(int32_t id, sptrreminderType_ = other.reminderType_; this->slotType_ = other.slotType_; this->snoozeSlotType_ = other.snoozeSlotType_; - this->notificationRequest_ = other.notificationRequest_; this->wantAgentInfo_ = other.wantAgentInfo_; this->maxScreenWantAgentInfo_ = other.maxScreenWantAgentInfo_; this->actionButtonMap_ = other.actionButtonMap_; @@ -794,11 +794,6 @@ std::string ReminderRequest::GetGroupId() const return groupId_; } -sptr ReminderRequest::GetNotificationRequest() const -{ - return notificationRequest_; -} - int32_t ReminderRequest::GetReminderId() const { return reminderId_; @@ -1006,48 +1001,46 @@ std::string ReminderRequest::GetMaxWantAgentStr() return maxWantAgentStr_; } -void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra) +NotificationRequest ReminderRequest::CreateNotificationRequest() { - switch (type) { - case UpdateNotificationType::COMMON: { - ANSR_LOGI("UpdateNotification common information"); - if (extra == "snooze") { - UpdateNotificationCommon(true); - } else { - UpdateNotificationCommon(false); - } - break; - } - case UpdateNotificationType::REMOVAL_WANT_AGENT: { - ANSR_LOGI("UpdateNotification removal_want_agent"); - AddRemovalWantAgent(); - break; - } - case UpdateNotificationType::WANT_AGENT: { - ANSR_LOGI("UpdateNotification want_agent"); - AppExecFwk::ElementName wantAgent("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName); - SetWantAgent(wantAgent); - SetExtraInfo(wantAgentInfo_->parameters); - break; - } - case UpdateNotificationType::MAX_SCREEN_WANT_AGENT: { - ANSR_LOGI("UpdateNotification max_screen_want_agent"); - AppExecFwk::ElementName maxScreenWantAgent( - "", maxScreenWantAgentInfo_->pkgName, maxScreenWantAgentInfo_->abilityName); - SetMaxScreenWantAgent(maxScreenWantAgent); - break; - } - case UpdateNotificationType::BUNDLE_INFO: { - ANSR_LOGI("UpdateNotification hap information"); - UpdateNotificationBundleInfo(); - break; - } - case UpdateNotificationType::CONTENT: { - break; - } - default: - break; + NotificationRequest notificationRequest(notificationId_); + return notificationRequest; +} + +void ReminderRequest::UpdateNotificationRequest(NotificationRequest& notificationRequest, const bool isSnooze) +{ + if (isSnooze) { + UpdateNotificationStateForSnooze(notificationRequest); + UpdateNotificationCommon(notificationRequest, true); + } else { + UpdateNotificationStateForAlert(notificationRequest); + UpdateNotificationCommon(notificationRequest, false); } + UpdateNotificationAddRemovalWantAgent(notificationRequest); + UpdateNotificationWantAgent(notificationRequest); + UpdateNotificationMaxScreenWantAgent(notificationRequest); + UpdateNotificationBundleInfo(notificationRequest); +} + +void ReminderRequest::UpdateNotificationWantAgent(NotificationRequest& notificationRequest) +{ + ANSR_LOGI("UpdateNotification want_agent"); + AppExecFwk::ElementName element("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName); + std::shared_ptr wantAgent = CreateWantAgent(element); + notificationRequest.SetWantAgent(wantAgent); + if (wantAgentInfo_->parameters.HasParam(PARAM_EXTRA_KEY)) { + std::shared_ptr extras = std::make_shared( + params.GetWantParams(PARAM_EXTRA_KEY)); + notificationRequest.SetAdditionalData(extras); + } +} + +void ReminderRequest::UpdateNotificationMaxScreenWantAgent(NotificationRequest& notificationRequest) +{ + AppExecFwk::ElementName element( + "", maxScreenWantAgentInfo_->pkgName, maxScreenWantAgentInfo_->abilityName); + std::shared_ptr wantAgent = CreateMaxWantAgent(element); + notificationRequest.SetMaxScreenWantAgent(wantAgent); } bool ReminderRequest::MarshallingActionButton(Parcel& parcel) const @@ -1289,20 +1282,6 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) return false; } - if (!InitNotificationRequest()) { - return false; - } - return true; -} - -bool ReminderRequest::InitNotificationRequest() -{ - notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); - if (notificationRequest_ == nullptr) { - ANSR_LOGE("Failed to create notification."); - return false; - } - displayContent_ = content_; return true; } @@ -1453,7 +1432,7 @@ std::string ReminderRequest::GetState(const uint8_t state) const return stateInfo; } -void ReminderRequest::AddActionButtons(const bool includeSnooze) +void ReminderRequest::AddActionButtons(NotificationRequest& notificationRequest, const bool includeSnooze) { int32_t requestCode = 10; std::vector flags; @@ -1503,12 +1482,13 @@ void ReminderRequest::AddActionButtons(const bool includeSnooze) std::shared_ptr actionButton = NotificationActionButton::Create(nullptr, title, buttonWantAgent); - notificationRequest_->AddActionButton(actionButton); + notificationRequest.AddActionButton(actionButton); } } -void ReminderRequest::AddRemovalWantAgent() +void ReminderRequest::UpdateNotificationAddRemovalWantAgent(NotificationRequest& notificationRequest) { + ANSR_LOGI("UpdateNotification removal_want_agent"); int32_t requestCode = 10; std::vector flags; flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); @@ -1530,7 +1510,7 @@ void ReminderRequest::AddRemovalWantAgent() AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, userId_); IPCSkeleton::SetCallingIdentity(identity); - notificationRequest_->SetRemovalWantAgent(wantAgent); + notificationRequest.SetRemovalWantAgent(wantAgent); } std::shared_ptr ReminderRequest::CreateWantAgent( @@ -1580,27 +1560,6 @@ std::shared_ptr ReminderRequest::CreateMax return wantAgent; } -void ReminderRequest::SetMaxScreenWantAgent(AppExecFwk::ElementName &element) -{ - std::shared_ptr wantAgent = CreateMaxWantAgent(element); - notificationRequest_->SetMaxScreenWantAgent(wantAgent); -} - -void ReminderRequest::SetWantAgent(AppExecFwk::ElementName &element) -{ - std::shared_ptr wantAgent = CreateWantAgent(element); - notificationRequest_->SetWantAgent(wantAgent); -} - -void ReminderRequest::SetExtraInfo(const AAFwk::WantParams& params) -{ - if (params.HasParam(PARAM_EXTRA_KEY)) { - std::shared_ptr extras = std::make_shared( - params.GetWantParams(PARAM_EXTRA_KEY)); - notificationRequest_->SetAdditionalData(extras); - } -} - void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string function) { uint8_t oldState = state_; @@ -1619,17 +1578,17 @@ void ReminderRequest::SetStateToInActive() "SetStateToInActive"); } -void ReminderRequest::UpdateActionButtons(const bool &setSnooze) +void ReminderRequest::UpdateActionButtons(NotificationRequest& notificationRequest, const bool &setSnooze) { if (notificationRequest_ == nullptr) { ANSR_LOGE("updateActionButtons failed, the notificationRequest is null"); return; } - notificationRequest_->ClearActionButtons(); + notificationRequest.ClearActionButtons(); if (setSnooze) { - AddActionButtons(false); + AddActionButtons(notificationRequest, false); } else { - AddActionButtons(true); + AddActionButtons(notificationRequest, true); } } @@ -1657,53 +1616,50 @@ bool ReminderRequest::UpdateNextReminder(const bool &force) return result; } -void ReminderRequest::UpdateNotificationCommon(bool isSnooze) +void ReminderRequest::UpdateNotificationCommon(NotificationRequest& notificationRequest, bool isSnooze) { + ANSR_LOGI("UpdateNotification common information"); time_t now; (void)time(&now); // unit is seconds. - notificationRequest_->SetDeliveryTime(GetDurationSinceEpochInMilli(now)); - notificationRequest_->SetLabel(NOTIFICATION_LABEL); - notificationRequest_->SetShowDeliveryTime(true); + notificationRequest.SetDeliveryTime(GetDurationSinceEpochInMilli(now)); + notificationRequest.SetLabel(NOTIFICATION_LABEL); + notificationRequest.SetShowDeliveryTime(true); if (isSnooze) { if (snoozeSlotType_ == NotificationConstant::SlotType::OTHER) { - notificationRequest_->SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); + notificationRequest.SetSlotType(NotificationConstant::SlotType::CONTENT_INFORMATION); } else { - notificationRequest_->SetSlotType(snoozeSlotType_); + notificationRequest.SetSlotType(snoozeSlotType_); } } else { - notificationRequest_->SetSlotType(slotType_); + notificationRequest.SetSlotType(slotType_); } - notificationRequest_->SetTapDismissed(tapDismissed_); - notificationRequest_->SetAutoDeletedTime(autoDeletedTime_); + notificationRequest.SetTapDismissed(tapDismissed_); + notificationRequest.SetAutoDeletedTime(autoDeletedTime_); auto notificationNormalContent = std::make_shared(); notificationNormalContent->SetText(displayContent_); notificationNormalContent->SetTitle(title_); auto notificationContent = std::make_shared(notificationNormalContent); - notificationRequest_->SetContent(notificationContent); + notificationRequest.SetContent(notificationContent); if ((reminderType_ == ReminderRequest::ReminderType::TIMER) || (reminderType_ == ReminderRequest::ReminderType::ALARM)) { - notificationRequest_->SetUnremovable(true); + notificationRequest.SetUnremovable(true); } } -void ReminderRequest::UpdateNotificationBundleInfo() +void ReminderRequest::UpdateNotificationBundleInfo(NotificationRequest& notificationRequest) { - notificationRequest_->SetOwnerUid(uid_); - notificationRequest_->SetCreatorUid(FOUDATION_UID); + notificationRequest.SetOwnerUid(uid_); + notificationRequest.SetCreatorUid(FOUDATION_UID); } -void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) +void ReminderRequest::UpdateNotificationContent(NotificationRequest& notificationRequest, const bool &setSnooze) { - if (notificationRequest_ == nullptr) { - ANSR_LOGE("updateNotificationContent failed, the notificationRequest is null"); - return; - } std::string extendContent = ""; if (setSnooze) { if (timeIntervalInMilli_ != 0) { // snooze the reminder by manual extendContent = snoozeContent_; - notificationRequest_->SetTapDismissed(false); + notificationRequest.SetTapDismissed(false); } else { // the reminder is expired now, when timeInterval is 0 extendContent = expiredContent_; @@ -1714,7 +1670,7 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) } else if (snoozeTimesDynamic_ != snoozeTimes_) { // the reminder is snoozing by period artithmetic, when the ring duration is over. extendContent = snoozeContent_; - notificationRequest_->SetTapDismissed(false); + notificationRequest.SetTapDismissed(false); } else { // the reminder has already snoozed by period arithmetic, when the ring duration is over. extendContent = expiredContent_; @@ -1727,18 +1683,18 @@ void ReminderRequest::UpdateNotificationContent(const bool &setSnooze) ANSR_LOGD("Display content=%{public}s", displayContent_.c_str()); } -void ReminderRequest::UpdateNotificationStateForAlert() +void ReminderRequest::UpdateNotificationStateForAlert(NotificationRequest& notificationRequest) { ANSR_LOGD("UpdateNotification content and buttons"); - UpdateNotificationContent(false); - UpdateActionButtons(false); + UpdateNotificationContent(notificationRequest, false); + UpdateActionButtons(notificationRequest, false); } -void ReminderRequest::UpdateNotificationStateForSnooze() +void ReminderRequest::UpdateNotificationStateForSnooze(NotificationRequest& notificationRequest) { ANSR_LOGD("UpdateNotification content and buttons"); - UpdateNotificationContent(true); - UpdateActionButtons(true); + UpdateNotificationContent(notificationRequest, true); + UpdateActionButtons(notificationRequest, true); } int32_t ReminderRequest::GetActualTime(const TimeTransferType &type, int32_t cTime) diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index 379b2cf74..76329a216 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -33,6 +33,7 @@ namespace OHOS { namespace Notification { +constexpr int32_t REMINDER_SERVICE_LOADSA_TIMEOUT_MS = 10000; ErrCode ReminderRequestClient::AddSlotByType(const NotificationConstant::SlotType &slotType) { sptr proxy = GetAnsManagerProxy(); @@ -184,24 +185,82 @@ sptr ReminderRequestClient::GetAnsManagerProxy() sptr ReminderRequestClient::GetReminderManagerProxy() { - auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); - if (!samgr) { - ANS_LOGE("Failed to get system ability mgr."); - return nullptr; + { + std::lock_guard lock(serviceLock_); + if (proxy_ != nullptr) { + return proxy_; + } + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ANS_LOGE("get samgr failed"); + return nullptr; + } + auto object = samgrProxy->CheckSystemAbility(1930); + if (object != nullptr) { + ANS_LOGE("get service succeeded"); + proxy_ = iface_cast(object); + return proxy_; + } } - sptr remoteObject = samgr->GetSystemAbility(1930); - if (!remoteObject) { - ANS_LOGE("Failed to get notification Manager."); - return nullptr; + ANS_LOGE("object is null"); + if (LoadReminderService()) { + std::lock_guard lock(serviceLock_); + if (proxy_ != nullptr) { + return proxy_; + } else { + ANS_LOGE("load reminder service failed"); + return nullptr; + } } + ANS_LOGE("load reminder service failed"); + return nullptr; +} - sptr proxy = iface_cast(remoteObject); - if ((!proxy) || (!proxy->AsObject())) { - ANS_LOGE("Failed to get notification Manager's proxy"); - return nullptr; +bool ReminderRequestClient::LoadReminderService() +{ + std::lock_guard lock(serviceLock_); + sptr loadCallback = sptr(new ReminderServiceCallback()); + if (loadCallback == nullptr) { + ANS_LOGE("loadCallback is nullptr."); + return false; } - return proxy; + + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ANS_LOGE("get samgr failed"); + return false; + } + + int32_t ret = samgrProxy->LoadSystemAbility(1930, loadCallback); + if (ret != ERR_OK) { + ANS_LOGE("Failed to Load systemAbility"); + return false; + } + + auto waitStatus = proxyConVar_.wait_for(lock, std::chrono::milliseconds(REMINDER_SERVICE_LOADSA_TIMEOUT_MS), + [this]() { return proxy_ != nullptr; }); + if (!waitStatus) { + ANS_LOGE("reminder service load sa timeout"); + return false; + } + return true; +} + +void ReminderRequestClient::LoadSystemAbilitySuccess(const sptr &remoteObject) +{ + HILOGI("ReminderRequestClient FinishStartSA"); + std::lock_guard lock(serviceLock_); + if (remoteObject != nullptr) { + Proxy_ = iface_cast(remoteObject); + proxyConVar_.notify_one(); + } +} + +void ReminderRequestClient::LoadSystemAbilityFail() +{ + std::lock_guard lock(serviceLock_); + dpProxy_ = nullptr; } } // namespace Notification diff --git a/frameworks/reminder/src/reminder_service_load_callback.cpp b/frameworks/reminder/src/reminder_service_load_callback.cpp new file mode 100644 index 000000000..c24c9492b --- /dev/null +++ b/frameworks/reminder/src/reminder_service_load_callback.cpp @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2024 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 "reminder_service_load_callback.h" + +#include "ans_log_wrapper.h" +#include "reminder_request_client.h" + +namespace OHOS { class IRemoteObject; } +namespace OHOS { +namespace Notification { + +const std::string TAG = "ReminderServiceLoadCallback"; + +void ReminderServiceCallback::OnLoadSystemAbilitySuccess( + int32_t systemAbilityId, const sptr &remoteObject) +{ + ReminderRequestClient::GetInstance().LoadSystemAbilitySuccess(remoteObject); + HILOGI("on load system ability success!"); +} + +void ReminderServiceCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) +{ + ReminderRequestClient::GetInstance().LoadSystemAbilityFail(); + HILOGI("on load system ability failed!"); +} +} +} \ No newline at end of file diff --git a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp index 4d4e655f8..e928c9683 100644 --- a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp @@ -178,10 +178,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00100, Function | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::COMMON; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = true; + reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } /** @@ -196,10 +195,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00200, Function | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = false; + reminderRequest->UpdateNotificationRequest(notificationRequest, false); } /** @@ -214,11 +212,11 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00300, Function | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); reminderRequest->wantAgentInfo_ = std::make_shared(); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::WANT_AGENT; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = true; + reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } /** @@ -233,11 +231,10 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00400, Function | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); reminderRequest->maxScreenWantAgentInfo_ = std::make_shared(); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = true; + reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } /** @@ -252,10 +249,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00500, Function | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::BUNDLE_INFO; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = true; + reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } /** @@ -269,9 +265,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00600, Function | { auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); - ReminderRequest::UpdateNotificationType type = ReminderRequest::UpdateNotificationType::CONTENT; - std::string extra = "aa"; - reminderRequest->UpdateNotificationRequest(type, extra); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); + bool isSnooze = true; + reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } /** @@ -286,7 +282,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00100, Function | SmallTest | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; ReminderRequest::ActionButtonType actionButtonType = ReminderRequest::ActionButtonType::CLOSE; ReminderRequest::ActionButtonInfo info; @@ -310,7 +306,7 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00200, Function | SmallTest | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; std::string pkgName = "bb"; std::string abilityName = "cc"; @@ -338,7 +334,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00100, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string stringData = "aa"; ReminderRequest::ActionButtonType buttonType = ReminderRequest::ActionButtonType::CLOSE; ReminderRequest::ActionButtonInfo info; @@ -348,7 +344,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00100, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(buttonType, info)); bool includeSnooze = true; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -363,7 +359,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00200, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; ReminderRequest::ActionButtonType actionButtonType = ReminderRequest::ActionButtonType::SNOOZE; ReminderRequest::ActionButtonInfo info; @@ -373,7 +369,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00200, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); bool includeSnooze = true; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -388,7 +384,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00300, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationIds = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationIds); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "title"; ReminderRequest::ActionButtonType actionButtonType_ = ReminderRequest::ActionButtonType::SNOOZE; ReminderRequest::ActionButtonInfo info; @@ -398,7 +394,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00300, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType_, info)); bool includeSnooze = false; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -413,7 +409,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00400, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; ReminderRequest::ActionButtonType actionButtonType = ReminderRequest::ActionButtonType::CUSTOM; ReminderRequest::ActionButtonInfo info; @@ -423,7 +419,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00400, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); bool includeSnooze = false; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -438,7 +434,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00500, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; std::string pkgName = "bb"; std::string abilityName = "cc"; @@ -452,7 +448,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00500, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); bool includeSnooze = false; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -467,7 +463,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00600, Function | SmallTest auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; ReminderRequest::ActionButtonType actionButtonType = ReminderRequest::ActionButtonType::INVALID; ReminderRequest::ActionButtonInfo info; @@ -477,7 +473,7 @@ HWTEST_F(ReminderRequestBranchTest, AddActionButtons_00600, Function | SmallTest reminderRequest->actionButtonMap_.insert( std::pair(actionButtonType, info)); bool includeSnooze = false; - reminderRequest->AddActionButtons(includeSnooze); + reminderRequest->AddActionButtons(notificationRequest, includeSnooze); } /** @@ -492,9 +488,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationCommon_00100, Function | S auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); reminderRequest->reminderType_ = ReminderRequest::ReminderType::TIMER; - reminderRequest->UpdateNotificationCommon(false); + reminderRequest->UpdateNotificationCommon(notificationRequest, false); } /** @@ -509,9 +505,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationCommon_00200, Function | S auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); reminderRequest->reminderType_ = ReminderRequest::ReminderType::ALARM; - reminderRequest->UpdateNotificationCommon(false); + reminderRequest->UpdateNotificationCommon(notificationRequest, false); } /** @@ -526,9 +522,9 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationCommon_00300, Function | S auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); reminderRequest->reminderType_ = ReminderRequest::ReminderType::INVALID; - reminderRequest->UpdateNotificationCommon(false); + reminderRequest->UpdateNotificationCommon(notificationRequest, false); } /** @@ -543,10 +539,10 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationBundleInfo_00100, Function auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string ownerName = ""; - reminderRequest->notificationRequest_->SetOwnerBundleName(ownerName); - reminderRequest->UpdateNotificationBundleInfo(); + notificationRequest.SetOwnerBundleName(ownerName); + reminderRequest->UpdateNotificationBundleInfo(notificationRequest); } /** @@ -561,10 +557,10 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationBundleInfo_00200, Function auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - reminderRequest->notificationRequest_ = new (std::nothrow) NotificationRequest(notificationId_); + auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string ownerName = "aa"; - reminderRequest->notificationRequest_->SetOwnerBundleName(ownerName); - reminderRequest->UpdateNotificationBundleInfo(); + notificationRequest.SetOwnerBundleName(ownerName); + reminderRequest->UpdateNotificationBundleInfo(notificationRequest); } } } diff --git a/frameworks/reminder/test/unittest/reminder_request_test.cpp b/frameworks/reminder/test/unittest/reminder_request_test.cpp index 0489d7cbb..dd88f24df 100644 --- a/frameworks/reminder/test/unittest/reminder_request_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_request_test.cpp @@ -931,28 +931,28 @@ HWTEST_F(ReminderRequestTest, Unmarshalling_00001, Function | SmallTest | Level1 } /** - * @tc.name: InitNotificationRequest_00001 - * @tc.desc: Test InitNotificationRequest parameters. + * @tc.name: CreateNotificationRequest_00001 + * @tc.desc: Test CreateNotificationRequest parameters. * @tc.type: FUNC * @tc.require: issueI5VB6V */ -HWTEST_F(ReminderRequestTest, InitNotificationRequest_00001, Function | SmallTest | Level1) +HWTEST_F(ReminderRequestTest, CreateNotificationRequest_00001, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); + EXPECT_EQ(rrc->CreateNotificationRequest(), nullptr); } /** - * @tc.name: InitNotificationRequest_00002 - * @tc.desc: Test InitNotificationRequest parameters. + * @tc.name: CreateNotificationRequest_00002 + * @tc.desc: Test CreateNotificationRequest parameters. * @tc.type: FUNC * @tc.require: issueI5VB6V */ -HWTEST_F(ReminderRequestTest, InitNotificationRequest_00002, Function | SmallTest | Level1) +HWTEST_F(ReminderRequestTest, CreateNotificationRequest_00002, Function | SmallTest | Level1) { auto rrc = std::make_shared(); rrc->SetNotificationId(100); - EXPECT_EQ(rrc->InitNotificationRequest(), true); + EXPECT_EQ(rrc->CreateNotificationRequest(), nullptr); } /** @@ -1112,9 +1112,10 @@ HWTEST_F(ReminderRequestTest, SetActionButton_00005, Function | SmallTest | Leve HWTEST_F(ReminderRequestTest, AddActionButtons_00001, Function | SmallTest | Level1) { std::shared_ptr reminderRequestChild = std::make_shared(); + NotificationRequest notificationRequest = reminderRequestChild->CreateNotificationRequest(); ASSERT_NE(nullptr, reminderRequestChild); - reminderRequestChild->AddActionButtons(true); - reminderRequestChild->AddActionButtons(false); + reminderRequestChild->AddActionButtons(notificationRequest, true); + reminderRequestChild->AddActionButtons(notificationRequest, false); } /** @@ -1206,10 +1207,9 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00002, Function | SmallT { auto rrc = std::make_shared(); rrc->SetNotificationId(100); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - - rrc->UpdateNotificationContent(true); - rrc->UpdateNotificationContent(false); + auto notification = rrc.CreateNotificationRequest(); + rrc->UpdateNotificationContent(notification, true); + rrc->UpdateNotificationContent(notification, false); Notification::ReminderRequest::TimeTransferType type = Notification::ReminderRequest::TimeTransferType::WEEK; int32_t actualTime = 1; @@ -1428,14 +1428,13 @@ HWTEST_F(ReminderRequestTest, RecoverWantAgent_00006, Function | SmallTest | Lev HWTEST_F(ReminderRequestTest, UpdateActionButtons_00001, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool setSnooze = true; rrc->SetSnoozeTimes(1); EXPECT_EQ(rrc->GetSnoozeTimes(), 1); rrc->SetSnoozeTimesDynamic(1); EXPECT_EQ(rrc->GetSnoozeTimesDynamic(), 1); - rrc->UpdateActionButtons(setSnooze); + rrc->UpdateActionButtons(notificationRequest, setSnooze); } /** @@ -1447,14 +1446,13 @@ HWTEST_F(ReminderRequestTest, UpdateActionButtons_00001, Function | SmallTest | HWTEST_F(ReminderRequestTest, UpdateActionButtons_00002, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool setSnooze = true; rrc->SetSnoozeTimes(0); EXPECT_EQ(rrc->GetSnoozeTimes(), 0); rrc->SetSnoozeTimesDynamic(1); EXPECT_EQ(rrc->GetSnoozeTimesDynamic(), 1); - rrc->UpdateActionButtons(setSnooze); + rrc->UpdateActionButtons(notificationRequest, setSnooze); } /** @@ -1466,14 +1464,13 @@ HWTEST_F(ReminderRequestTest, UpdateActionButtons_00002, Function | SmallTest | HWTEST_F(ReminderRequestTest, UpdateActionButtons_00003, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool setSnooze = false; rrc->SetSnoozeTimes(1); EXPECT_EQ(rrc->GetSnoozeTimes(), 1); rrc->SetSnoozeTimesDynamic(1); EXPECT_EQ(rrc->GetSnoozeTimesDynamic(), 1); - rrc->UpdateActionButtons(setSnooze); + rrc->UpdateActionButtons(notificationRequest, setSnooze); } /** @@ -1485,14 +1482,13 @@ HWTEST_F(ReminderRequestTest, UpdateActionButtons_00003, Function | SmallTest | HWTEST_F(ReminderRequestTest, UpdateActionButtons_00004, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool setSnooze = true; rrc->SetSnoozeTimes(1); EXPECT_EQ(rrc->GetSnoozeTimes(), 1); rrc->SetSnoozeTimesDynamic(0); EXPECT_EQ(rrc->GetSnoozeTimesDynamic(), 0); - rrc->UpdateActionButtons(setSnooze); + rrc->UpdateActionButtons(notificationRequest, setSnooze); } /** @@ -1504,14 +1500,13 @@ HWTEST_F(ReminderRequestTest, UpdateActionButtons_00004, Function | SmallTest | HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00300, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); uint32_t minTimeIntervalInSecond = 5 * 60; rrc->SetTimeInterval(1); EXPECT_EQ(rrc->GetTimeInterval(), minTimeIntervalInSecond); bool setSnooze = true; - rrc->UpdateNotificationContent(setSnooze); + rrc->UpdateNotificationContent(notificationRequest, setSnooze); } @@ -1524,8 +1519,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00300, Function | SmallT HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00400, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool deSet = true; uint8_t newState = 2; @@ -1535,7 +1529,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00400, Function | SmallT EXPECT_EQ(result1, 2); EXPECT_EQ(rrc->IsAlerting(), true); bool setSnooze = false; - rrc->UpdateNotificationContent(setSnooze); + rrc->UpdateNotificationContent(notificationRequest, setSnooze); } /** @@ -1548,8 +1542,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00600, Function | SmallT { // given auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); rrc->snoozeContent_ = "snooze"; rrc->content_ = "content"; rrc->expiredContent_ = "expiredContent"; @@ -1557,7 +1550,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00600, Function | SmallT // when bool setSnooze = true; - rrc->UpdateNotificationContent(setSnooze); + rrc->UpdateNotificationContent(notificationRequest, setSnooze); // then EXPECT_EQ(rrc->displayContent_, "snooze"); @@ -1573,8 +1566,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00800, Function | SmallT { // given auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); rrc->snoozeContent_ = "snooze"; rrc->content_ = "content"; rrc->expiredContent_ = "expiredContent"; @@ -1582,7 +1574,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00800, Function | SmallT // when bool setSnooze = true; - rrc->UpdateNotificationContent(setSnooze); + rrc->UpdateNotificationContent(notificationRequest, setSnooze); // then EXPECT_EQ(rrc->displayContent_, "expiredContent"); @@ -1597,8 +1589,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00800, Function | SmallT HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00500, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); bool deSet = false; uint8_t newState = 0; @@ -1614,7 +1605,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00500, Function | SmallT EXPECT_EQ(rrc->GetSnoozeTimesDynamic(), 1); bool setSnooze = false; - rrc->UpdateNotificationContent(setSnooze); + rrc->UpdateNotificationContent(notificationRequest, setSnooze); } /** @@ -1761,13 +1752,12 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00100, Function | SmallTe { // given auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); rrc->snoozeSlotType_ = NotificationConstant::SlotType::OTHER; bool isSnooze = true; // when - rrc->UpdateNotificationCommon(isSnooze); + rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::CONTENT_INFORMATION); @@ -1783,13 +1773,12 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00200, Function | SmallTe { // given auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); rrc->snoozeSlotType_ = NotificationConstant::SlotType::SERVICE_REMINDER; bool isSnooze = true; // when - rrc->UpdateNotificationCommon(isSnooze); + rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::SERVICE_REMINDER); @@ -1805,14 +1794,14 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00300, Function | SmallTe { // given auto rrc = std::make_shared(); - EXPECT_EQ(rrc->InitNotificationRequest(), true); - sptr ret = rrc->GetNotificationRequest(); + + NotificationRequest notificationRequest = rrc->CreateNotificationRequest(); rrc->snoozeSlotType_ = NotificationConstant::SlotType::SERVICE_REMINDER; rrc->slotType_ = NotificationConstant::SlotType::SOCIAL_COMMUNICATION; bool isSnooze = false; // when - rrc->UpdateNotificationCommon(isSnooze); + rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::SOCIAL_COMMUNICATION); diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index badd5a103..cffb2efae 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -355,13 +355,6 @@ public: */ std::string GetGroupId() const; - /** - * @brief Obtains notification request. - * - * @return notification request instance. - */ - sptr GetNotificationRequest() const; - /** * @brief Obtains reminder id. * @@ -887,10 +880,10 @@ public: * For example, action button should not init until the reminder is published successfully, as the reminder id is * assigned after that. * - * @param type Indicates the update type. - * @param extra Indicates the extra content. + * @param notificationRequest notificationRequest. + * @param isSnooze isSnooze */ - void UpdateNotificationRequest(UpdateNotificationType type, std::string extra); + void UpdateNotificationRequest(NotificationRequest& notificationRequest, bool isSnooze); /** * @brief Get repeated days of the week. @@ -1046,9 +1039,10 @@ protected: uint64_t GetTriggerTime(const time_t now, const time_t nextTriggerTime) const; uint64_t GetNowInstantMilli() const; + NotificationRequest CreateNotificationRequest(); + private: - void AddActionButtons(const bool includeSnooze); - void AddRemovalWantAgent(); + std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; std::shared_ptr CreateMaxWantAgent(AppExecFwk::ElementName &element) const; std::string GetShowTime(const uint64_t showTime) const; @@ -1061,10 +1055,15 @@ private: void SetState(bool deSet, const uint8_t newState, std::string function); void SetWantAgent(AppExecFwk::ElementName &element); void SetExtraInfo(const AAFwk::WantParams& params); - void UpdateActionButtons(const bool &setSnooze); + void UpdateActionButtons(NotificationRequest& notificationRequest, const bool &setSnooze); bool UpdateNextReminder(const bool &force); - void UpdateNotificationContent(const bool &setSnooze); - void UpdateNotificationCommon(bool isSnooze); + void AddActionButtons(NotificationRequest& notificationRequest, const bool includeSnooze); + void UpdateNotificationContent(NotificationRequest& notificationRequest, const bool &setSnooze); + void UpdateNotificationCommon(NotificationRequest& notificationRequest, bool isSnooze); + void UpdateNotificationAddRemovalWantAgent(NotificationRequest& notificationRequest); + void UpdateNotificationWantAgent(NotificationRequest& notificationRequest); + void UpdateNotificationMaxScreenWantAgent(NotificationRequest& notificationRequest); + void UpdateNotificationBundleInfo(NotificationRequest& notificationRequest); /** * @brief Determine whether it is repeated every week. @@ -1073,26 +1072,19 @@ private: */ bool IsRepeatDaysOfWeek(int32_t day) const; - /** - * @brief Used for reminder recovery from database. - * - * @param bundleName Indicates the third part bundle name. - */ - void UpdateNotificationBundleInfo(); - /** * @brief Update the notification, which will be shown for the "Alerting" reminder. * 1. Update the notification label/content. * 2. Restore the snooze action button. */ - void UpdateNotificationStateForAlert(); + void UpdateNotificationStateForAlert(NotificationRequest& notificationRequest); /** * @brief Update the notification, which will be shown when user do a snooze. * 1. Update the notification label/content. * 2. Remove the snooze action button. */ - void UpdateNotificationStateForSnooze(); + void UpdateNotificationStateForSnooze(NotificationRequest& notificationRequest); bool MarshallingWantParameters(Parcel& parcel, const AAFwk::WantParams& params) const; bool MarshallingActionButton(Parcel& parcel) const; @@ -1139,15 +1131,15 @@ private: ReminderType reminderType_ {ReminderType::INVALID}; NotificationConstant::SlotType slotType_ {NotificationConstant::SlotType::SOCIAL_COMMUNICATION}; NotificationConstant::SlotType snoozeSlotType_ {NotificationConstant::SlotType::OTHER}; - sptr notificationRequest_ = nullptr; std::shared_ptr wantAgentInfo_ = nullptr; std::shared_ptr maxScreenWantAgentInfo_ = nullptr; std::map actionButtonMap_ {}; + std::vector> actionButtons_ {}; std::string wantAgentStr_{}; std::string maxWantAgentStr_{}; - sptr notificationOption_ {nullptr}; + // sptr notificationOption_ {nullptr}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/reminder_request_alarm.h b/interfaces/inner_api/reminder_request_alarm.h index ab24c8984..8a8d39a74 100644 --- a/interfaces/inner_api/reminder_request_alarm.h +++ b/interfaces/inner_api/reminder_request_alarm.h @@ -110,7 +110,7 @@ public: */ bool ReadFromParcel(Parcel &parcel) override; - ReminderRequestAlarm() : ReminderRequest() {}; + ReminderRequestAlarm() : ReminderRequest(ReminderType::ALARM) {}; protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index e3167afae..fe51354db 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -313,7 +313,7 @@ public: */ uint64_t GetLastStartDateTime() const; - ReminderRequestCalendar() : ReminderRequest() {}; + ReminderRequestCalendar() : ReminderRequest(ReminderType::CALENDAR) {}; public: static constexpr uint8_t MAX_MONTHS_OF_YEAR = 12; diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index 6c99b594c..2723bb67c 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -22,6 +22,7 @@ #include "notification_constant.h" #include "ans_manager_interface.h" #include "ireminder_manager.h" +#include "ffrt.h" namespace OHOS { namespace Notification { @@ -124,6 +125,14 @@ private: sptr GetReminderManagerProxy(); + bool LoadReminderService(); + + ffrt::mutex serviceLock_; + + std::condition_variable proxyConVar_; + + sptr dpProxy_; + }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/reminder_request_timer.h b/interfaces/inner_api/reminder_request_timer.h index 4e89b48a0..a3e39351a 100644 --- a/interfaces/inner_api/reminder_request_timer.h +++ b/interfaces/inner_api/reminder_request_timer.h @@ -71,7 +71,7 @@ public: bool ReadFromParcel(Parcel &parcel) override; - ReminderRequestTimer() {}; + ReminderRequestTimer() : ReminderRequest(ReminderType::TIMER) {}; protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) override; diff --git a/interfaces/inner_api/reminder_service_load_callback.h b/interfaces/inner_api/reminder_service_load_callback.h new file mode 100644 index 000000000..4aa59c1f3 --- /dev/null +++ b/interfaces/inner_api/reminder_service_load_callback.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2024 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_REMINDER_SERVICE_CALLBACK_H +#define OHOS_REMINDER_SERVICE_CALLBACK_H + +#include +#include + +#include "refbase.h" +#include "system_ability_load_callback_stub.h" + +namespace OHOS { class IRemoteObject; } +namespace OHOS { +namespace Notification { +class ReminderServiceCallback : public SystemAbilityLoadCallbackStub { +public: + void OnLoadSystemAbilitySuccess(int32_t systemAbilityId, + const sptr &remoteObject) override; + void OnLoadSystemAbilityFail(int32_t systemAbilityId) override; +}; +} +} +#endif \ No newline at end of file diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index c60b77149..8e4fd740b 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -275,6 +275,10 @@ public: */ bool IsSystemReady(); + int32_t QueryActiveReminderCount(); + + void ReceiveLoadReminderEvent(); + static constexpr uint8_t TIME_ZONE_CHANGE = 0; static constexpr uint8_t DATE_TIME_CHANGE = 1; @@ -595,7 +599,7 @@ private: */ void UpdateAndSaveReminderLocked(const sptr &reminder); - void UpdateNotification(const sptr &reminder, bool isSnooze); + NotificationRequest CreateNotificationRequest(const sptr &reminder, bool isSnooze); static bool cmp(sptr &reminderRequest, sptr &other); diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h index ed81520b0..d04c78d29 100644 --- a/services/reminder/include/reminder_service.h +++ b/services/reminder/include/reminder_service.h @@ -110,11 +110,23 @@ public: * @return Returns ERR_OK on success, others on failure. */ ErrCode GetExcludeDates(const int32_t reminderId, std::vector& dates) override; + + void TryPostDelayUnloadTask(int64_t delayTime); private: ReminderService() = default; + + void PostDelayUnloadTask(); + + sptr CreateTarReminderRequest(const ReminderRequest &reminder); + + ErrCode InitReminderRequest(sptr& tarReminder, const std::string& bundle, + const int32_t callingUid); private: + ffrt::task_handle unloadTask_ = nullptr; static sptr instance_; static std::mutex instanceMutex_; + + static std::mutex unloadMutex_; }; } // namespace Notification } // namespace OHOS diff --git a/services/reminder/include/reminder_store.h b/services/reminder/include/reminder_store.h index 864674164..03d365e34 100644 --- a/services/reminder/include/reminder_store.h +++ b/services/reminder/include/reminder_store.h @@ -39,7 +39,8 @@ public: int32_t DeleteUser(const int32_t userId); int32_t UpdateOrInsert(const sptr& reminder); int32_t GetMaxId(); - std::vector> GetAllValidReminders(); + int32_t QueryActiveReminderCount(); + std::vector> GetHalfHourReminders(); public: static void GetUInt8Val(const std::shared_ptr& resultSet, @@ -84,6 +85,7 @@ private: std::shared_ptr Query(const std::string& tableName, const std::string& colums, const int32_t reminderId); std::shared_ptr Query(const std::string& queryCondition) const; + private: std::shared_ptr rdbStore_ = nullptr; diff --git a/services/reminder/sa_profile/1930.json b/services/reminder/sa_profile/1930.json index 289b0e338..e2a78eb6b 100644 --- a/services/reminder/sa_profile/1930.json +++ b/services/reminder/sa_profile/1930.json @@ -4,10 +4,14 @@ { "name": 1930, "libpath": "libreminder.z.so", - "run-on-create": true, - "depend_time_out": 60000, + "run-on-create": false, "distributed": false, - "dump_level": 1 + "dump_level": 1, + "commonevent":[ + { + "name":"usual.event.BOOT_COMPLETED" + } + ] } ] } diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 3d2af1417..77a57eca0 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -63,6 +63,8 @@ const int REASON_APP_API = 1; const int INDEX_KEY = 0; const int INDEX_TYPE = 1; const int INDEX_VALUE = 2; +const int64_t ONE_MIN_TIME = 60 * 1000; +const int64_t HALF_HOUR = 30 * ONE_MIN_TIME; } /** @@ -307,11 +309,6 @@ void ReminderDataManager::CancelNotification(const sptr &remind ANSR_LOGD("No need to cancel notification"); return; } - sptr notification = reminder->GetNotificationRequest(); - if (notification == nullptr) { - ANSR_LOGW("Cancel notification fail"); - return; - } ANSR_LOGD("Cancel notification"); std::string identity = IPCSkeleton::ResetCallingIdentity(); NotificationHelper::CancelNotification(ReminderRequest::NOTIFICATION_LABEL, reminder->GetNotificationId()); @@ -566,19 +563,58 @@ std::shared_ptr ReminderDataManager::InitInstance() REMINDER_DATA_MANAGER = std::make_shared(); ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); } + StartReminderLoadTimer(); return REMINDER_DATA_MANAGER; } -// std::shared_ptr ReminderDataManager::InitInstance( -// const sptr &advancedNotificationService) -// { -// if (REMINDER_DATA_MANAGER == nullptr) { -// REMINDER_DATA_MANAGER = std::make_shared(); -// // REMINDER_DATA_MANAGER->advancedNotificationService_ = advancedNotificationService; -// ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); -// } -// return REMINDER_DATA_MANAGER; -// } +void ReminderDataManager::StartReminderLoadTimer() +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + REMINDER_CHECK_NULL_VOID(timer, "Get timeServiceClient failed"); + std::lock_guard locker(timeLoadMutex_); + if (reminderLoadtimerId_ == 0) { + reminderLoadtimerId_ = CreateReminderLoadTimer(timer); + } + timer->StopTimer(reminderLoadtimerId_); + uint64_t nowMilli = GetCurrentTime() + HALF_HOUR; + timer->StartTimer(reminderLoadtimerId_, nowMilli); +} + +int64_t ReminderDataManager::CreateReminderLoadTimer(const sptr timer) +{ + auto sharedTimerInfo = std::make_shared(); + if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { + ANSR_LOGE("Failed to set timer type."); + return nullptr; + } + sharedTimerInfo->SetRepeat(false); + sharedTimerInfo->SetInterval(0); + int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); + sharedTimerInfo->SetType(timerType); + + int32_t requestCode = 10; + std::vector flags; + flags.push_back(AbilityRuntime::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + + auto want = std::make_shared(); + want->SetAction(ReminderRequest::REMINDER_EVENT_LOAD_REMINDER); + std::vector> wants; + wants.push_back(want); + AbilityRuntime::WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + AbilityRuntime::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, wants, nullptr); + + std::string identity = IPCSkeleton::ResetCallingIdentity(); + std::shared_ptr wantAgent = + AbilityRuntime::WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo, 0); + IPCSkeleton::SetCallingIdentity(identity); + + sharedTimerInfo->SetWantAgent(wantAgent); + return timer->CreateTimer(sharedTimerInfo); +} + + bool ReminderDataManager::CheckUpdateConditions(const sptr &reminder, const ReminderRequest::ActionButtonType &actionButtonType, @@ -787,11 +823,9 @@ void ReminderDataManager::TerminateAlerting(const sptr &reminde } int32_t reminderId = reminder->GetReminderId(); int32_t uid = reminder->GetUid(); - sptr notificationRequest = reminder->GetNotificationRequest(); ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); - UpdateNotification(reminder, false); - NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); - // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); + NotificationRequest notificationRequest = CreateNotificationRequest(reminder, false); + NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, notificationRequest); store_->UpdateOrInsert(reminder); } @@ -997,7 +1031,6 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co ANSR_LOGD("Show the reminder(Play sound: %{public}d), %{public}s", static_cast(isNeedToPlaySound), reminder->Dump().c_str()); int32_t reminderId = reminder->GetReminderId(); - sptr notificationRequest = reminder->GetNotificationRequest(); if (!IsAllowedNotify(reminder)) { ANSR_LOGE("Not allow to notify."); reminder->OnShow(false, isSysTimeChanged, false); @@ -1008,14 +1041,12 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co bool toPlaySound = isNeedToPlaySound && ShouldAlert(reminder) ? true : false; reminder->OnShow(toPlaySound, isSysTimeChanged, true); AddToShowedReminders(reminder); - UpdateNotification(reminder, false); // this should be called after OnShow + NotificationRequest notificationRequest = CreateNotificationRequest(reminder, false); // this should be called after OnShow if (alertingReminderId_ != -1) { TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); } - ErrCode errCode = NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); - // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - // ErrCode errCode = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + ErrCode errCode = NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, notificationRequest); if (errCode != ERR_OK) { reminder->OnShowFail(); RemoveFromShowedReminders(reminder); @@ -1037,17 +1068,10 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co } } -void ReminderDataManager::UpdateNotification(const sptr &reminder, bool isSnooze) +NotificationRequest ReminderDataManager::CreateNotificationRequest(const sptr &reminder, bool isSnooze) { - if (isSnooze) { - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, "snooze"); - } else { - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); - } - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::MAX_SCREEN_WANT_AGENT, ""); - reminder->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::BUNDLE_INFO, ""); + NotificationRequest notificationRequest = reminder->CreateNotificationRequest(); + reminder->UpdateNotificationRequest(notificationRequest, isSnooze); } void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) @@ -1085,14 +1109,9 @@ void ReminderDataManager::SnoozeReminderImpl(sptr &reminder) store_->UpdateOrInsert(reminder); // 2) Show the notification dialog in the systemUI - sptr notificationRequest = reminder->GetNotificationRequest(); ANSR_LOGD("publish(update) notification.(reminderId=%{public}d)", reminder->GetReminderId()); - UpdateNotification(reminder, true); - // // Set the notification SoundEnabled and VibrationEnabled by soltType - // advancedNotificationService_->SetRequestBySlotType(notificationRequest, bundleOption); - - // advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, *notificationRequest); + NotificationRequest notificationRequest = CreateNotificationRequest(reminder, true); + NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, notificationRequest); StartRecentReminder(); } @@ -1436,22 +1455,16 @@ bool ReminderDataManager::IsBelongToSameApp(const int32_t uidSrc, return result; } +void ReminderDataManager::ReceiveLoadReminderEvent() +{ + LoadReminderFromDb(); +} + void ReminderDataManager::LoadReminderFromDb() { std::lock_guard lock(ReminderDataManager::MUTEX); - std::vector> existReminders = store_->GetAllValidReminders(); + std::vector> existReminders = store_->GetHalfHourReminders(); reminderVector_ = existReminders; - ANSR_LOGD("LoadReminderFromDb, reminder size=%{public}zu", reminderVector_.size()); - // for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { - // // sptr bundleOption = new (std::nothrow) NotificationBundleOption(); - // // if (bundleOption == nullptr) { - // // ANS_LOGE("Failed to create bundle option due to low memory."); - // // return; - // // } - // // bundleOption->SetBundleName((*it)->GetBundleName()); - // // bundleOption->SetUid((*it)->GetUid()); - // // (*it)->SetNotificationBundleOption(bundleOption); - // } totalCount_ = static_cast(reminderVector_.size()); ReminderRequest::GLOBAL_ID = store_->GetMaxId() + 1; } @@ -1972,5 +1985,10 @@ void ReminderDataManager::CheckNeedNotifyStatus(const sptr &rem ANSR_LOGI("notify reminder status change %{public}s", bundleName.c_str()); } } + +int32_t ReminderDataManager::QueryActiveReminderCount() +{ + return store_->QueryActiveReminderCount(); +} } } diff --git a/services/reminder/src/reminder_event_manager.cpp b/services/reminder/src/reminder_event_manager.cpp index 51a6ef21e..addb0884a 100644 --- a/services/reminder/src/reminder_event_manager.cpp +++ b/services/reminder/src/reminder_event_manager.cpp @@ -174,6 +174,10 @@ void ReminderEventManager::ReminderEventCustomSubscriber::OnReceiveEvent(const E reminderDataManager_->ClickReminder(want); return; } + if (action == ReminderRequest::REMINDER_EVENT_LOAD_REMINDER) { + reminderDataManager_->ReceiveLoadReminderEvent(); + return; + } } void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFwk::CommonEventData &data) diff --git a/services/reminder/src/reminder_notification_inline.cpp b/services/reminder/src/reminder_notification_inline.cpp index a981b64a4..222a12560 100644 --- a/services/reminder/src/reminder_notification_inline.cpp +++ b/services/reminder/src/reminder_notification_inline.cpp @@ -32,6 +32,21 @@ namespace OHOS { namespace Notification { +#define REMINDER_CHECK_NULL_VOID(ptr, msg) \ + do { \ + if (ptr == nullptr) { \ + ANSR_LOGW("%{public}s", msg); \ + return; \ + } \ + } while(0) + +#define REMINDER_CHECK_NULL_RETURN(ptr, msg, ret) \ + do { \ + if (ptr == nullptr) { \ + ANSR_LOGW("%{public}s", msg); \ + return ret; \ + } \ + } while(0) inline std::string GetClientBundleNameByUid(int32_t callingUid) { std::string bundle; diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index 353f0771a..5845f8d3b 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -48,6 +48,7 @@ namespace OHOS { namespace Notification { +constexpr int64_t DELAY_TIME = 60 * 1000 * 1000; sptr ReminderService::instance_; std::mutex ReminderService::instanceMutex_; sptr ReminderService::GetInstance() @@ -77,6 +78,45 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ { HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGI("Publish reminder"); + sptr tarReminder = CreateTarReminderRequest(reminder); + if (!tarReminder) { + ANSR_LOGE("ReminderRequest object is nullptr"); + return ERR_ANS_INVALID_PARAM; + } + int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::string bundle = GetClientBundleName(); + if (!CheckReminderPermission()) { + ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); + return ERR_REMINDER_PERMISSION_DENIED; + } + bool isAllowUseReminder = false; + NotificationHelper::AllowUseReminder(bundle, isAllowUseReminder); + if (isAllowUseReminder) { + ANSR_LOGW("The number of reminders exceeds the limit[0]."); + return ERR_REMINDER_NUMBER_OVERLOAD; + } + InitReminderRequest(tarReminder, bundle, callingUid); + auto bundleOption = CreateBundleOption(tarReminder->GetBundleName(), tarReminder->GetUid()); + bool allowedNotify = false; + ErrCode result = NotificationHelper::IsAllowedNotify(bundleOption, allowedNotify); + if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { + ANSR_LOGW("The application does not request enable notification"); + return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; + } + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + return ERR_NO_INIT; + } + int32_t ret = rdm->PublishReminder(tarReminder, callingUid); + if (ret == ERR_OK) { + reminderId = tarReminder->GetReminderId(); + } + TryPostDelayUnloadTask(DELAY_TIME); + return ret; +} + +sptr ReminderService::CreateTarReminderRequest(const ReminderRequest &reminder) +{ sptr tarReminder = nullptr; switch (reminder.GetReminderType()) { case (ReminderRequest::ReminderType::TIMER): { @@ -99,28 +139,16 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ } default: { ANSR_LOGW("PublishReminder fail."); - return ERR_ANS_INVALID_PARAM; } } - if (!tarReminder) { - ANSR_LOGE("ReminderRequest object is nullptr"); - return ERR_ANS_INVALID_PARAM; - } - int32_t callingUid = IPCSkeleton::GetCallingUid(); - std::string bundle = GetClientBundleName(); - if (!CheckReminderPermission()) { - ANSR_LOGW("Permission denied: ohos.permission.PUBLISH_AGENT_REMINDER"); - return ERR_REMINDER_PERMISSION_DENIED; - } - bool isAllowUseReminder = false; - NotificationHelper::AllowUseReminder(bundle, isAllowUseReminder); - if (isAllowUseReminder) { - ANSR_LOGW("The number of reminders exceeds the limit[0]."); - return ERR_REMINDER_NUMBER_OVERLOAD; - } + return tarReminder; +} + +ErrCode ReminderService::InitReminderRequest(sptr& tarReminder, + const std::string& bundle, const int32_t callingUid) +{ ANSR_LOGD("is system app: %{public}d", ReminderAccessTokenHelper::IsSystemApp()); tarReminder->SetSystemApp(ReminderAccessTokenHelper::IsSystemApp()); - sptr notificationRequest = reminder.GetNotificationRequest(); tarReminder->InitCreatorBundleName(bundle); tarReminder->InitCreatorUid(callingUid); if (tarReminder->GetWantAgentInfo() == nullptr || tarReminder->GetMaxScreenWantAgentInfo() == nullptr) { @@ -153,22 +181,6 @@ ErrCode ReminderService::PublishReminder(const ReminderRequest &reminder, int32_ tarReminder->InitUserId(activeUserId); tarReminder->InitUid(ReminderBundleManagerHelper::GetInstance()->GetDefaultUidByBundleName( tarReminder->GetBundleName(), tarReminder->GetUserId())); - auto bundleOption = CreateBundleOption(tarReminder->GetBundleName(), tarReminder->GetUid()); - bool allowedNotify = false; - ErrCode result = NotificationHelper::IsAllowedNotify(bundleOption, allowedNotify); - if (!tarReminder->IsSystemApp() && (result != ERR_OK || !allowedNotify)) { - ANSR_LOGW("The application does not request enable notification"); - return ERR_REMINDER_NOTIFICATION_NOT_ENABLE; - } - auto rdm = ReminderDataManager::GetInstance(); - if (rdm == nullptr) { - return ERR_NO_INIT; - } - int32_t ret = rdm->PublishReminder(tarReminder, callingUid); - if (ret == ERR_OK) { - reminderId = tarReminder->GetReminderId(); - } - return ret; } ErrCode ReminderService::CancelReminder(const int32_t reminderId) @@ -184,7 +196,9 @@ ErrCode ReminderService::CancelReminder(const int32_t reminderId) if (rdm == nullptr) { return ERR_NO_INIT; } - return rdm->CancelReminder(reminderId, callingUid); + ErrCode result = rdm->CancelReminder(reminderId, callingUid); + TryPostDelayUnloadTask(DELAY_TIME); + return result; } ErrCode ReminderService::CancelAllReminders() @@ -202,7 +216,9 @@ ErrCode ReminderService::CancelAllReminders() if (rdm == nullptr) { return ERR_NO_INIT; } - return rdm->CancelAllReminders(userId, callingUid); + ErrCode result = rdm->CancelAllReminders(userId, callingUid); + TryPostDelayUnloadTask(DELAY_TIME); + return result; } @@ -223,6 +239,7 @@ ErrCode ReminderService::GetValidReminders(std::vector &reminde } rdm->GetValidReminders(callingUid, reminders); ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); + TryPostDelayUnloadTask(DELAY_TIME); return ERR_OK; } @@ -240,7 +257,9 @@ ErrCode ReminderService::AddExcludeDate(const int32_t reminderId, const int64_t ANSR_LOGW("Reminder data manager not init!"); return ERR_NO_INIT; } - return rdm->AddExcludeDate(reminderId, date, callingUid); + ErrCode result = rdm->AddExcludeDate(reminderId, date, callingUid); + TryPostDelayUnloadTask(DELAY_TIME); + return result; } ErrCode ReminderService::DelExcludeDates(const int32_t reminderId) @@ -258,7 +277,9 @@ ErrCode ReminderService::DelExcludeDates(const int32_t reminderId) ANSR_LOGW("Reminder data manager not init!"); return ERR_NO_INIT; } - return rdm->DelExcludeDates(reminderId, callingUid); + ErrCode result = rdm->DelExcludeDates(reminderId, callingUid); + TryPostDelayUnloadTask(DELAY_TIME); + return result; } ErrCode ReminderService::GetExcludeDates(const int32_t reminderId, std::vector& dates) @@ -275,7 +296,45 @@ ErrCode ReminderService::GetExcludeDates(const int32_t reminderId, std::vectorGetExcludeDates(reminderId, callingUid, dates); + ErrCode result = rdm->GetExcludeDates(reminderId, callingUid, dates); + TryPostDelayUnloadTask(DELAY_TIME); + return result; +} + +void ReminderService::TryPostDelayUnloadTask(int64_t delayTime) +{ + std::lock_guard lock(unloadMutex_); + if (tryUnloadTask_) { + ffrt::skip(tryUnloadTask_); + } + tryUnloadTask_ = ffrt::submit_h([]() { + auto rdm = ReminderDataManager::GetInstance(); + if (rdm == nullptr) { + ANSR_LOGW("Reminder data manager not init!"); + return; + } + int32_t reminderCount = rdm->QueryActiveReminderCount(); + if (reminderCount > 0) { + return; + } + PostDelayUnloadTask(); + }, {}, {}, ffrt::task_attr().delay(delayTime)); + +} + +void ReminderService::PostDelayUnloadTask() +{ + ANSR_LOGI("do unload task"); + auto samgrProxy = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgrProxy == nullptr) { + ANSR_LOGE("get samgr failed"); + return; + } + int32_t ret = samgrProxy->UnloadSystemAbility(1930); + if (ret != ERR_OK) { + ANSR_LOGE("remove system ability failed"); + return; + } } } // namespace Notification } // namespace OHOS diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp index 89407e4a8..e98247dbf 100644 --- a/services/reminder/src/reminder_service_ability.cpp +++ b/services/reminder/src/reminder_service_ability.cpp @@ -25,6 +25,7 @@ REGISTER_SYSTEM_ABILITY_BY_ID(ReminderServiceAbility, 1930, true); const std::string EXTENSION_BACKUP = "backup"; const std::string EXTENSION_RESTORE = "restore"; +constexpr int64_t INIT_DELAY_TIME = 0; ReminderServiceAbility::ReminderServiceAbility(const int32_t systemAbilityId, bool runOnCreate) : SystemAbility(systemAbilityId, runOnCreate), service_(nullptr) @@ -44,6 +45,7 @@ void ReminderServiceAbility::OnStart() return; } reminderAgent_ = ReminderDataManager::InitInstance(); + ReminderService::GetInstance()->TryPostDelayUnloadTask(INIT_DELAY_TIME); } void ReminderServiceAbility::OnStop() diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index 363e37217..d1aecc642 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -28,6 +28,7 @@ #include "reminder_request_timer.h" #include "reminder_request_calendar.h" #include "reminder_store_strategy.h" +#include "reminder_notification_inline.cpp" namespace OHOS { namespace Notification { @@ -39,6 +40,8 @@ const int32_t REMINDER_RDB_VERSION_V4 = 4; const int32_t REMINDER_RDB_VERSION_V5 = 5; const int32_t REMINDER_RDB_VERSION_V6 = 6; const int32_t REMINDER_RDB_VERSION = 7; +const int64_t ONE_MIN_TIME = 60 * 1000; +const int64_t HALF_HOUR = 30 * ONE_MIN_TIME; } const int32_t ReminderStore::STATE_OK = 0; @@ -414,11 +417,21 @@ int32_t ReminderStore::GetMaxId() return maxId; } -__attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() +__attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetHalfHourReminders() { - std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " - + ReminderBaseTable::TABLE_NAME + " WHERE " - + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " + int64_t nowTime = GetCurrentTime(); + std::string sql = "SELECT * FROM " + + ReminderBaseTable::TABLE_NAME + " WHERE (" + + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::IS_EXPIRED + " = 'false' AND " + + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::REMINDER_TYPE + " != 1 AND " + + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::TRIGGER_TIME + " < " + + std::to_string(nowTime + HALF_HOUR) + ") OR " + + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::REMINDER_ID + " IN " + + "(SELECT" + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderCalendarTable::TABLE_NAME + + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::CALENDAR_DATE_TIME + " < " + + std::to_string(nowTime + HALF_HOUR) + " AND " + + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::CALENDAR_DATE_TIME + " > " + + std::to_string(nowTime) +") ORDER BY " + ReminderBaseTable::TRIGGER_TIME + " ASC"; ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); return GetReminders(sql); @@ -803,5 +816,28 @@ std::shared_ptr ReminderStore::Query(const std::string& qu std::vector whereArgs; return rdbStore_->QuerySql(queryCondition, whereArgs); } + +int32_t ReminderStore::QueryActiveReminderCount() const +{ + REMINDER_CHECK_NULL_RETURN(rdbStore_, "Rdb store is not initialized.", 0); + std::string queryCondition = "SELECT * FROM "; + queryCondition.append(ReminderBaseTable::TABLE_NAME).append(" WHERE ").append(ReminderBaseTable::IS_EXPIRED) + .append(" = 'true' AND ").append(REMINDER_TYPE).append(" != 1"); + std::vector whereArgs; + auto resultSet = rdbStore_->QuerySql(queryCondition, whereArgs); + int32_t baseTableNum = 0; + resultSet->GetRowCount(baseTableNum); + + std::string queryCondition = "SELECT * FROM "; + int64_t nowTime = GetCurrentTime(); + queryCondition.append(ReminderCalendarTable::TABLE_NAME).append(" WHERE (") + .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append(" < ").append(std::to_string(nowTime)).append(" AND ") + .append(CALENDAR_END_DATE_TIME).append(" > ").append(std::to_string(nowTime)).append(" ) OR ") + .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append("> ").append(std::to_string(nowTime)); + resultSet = rdbStore_->QuerySql(queryCondition, whereArgs); + int32_t calenderTableNum = 0; + resultSet->GetRowCount(calenderTableNum); + return baseTableNum + calenderTableNum +} } // namespace Notification } // namespace OHOS diff --git a/services/reminder/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp index 148a3f2ee..e3020d6bb 100644 --- a/services/reminder/test/unittest/reminder_data_manager_test.cpp +++ b/services/reminder/test/unittest/reminder_data_manager_test.cpp @@ -246,7 +246,7 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_009, Level1) { int32_t callingUid = -1; sptr reminder = new ReminderRequestTimer(10); - manager->UpdateAndSaveReminderLocked(reminder, callingUid); + manager->UpdateAndSaveReminderLocked(reminder); sptr service(new ReminderService); manager->ShouldAlert(nullptr); manager->currentUserId_ = 0; diff --git a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp index bfbb20638..87208f8df 100644 --- a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp @@ -154,7 +154,7 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_17900, Function int32_t reminderId = 1; ReminderRequest reminder; - reminder.InitNotificationRequest(); + reminder.CreateNotificationRequest(); ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; @@ -173,7 +173,6 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_18000, Function MockIsNonBundleName(true); int32_t reminderId = 1; ReminderRequest reminder; - reminder.InitNotificationRequest(); ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_ANS_INVALID_BUNDLE); MockIsNonBundleName(false); GTEST_LOG_(INFO) << "GetAppTargetBundle_2000 test end"; diff --git a/test/fuzztest/notificationrequest_fuzzer/notificationrequest_fuzzer.cpp b/test/fuzztest/notificationrequest_fuzzer/notificationrequest_fuzzer.cpp index 0d8709c87..e761abe5e 100644 --- a/test/fuzztest/notificationrequest_fuzzer/notificationrequest_fuzzer.cpp +++ b/test/fuzztest/notificationrequest_fuzzer/notificationrequest_fuzzer.cpp @@ -43,7 +43,6 @@ namespace OHOS { request.GetWantAgent(); request.SetRemovalWantAgent(wantAgent); request.GetRemovalWantAgent(); - request.SetMaxScreenWantAgent(wantAgent); request.GetMaxScreenWantAgent(); std::shared_ptr extras = nullptr; request.SetAdditionalData(extras); diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index ea7c1dacb..933dffbb6 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -94,7 +94,6 @@ namespace OHOS { manager->CheckReminderLimitExceededLocked(callingUid, reminder); std::vector> reminders; manager->GetImmediatelyShowRemindersLocked(reminders); - manager->GetSoundUri(reminder); manager->AddToShowedReminders(reminder); manager->IsAllowedNotify(reminder); diff --git a/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp b/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp index e891852b0..fa363d2ce 100644 --- a/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp +++ b/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp @@ -44,7 +44,7 @@ namespace OHOS { reminderRequest.GetExpiredContent(); reminderRequest.GetMaxScreenWantAgentInfo(); reminderRequest.GetNotificationId(); - reminderRequest.GetNotificationRequest(); + reminderRequest.CreateNotificationRequest(); reminderRequest.GetReminderId(); reminderRequest.GetReminderTimeInMilli(); reminderRequest.SetReminderId(reminderId); @@ -66,7 +66,7 @@ namespace OHOS { reminderRequest.UpdateNextReminder(); reminderRequest.SetNextTriggerTime(); Parcel parcel; - reminderRequest.InitNotificationRequest(); + reminderRequest.CreateNotificationRequest(); reminderRequest.InitServerObj(); return reminderRequest.IsAlerting(); } -- Gitee From e650f7762cd71be5b7f49ab793294fad5fc8a335 Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 08:32:01 +0800 Subject: [PATCH 22/29] push Signed-off-by: fengyang --- frameworks/reminder/src/reminder_request.cpp | 21 ++----------------- interfaces/inner_api/reminder_request.h | 11 +--------- .../reminder/include/reminder_data_manager.h | 10 --------- .../unittest/reminder_data_manager_test.cpp | 2 -- 4 files changed, 3 insertions(+), 41 deletions(-) diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index c9cc5f410..9a74bd038 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -69,9 +69,9 @@ const std::string ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT = "ohos.event.not const std::string ReminderRequest::REMINDER_EVENT_CUSTOM_ALERT = "ohos.event.notification.reminder.COSTUM_ALERT"; const std::string ReminderRequest::REMINDER_EVENT_CLICK_ALERT = "ohos.event.notification.reminder.CLICK_ALERT"; const std::string ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT = "ohos.event.notification.reminder.ALERT_TIMEOUT"; -const std::string ReminderRequest::REMINDER_EVENT_LOAD_REMINDER = "ohos.event.notification.reminder.LOAD_REMINDER"; const std::string ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION = "ohos.event.notification.reminder.REMOVE_NOTIFICATION"; +const std::string ReminderRequest::REMINDER_EVENT_LOAD_REMINDER = "ohos.event.notification.reminder.LOAD_REMINDER"; const std::string ReminderRequest::PARAM_REMINDER_ID = "REMINDER_ID"; const std::string ReminderRequest::SEP_BUTTON_SINGLE = ""; const std::string ReminderRequest::SEP_BUTTON_MULTI = ""; @@ -402,7 +402,6 @@ void ReminderRequest::OnShow(bool isPlaySoundOrVibration, bool isSysTimeChanged, if (isPlaySoundOrVibration) { SetState(true, REMINDER_STATUS_ALERTING, "OnShow"); } - UpdateNotificationStateForAlert(); } } @@ -424,7 +423,6 @@ bool ReminderRequest::OnSnooze() if (!UpdateNextReminder(true)) { return false; } - UpdateNotificationStateForSnooze(); if (timeIntervalInMilli_ > 0) { SetState(true, REMINDER_STATUS_SNOOZE, "onSnooze()"); } @@ -462,7 +460,6 @@ bool ReminderRequest::OnTerminate() return false; } SetState(false, REMINDER_STATUS_ALERTING, "onTerminate"); - UpdateNotificationStateForAlert(); return true; } @@ -946,16 +943,6 @@ std::string ReminderRequest::GetCustomRingUri() const return customRingUri_; } -sptr ReminderRequest::GetNotificationBundleOption() const -{ - return notificationOption_; -} - -void ReminderRequest::SetNotificationBundleOption(const sptr& option) -{ - notificationOption_ = option; -} - std::shared_ptr ReminderRequest::GetWantAgentInfo() const { return wantAgentInfo_; @@ -1030,7 +1017,7 @@ void ReminderRequest::UpdateNotificationWantAgent(NotificationRequest& notificat notificationRequest.SetWantAgent(wantAgent); if (wantAgentInfo_->parameters.HasParam(PARAM_EXTRA_KEY)) { std::shared_ptr extras = std::make_shared( - params.GetWantParams(PARAM_EXTRA_KEY)); + wantAgentInfo_->parameters.GetWantParams(PARAM_EXTRA_KEY)); notificationRequest.SetAdditionalData(extras); } } @@ -1580,10 +1567,6 @@ void ReminderRequest::SetStateToInActive() void ReminderRequest::UpdateActionButtons(NotificationRequest& notificationRequest, const bool &setSnooze) { - if (notificationRequest_ == nullptr) { - ANSR_LOGE("updateActionButtons failed, the notificationRequest is null"); - return; - } notificationRequest.ClearActionButtons(); if (setSnooze) { AddActionButtons(notificationRequest, false); diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index cffb2efae..8076036cc 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -863,16 +863,6 @@ public: */ void SetCustomRingUri(const std::string &uri); - /** - * @brief Gets notification bundle option. - */ - sptr GetNotificationBundleOption() const; - - /** - * @brief Sets notification bundle option. - */ - void SetNotificationBundleOption(const sptr& option); - /** * @brief Update notification attributes. * @@ -986,6 +976,7 @@ public: * @brief Update the reminder when remove notification from the systemUI. */ static const std::string REMINDER_EVENT_REMOVE_NOTIFICATION; + static const std::string REMINDER_EVENT_LOAD_REMINDER; static const std::string PARAM_REMINDER_ID; static const uint8_t REMINDER_STATUS_INACTIVE; static const uint8_t REMINDER_STATUS_ACTIVE; diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 8e4fd740b..4502cee3a 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -121,8 +121,6 @@ public: */ static std::shared_ptr GetInstance(); static std::shared_ptr InitInstance(); - // fengyang static std::shared_ptr InitInstance( - // const sptr &advancedNotificationService); /** * Obtains all the valid reminders (which are not expired) relative to the bundle option. @@ -193,13 +191,6 @@ public: */ void RefreshRemindersDueToSysTimeChange(uint8_t type); - /** - * @brief Indicates the single instance of ans that used to execute operations in service. - * - * @param Indicates the single instance of ans notification service. - */ - // fengyang void SetService(sptr &advancedNotificationService); - bool ShouldAlert(const sptr &reminder) const; /** @@ -723,7 +714,6 @@ private: */ int16_t totalCount_ {0}; int currentUserId_ {0}; - // fengyang sptr advancedNotificationService_ = nullptr; std::shared_ptr store_ = nullptr; /** diff --git a/services/reminder/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp index e3020d6bb..086bf8810 100644 --- a/services/reminder/test/unittest/reminder_data_manager_test.cpp +++ b/services/reminder/test/unittest/reminder_data_manager_test.cpp @@ -283,9 +283,7 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_011, Level1) { sptr reminder(new ReminderRequestTimer(10)); reminder->SetReminderId(0); - sptr option(new NotificationBundleOption()); manager->ShowReminder(reminder, true, true, true, true); - reminder->SetNotificationBundleOption(option); reminder->SetReminderId(10); manager->ShowReminder(reminder, true, true, true, true); manager->ShowReminder(reminder, true, true, true, true); -- Gitee From 51ed49c3dd7c285ecbc3bf7f7d52a9b19a74d675 Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 08:42:56 +0800 Subject: [PATCH 23/29] push Signed-off-by: fengyang --- frameworks/reminder/BUILD.gn | 4 ++-- frameworks/reminder/IReminderManager.idl | 2 +- .../reminder/src/reminder_request_client.cpp | 20 +++++++++---------- .../src/reminder_service_load_callback.cpp | 4 ++-- interfaces/inner_api/reminder_request.h | 4 ++-- .../inner_api/reminder_request_client.h | 4 ++-- .../reminder/include/reminder_data_manager.h | 8 ++++++++ services/reminder/include/reminder_service.h | 2 +- .../reminder/src/reminder_data_manager.cpp | 6 ++---- 9 files changed, 30 insertions(+), 24 deletions(-) diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index 6bfeff856..52034a4d1 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -25,11 +25,11 @@ idl_interface_sources = [ ] idl_gen_interface("reminder_manager_interface") { - src_idl = rebase_path("IReminderManager.idl") + src_idl = rebase_path("IReminderService.idl") dst_file = string_join(",", idl_interface_sources) hitrace = "HITRACE_TAG_ABILITY_MANAGER" log_domainid = "0xD003900" - log_tag = "ReminderManagerService" + log_tag = "ReminderServiceService" } config("reminder_innerkits_public_config") { diff --git a/frameworks/reminder/IReminderManager.idl b/frameworks/reminder/IReminderManager.idl index b050e6ec9..b384c516c 100644 --- a/frameworks/reminder/IReminderManager.idl +++ b/frameworks/reminder/IReminderManager.idl @@ -14,7 +14,7 @@ */ sequenceable OHOS.Notification.ReminderRequest; -interface OHOS.Notification.IReminderManager { +interface OHOS.Notification.IReminderService { void PublishReminder([in] ReminderRequest reminder, [out] int reminderId); void CancelReminder([in] int reminderId); void CancelAllReminders(); diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index 76329a216..4b8d707ab 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -91,9 +91,9 @@ ErrCode ReminderRequestClient::RemoveNotificationSlot(const NotificationConstant ErrCode ReminderRequestClient::PublishReminder(const ReminderRequest& reminder, int32_t& reminderId) { AddSlotByType(reminder.GetSlotType()); - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { - ANS_LOGE("GetReminderManagerProxy fail."); + ANS_LOGE("GetReminderServiceProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } return proxy->PublishReminder(reminder, reminderId); @@ -101,7 +101,7 @@ ErrCode ReminderRequestClient::PublishReminder(const ReminderRequest& reminder, ErrCode ReminderRequestClient::CancelReminder(const int32_t reminderId) { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -111,7 +111,7 @@ ErrCode ReminderRequestClient::CancelReminder(const int32_t reminderId) ErrCode ReminderRequestClient::CancelAllReminders() { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -121,7 +121,7 @@ ErrCode ReminderRequestClient::CancelAllReminders() ErrCode ReminderRequestClient::GetValidReminders(std::vector &validReminders) { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -131,7 +131,7 @@ ErrCode ReminderRequestClient::GetValidReminders(std::vector &v ErrCode ReminderRequestClient::AddExcludeDate(const int32_t reminderId, const uint64_t date) { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -141,7 +141,7 @@ ErrCode ReminderRequestClient::AddExcludeDate(const int32_t reminderId, const ui ErrCode ReminderRequestClient::DelExcludeDates(const int32_t reminderId) { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -151,7 +151,7 @@ ErrCode ReminderRequestClient::DelExcludeDates(const int32_t reminderId) ErrCode ReminderRequestClient::GetExcludeDates(const int32_t reminderId, std::vector& dates) { - sptr proxy = GetReminderManagerProxy(); + sptr proxy = GetReminderServiceProxy(); if (!proxy) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; @@ -183,7 +183,7 @@ sptr ReminderRequestClient::GetAnsManagerProxy() return proxy; } -sptr ReminderRequestClient::GetReminderManagerProxy() +sptr ReminderRequestClient::GetReminderServiceProxy() { { std::lock_guard lock(serviceLock_); @@ -198,7 +198,7 @@ sptr ReminderRequestClient::GetReminderManagerProxy() auto object = samgrProxy->CheckSystemAbility(1930); if (object != nullptr) { ANS_LOGE("get service succeeded"); - proxy_ = iface_cast(object); + proxy_ = iface_cast(object); return proxy_; } } diff --git a/frameworks/reminder/src/reminder_service_load_callback.cpp b/frameworks/reminder/src/reminder_service_load_callback.cpp index c24c9492b..adbc50680 100644 --- a/frameworks/reminder/src/reminder_service_load_callback.cpp +++ b/frameworks/reminder/src/reminder_service_load_callback.cpp @@ -28,13 +28,13 @@ void ReminderServiceCallback::OnLoadSystemAbilitySuccess( int32_t systemAbilityId, const sptr &remoteObject) { ReminderRequestClient::GetInstance().LoadSystemAbilitySuccess(remoteObject); - HILOGI("on load system ability success!"); + ANS_LOGI("on load system ability success!"); } void ReminderServiceCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) { ReminderRequestClient::GetInstance().LoadSystemAbilityFail(); - HILOGI("on load system ability failed!"); + ANS_LOGI("on load system ability failed!"); } } } \ No newline at end of file diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index 8076036cc..ac79dc143 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -900,6 +900,8 @@ public: */ void OnLanguageChange(const std::shared_ptr &resMgr); + NotificationRequest CreateNotificationRequest(); + public: /** * @brief Serialize want agent info and max want agent info to string. @@ -1030,8 +1032,6 @@ protected: uint64_t GetTriggerTime(const time_t now, const time_t nextTriggerTime) const; uint64_t GetNowInstantMilli() const; - NotificationRequest CreateNotificationRequest(); - private: std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index 2723bb67c..e9998ee89 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -123,7 +123,7 @@ private: sptr GetAnsManagerProxy(); - sptr GetReminderManagerProxy(); + sptr GetReminderServiceProxy(); bool LoadReminderService(); @@ -131,7 +131,7 @@ private: std::condition_variable proxyConVar_; - sptr dpProxy_; + sptr dpProxy_; }; } // namespace Notification diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 4502cee3a..70ec4efdc 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -642,6 +642,10 @@ private: */ void ReportSysEvent(const sptr& reminder); + void StartReminderLoadTimer(); + + int64_t CreateReminderLoadTimer(const sptr timer); + /** * Single instance. */ @@ -736,6 +740,10 @@ private: * Sa ready flag */ std::atomic saReadyFlag_{ 0 }; + + std::mutex timeLoadMutex_; + int32_t reminderLoadtimerId_ {0}; + }; } // namespace OHOS } // namespace Notification diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h index d04c78d29..0aa1ab674 100644 --- a/services/reminder/include/reminder_service.h +++ b/services/reminder/include/reminder_service.h @@ -34,7 +34,7 @@ namespace OHOS { namespace Notification { static const uint32_t DEFAULT_SLOT_FLAGS = 59; // 0b111011 -class ReminderService final : public ReminderManagerStub, +class ReminderService final : public ReminderServiceStub, public std::enable_shared_from_this { public: diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 77a57eca0..a7da5513c 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -583,12 +583,10 @@ void ReminderDataManager::StartReminderLoadTimer() int64_t ReminderDataManager::CreateReminderLoadTimer(const sptr timer) { auto sharedTimerInfo = std::make_shared(); - if ((sharedTimerInfo->TIMER_TYPE_WAKEUP > UINT8_MAX) || (sharedTimerInfo->TIMER_TYPE_EXACT > UINT8_MAX)) { - ANSR_LOGE("Failed to set timer type."); - return nullptr; - } sharedTimerInfo->SetRepeat(false); sharedTimerInfo->SetInterval(0); + uint8_t timerTypeWakeup = static_cast(sharedTimerInfo->TIMER_TYPE_WAKEUP); + uint8_t timerTypeExact = static_cast(sharedTimerInfo->TIMER_TYPE_EXACT); int32_t timerType = static_cast(timerTypeWakeup | timerTypeExact); sharedTimerInfo->SetType(timerType); -- Gitee From ff57e0d0f59faac66b34031e52118759d905469f Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 09:08:16 +0800 Subject: [PATCH 24/29] push Signed-off-by: fengyang --- frameworks/reminder/BUILD.gn | 10 +++++----- .../{IReminderManager.idl => IReminderService.idl} | 0 frameworks/reminder/src/reminder_request_client.cpp | 6 +++--- interfaces/inner_api/reminder_request_calendar.h | 1 - interfaces/inner_api/reminder_request_client.h | 4 ++-- .../reminder/include/reminder_bundle_manager_helper.h | 6 +++--- services/reminder/include/reminder_data_manager.h | 4 ++-- .../include/reminder_os_account_manager_helper.h | 6 +++--- services/reminder/include/reminder_service.h | 4 ++-- services/reminder/src/reminder_data_manager.cpp | 1 + services/reminder/src/reminder_service.cpp | 4 +++- services/reminder/src/reminder_service_ability.cpp | 1 + services/reminder/src/reminder_store.cpp | 10 +++++----- 13 files changed, 30 insertions(+), 27 deletions(-) rename frameworks/reminder/{IReminderManager.idl => IReminderService.idl} (100%) diff --git a/frameworks/reminder/BUILD.gn b/frameworks/reminder/BUILD.gn index 52034a4d1..6041dea06 100644 --- a/frameworks/reminder/BUILD.gn +++ b/frameworks/reminder/BUILD.gn @@ -20,11 +20,11 @@ group("reminder_client") { } idl_interface_sources = [ - "${target_gen_dir}/reminder_manager_proxy.cpp", - "${target_gen_dir}/reminder_manager_stub.cpp", + "${target_gen_dir}/reminder_service_proxy.cpp", + "${target_gen_dir}/reminder_service_stub.cpp", ] -idl_gen_interface("reminder_manager_interface") { +idl_gen_interface("reminder_service_interface") { src_idl = rebase_path("IReminderService.idl") dst_file = string_join(",", idl_interface_sources) hitrace = "HITRACE_TAG_ABILITY_MANAGER" @@ -56,7 +56,7 @@ ohos_shared_library("reminder_innerkits") { include_dirs = [ "${inner_api_path}" ] public_configs = [ ":reminder_innerkits_public_config" ] - output_values = get_target_outputs(":reminder_manager_interface") + output_values = get_target_outputs(":reminder_service_interface") sources = [ "${frameworks_module_reminder_path}/src/reminder_request_factory.cpp", "${frameworks_module_reminder_path}/src/reminder_request_client.cpp", @@ -70,7 +70,7 @@ ohos_shared_library("reminder_innerkits") { sources += filter_include(output_values, [ "*.cpp" ]) defines = [] deps = [ - ":reminder_manager_interface", + ":reminder_service_interface", "${frameworks_path}/ans:ans_client", ] diff --git a/frameworks/reminder/IReminderManager.idl b/frameworks/reminder/IReminderService.idl similarity index 100% rename from frameworks/reminder/IReminderManager.idl rename to frameworks/reminder/IReminderService.idl diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index 4b8d707ab..b729a4bd3 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -15,7 +15,7 @@ #include "reminder_request_client.h" #include "ans_manager_proxy.h" -#include "reminder_manager_proxy.h" +#include "reminder_service_proxy.h" #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" @@ -252,7 +252,7 @@ void ReminderRequestClient::LoadSystemAbilitySuccess(const sptr & HILOGI("ReminderRequestClient FinishStartSA"); std::lock_guard lock(serviceLock_); if (remoteObject != nullptr) { - Proxy_ = iface_cast(remoteObject); + proxy_ = iface_cast(remoteObject); proxyConVar_.notify_one(); } } @@ -260,7 +260,7 @@ void ReminderRequestClient::LoadSystemAbilitySuccess(const sptr & void ReminderRequestClient::LoadSystemAbilityFail() { std::lock_guard lock(serviceLock_); - dpProxy_ = nullptr; + proxy_ = nullptr; } } // namespace Notification diff --git a/interfaces/inner_api/reminder_request_calendar.h b/interfaces/inner_api/reminder_request_calendar.h index fe51354db..dcdd4a911 100644 --- a/interfaces/inner_api/reminder_request_calendar.h +++ b/interfaces/inner_api/reminder_request_calendar.h @@ -324,7 +324,6 @@ protected: private: - uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; uint64_t GetNextTriggerTime(const bool updateLast = false); uint64_t GetNextTriggerTimeAsRepeatReminder(const tm &nowTime, const tm &tarTime) const; diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index e9998ee89..7ca27ef71 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -21,7 +21,7 @@ #include "notification_slot.h" #include "notification_constant.h" #include "ans_manager_interface.h" -#include "ireminder_manager.h" +#include "ireminder_service.h" #include "ffrt.h" namespace OHOS { @@ -131,7 +131,7 @@ private: std::condition_variable proxyConVar_; - sptr dpProxy_; + sptr proxy_; }; } // namespace Notification diff --git a/services/reminder/include/reminder_bundle_manager_helper.h b/services/reminder/include/reminder_bundle_manager_helper.h index 25be9747b..9763f19e8 100644 --- a/services/reminder/include/reminder_bundle_manager_helper.h +++ b/services/reminder/include/reminder_bundle_manager_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H +#ifndef NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H +#define NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H #include #include @@ -82,4 +82,4 @@ private: }; } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H +#endif // NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_BUNDLE_MANAGER_HELPER_H diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index 70ec4efdc..f45225523 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -270,6 +270,8 @@ public: void ReceiveLoadReminderEvent(); + void StartReminderLoadTimer(); + static constexpr uint8_t TIME_ZONE_CHANGE = 0; static constexpr uint8_t DATE_TIME_CHANGE = 1; @@ -642,8 +644,6 @@ private: */ void ReportSysEvent(const sptr& reminder); - void StartReminderLoadTimer(); - int64_t CreateReminderLoadTimer(const sptr timer); /** diff --git a/services/reminder/include/reminder_os_account_manager_helper.h b/services/reminder/include/reminder_os_account_manager_helper.h index 557cfda78..f98d740e1 100644 --- a/services/reminder/include/reminder_os_account_manager_helper.h +++ b/services/reminder/include/reminder_os_account_manager_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H -#define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H +#ifndef NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H +#define NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H #include "errors.h" #include "singleton.h" @@ -52,4 +52,4 @@ public: }; } // namespace OHOS } // namespace Notification -#endif // BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file +#endif // NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_service.h b/services/reminder/include/reminder_service.h index 0aa1ab674..781c42db3 100644 --- a/services/reminder/include/reminder_service.h +++ b/services/reminder/include/reminder_service.h @@ -28,7 +28,7 @@ #include "refbase.h" #include "ans_const_define.h" -#include "reminder_manager_stub.h" +#include "reminder_service_stub.h" namespace OHOS { namespace Notification { @@ -122,7 +122,7 @@ private: ErrCode InitReminderRequest(sptr& tarReminder, const std::string& bundle, const int32_t callingUid); private: - ffrt::task_handle unloadTask_ = nullptr; + ffrt::task_handle tryUnloadTask_ = nullptr; static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index a7da5513c..5f8c33be1 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -1070,6 +1070,7 @@ NotificationRequest ReminderDataManager::CreateNotificationRequest(const sptrCreateNotificationRequest(); reminder->UpdateNotificationRequest(notificationRequest, isSnooze); + return notificationRequest; } void ReminderDataManager::SnoozeReminder(const OHOS::EventFwk::Want &want) diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index 5845f8d3b..e30034c89 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -21,6 +21,7 @@ #include "reminder_bundle_manager_helper.h" #include "reminder_access_token_helper.h" #include "reminder_notification_inline.cpp" +#include "ffrt_inner.h" #include @@ -181,6 +182,7 @@ ErrCode ReminderService::InitReminderRequest(sptr& tarReminder, tarReminder->InitUserId(activeUserId); tarReminder->InitUid(ReminderBundleManagerHelper::GetInstance()->GetDefaultUidByBundleName( tarReminder->GetBundleName(), tarReminder->GetUserId())); + return ERR_OK; } ErrCode ReminderService::CancelReminder(const int32_t reminderId) @@ -307,7 +309,7 @@ void ReminderService::TryPostDelayUnloadTask(int64_t delayTime) if (tryUnloadTask_) { ffrt::skip(tryUnloadTask_); } - tryUnloadTask_ = ffrt::submit_h([]() { + tryUnloadTask_ = ffrt::submit_h([this]() { auto rdm = ReminderDataManager::GetInstance(); if (rdm == nullptr) { ANSR_LOGW("Reminder data manager not init!"); diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp index e98247dbf..db3966ecc 100644 --- a/services/reminder/src/reminder_service_ability.cpp +++ b/services/reminder/src/reminder_service_ability.cpp @@ -45,6 +45,7 @@ void ReminderServiceAbility::OnStart() return; } reminderAgent_ = ReminderDataManager::InitInstance(); + reminderAgent_->StartReminderLoadTimer(); ReminderService::GetInstance()->TryPostDelayUnloadTask(INIT_DELAY_TIME); } diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index d1aecc642..75265fae0 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -817,27 +817,27 @@ std::shared_ptr ReminderStore::Query(const std::string& qu return rdbStore_->QuerySql(queryCondition, whereArgs); } -int32_t ReminderStore::QueryActiveReminderCount() const +int32_t ReminderStore::QueryActiveReminderCount() { REMINDER_CHECK_NULL_RETURN(rdbStore_, "Rdb store is not initialized.", 0); std::string queryCondition = "SELECT * FROM "; queryCondition.append(ReminderBaseTable::TABLE_NAME).append(" WHERE ").append(ReminderBaseTable::IS_EXPIRED) - .append(" = 'true' AND ").append(REMINDER_TYPE).append(" != 1"); + .append(" = 'true' AND ").append(ReminderTable::REMINDER_TYPE).append(" != 1"); std::vector whereArgs; auto resultSet = rdbStore_->QuerySql(queryCondition, whereArgs); int32_t baseTableNum = 0; resultSet->GetRowCount(baseTableNum); - std::string queryCondition = "SELECT * FROM "; + queryCondition = "SELECT * FROM "; int64_t nowTime = GetCurrentTime(); queryCondition.append(ReminderCalendarTable::TABLE_NAME).append(" WHERE (") .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append(" < ").append(std::to_string(nowTime)).append(" AND ") - .append(CALENDAR_END_DATE_TIME).append(" > ").append(std::to_string(nowTime)).append(" ) OR ") + .append(ReminderCalendarTable::CALENDAR_END_DATE_TIME).append(" > ").append(std::to_string(nowTime)).append(" ) OR ") .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append("> ").append(std::to_string(nowTime)); resultSet = rdbStore_->QuerySql(queryCondition, whereArgs); int32_t calenderTableNum = 0; resultSet->GetRowCount(calenderTableNum); - return baseTableNum + calenderTableNum + return baseTableNum + calenderTableNum; } } // namespace Notification } // namespace OHOS -- Gitee From c9bc27b7844e46905c18595caec8a725e6b24a11 Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 09:36:48 +0800 Subject: [PATCH 25/29] push Signed-off-by: fengyang --- frameworks/js/napi/src/reminder/publish.cpp | 1 - frameworks/reminder/src/reminder_request.cpp | 4 ---- .../reminder/src/reminder_request_client.cpp | 15 ++++++++------- .../src/reminder_service_load_callback.cpp | 4 ++-- .../reminder_request_branch_test.cpp | 1 - .../test/unittest/reminder_request_test.cpp | 12 ++++++------ interfaces/inner_api/reminder_request_client.h | 7 +++++-- interfaces/inner_api/reminder_request_factory.h | 3 --- services/reminder/src/reminder_data_manager.cpp | 3 +-- services/reminder/src/reminder_store.cpp | 3 +-- 10 files changed, 23 insertions(+), 30 deletions(-) diff --git a/frameworks/js/napi/src/reminder/publish.cpp b/frameworks/js/napi/src/reminder/publish.cpp index a1e7aa60e..ed48a8fc7 100644 --- a/frameworks/js/napi/src/reminder/publish.cpp +++ b/frameworks/js/napi/src/reminder/publish.cpp @@ -827,7 +827,6 @@ void GetAllValidRemindersInner(napi_env env, const std::vector& int32_t count = 0; napi_create_array(env, &arr); for (auto& reminder : validReminders) { - napi_value result = nullptr; napi_create_object(env, &result); napi_value reminderReq = nullptr; diff --git a/frameworks/reminder/src/reminder_request.cpp b/frameworks/reminder/src/reminder_request.cpp index 9a74bd038..42c9453e1 100644 --- a/frameworks/reminder/src/reminder_request.cpp +++ b/frameworks/reminder/src/reminder_request.cpp @@ -1146,7 +1146,6 @@ ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) ReminderType tarReminderType = ReminderType::INVALID; ReadReminderTypeFormParcel(parcel, tarReminderType); auto reminderRequest = ReminderRequestFactory::CreateReminderRequest(tarReminderType); - if (reminderRequest == nullptr) { ANSR_LOGE("Failed to create reminder due to no memory."); return reminderRequest; @@ -1254,9 +1253,6 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) READ_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimes_, "snoozeTimes"); READ_UINT8_RETURN_FALSE_LOG(parcel, snoozeTimesDynamic_, "snoozeTimesDynamic"); READ_UINT8_RETURN_FALSE_LOG(parcel, state_, "state"); - - - int32_t slotType = static_cast(NotificationConstant::SlotType::OTHER); READ_INT32_RETURN_FALSE_LOG(parcel, slotType, "slotType"); slotType_ = static_cast(slotType); diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index b729a4bd3..5e1b07c16 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -14,6 +14,7 @@ */ #include "reminder_request_client.h" +#include "reminder_service_load_callback.h" #include "ans_manager_proxy.h" #include "reminder_service_proxy.h" #include "ans_const_define.h" @@ -186,7 +187,7 @@ sptr ReminderRequestClient::GetAnsManagerProxy() sptr ReminderRequestClient::GetReminderServiceProxy() { { - std::lock_guard lock(serviceLock_); + std::lock_guard lock(serviceLock_); if (proxy_ != nullptr) { return proxy_; } @@ -205,7 +206,7 @@ sptr ReminderRequestClient::GetReminderServiceProxy() ANS_LOGE("object is null"); if (LoadReminderService()) { - std::lock_guard lock(serviceLock_); + std::lock_guard lock(serviceLock_); if (proxy_ != nullptr) { return proxy_; } else { @@ -219,7 +220,7 @@ sptr ReminderRequestClient::GetReminderServiceProxy() bool ReminderRequestClient::LoadReminderService() { - std::lock_guard lock(serviceLock_); + std::unique_lock lock(serviceLock_); sptr loadCallback = sptr(new ReminderServiceCallback()); if (loadCallback == nullptr) { ANS_LOGE("loadCallback is nullptr."); @@ -249,17 +250,17 @@ bool ReminderRequestClient::LoadReminderService() void ReminderRequestClient::LoadSystemAbilitySuccess(const sptr &remoteObject) { - HILOGI("ReminderRequestClient FinishStartSA"); - std::lock_guard lock(serviceLock_); + ANS_LOGE("ReminderRequestClient FinishStartSA"); + std::lock_guard lock(serviceLock_); if (remoteObject != nullptr) { - proxy_ = iface_cast(remoteObject); + proxy_ = iface_cast(remoteObject); proxyConVar_.notify_one(); } } void ReminderRequestClient::LoadSystemAbilityFail() { - std::lock_guard lock(serviceLock_); + std::lock_guard lock(serviceLock_); proxy_ = nullptr; } diff --git a/frameworks/reminder/src/reminder_service_load_callback.cpp b/frameworks/reminder/src/reminder_service_load_callback.cpp index adbc50680..94bfdcb39 100644 --- a/frameworks/reminder/src/reminder_service_load_callback.cpp +++ b/frameworks/reminder/src/reminder_service_load_callback.cpp @@ -27,13 +27,13 @@ const std::string TAG = "ReminderServiceLoadCallback"; void ReminderServiceCallback::OnLoadSystemAbilitySuccess( int32_t systemAbilityId, const sptr &remoteObject) { - ReminderRequestClient::GetInstance().LoadSystemAbilitySuccess(remoteObject); + DelayedSingleton::GetInstance()->LoadSystemAbilitySuccess(remoteObject); ANS_LOGI("on load system ability success!"); } void ReminderServiceCallback::OnLoadSystemAbilityFail(int32_t systemAbilityId) { - ReminderRequestClient::GetInstance().LoadSystemAbilityFail(); + DelayedSingleton::GetInstance()->LoadSystemAbilityFail(); ANS_LOGI("on load system ability failed!"); } } diff --git a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp index e928c9683..1755a8463 100644 --- a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp @@ -214,7 +214,6 @@ HWTEST_F(ReminderRequestBranchTest, UpdateNotificationRequest_00300, Function | int32_t notificationId_ = 0; auto notificationRequest = reminderRequest->CreateNotificationRequest(); reminderRequest->wantAgentInfo_ = std::make_shared(); - auto notificationRequest = reminderRequest->CreateNotificationRequest(); bool isSnooze = true; reminderRequest->UpdateNotificationRequest(notificationRequest, isSnooze); } diff --git a/frameworks/reminder/test/unittest/reminder_request_test.cpp b/frameworks/reminder/test/unittest/reminder_request_test.cpp index dd88f24df..c37376f1d 100644 --- a/frameworks/reminder/test/unittest/reminder_request_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_request_test.cpp @@ -939,7 +939,7 @@ HWTEST_F(ReminderRequestTest, Unmarshalling_00001, Function | SmallTest | Level1 HWTEST_F(ReminderRequestTest, CreateNotificationRequest_00001, Function | SmallTest | Level1) { auto rrc = std::make_shared(); - EXPECT_EQ(rrc->CreateNotificationRequest(), nullptr); + EXPECT_EQ(rrc->CreateNotificationRequest().GetNotificationId(), 0); } /** @@ -952,7 +952,7 @@ HWTEST_F(ReminderRequestTest, CreateNotificationRequest_00002, Function | SmallT { auto rrc = std::make_shared(); rrc->SetNotificationId(100); - EXPECT_EQ(rrc->CreateNotificationRequest(), nullptr); + EXPECT_EQ(rrc->CreateNotificationRequest().GetNotificationId(), 100); } /** @@ -1207,7 +1207,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationContent_00002, Function | SmallT { auto rrc = std::make_shared(); rrc->SetNotificationId(100); - auto notification = rrc.CreateNotificationRequest(); + auto notification = rrc->CreateNotificationRequest(); rrc->UpdateNotificationContent(notification, true); rrc->UpdateNotificationContent(notification, false); @@ -1760,7 +1760,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00100, Function | SmallTe rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then - EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::CONTENT_INFORMATION); + EXPECT_EQ(notificationRequest.GetSlotType(), NotificationConstant::SlotType::CONTENT_INFORMATION); } /** @@ -1781,7 +1781,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00200, Function | SmallTe rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then - EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::SERVICE_REMINDER); + EXPECT_EQ(notificationRequest.GetSlotType(), NotificationConstant::SlotType::SERVICE_REMINDER); } /** @@ -1804,7 +1804,7 @@ HWTEST_F(ReminderRequestTest, UpdateNotificationCommon_00300, Function | SmallTe rrc->UpdateNotificationCommon(notificationRequest, isSnooze); // then - EXPECT_EQ(ret->GetSlotType(), NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + EXPECT_EQ(notificationRequest.GetSlotType(), NotificationConstant::SlotType::SOCIAL_COMMUNICATION); } /** diff --git a/interfaces/inner_api/reminder_request_client.h b/interfaces/inner_api/reminder_request_client.h index 7ca27ef71..dc85c7ecd 100644 --- a/interfaces/inner_api/reminder_request_client.h +++ b/interfaces/inner_api/reminder_request_client.h @@ -109,6 +109,10 @@ public: */ ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + void LoadSystemAbilitySuccess(const sptr &remoteObject); + + void LoadSystemAbilityFail(); + private: /** @@ -127,12 +131,11 @@ private: bool LoadReminderService(); - ffrt::mutex serviceLock_; + std::mutex serviceLock_; std::condition_variable proxyConVar_; sptr proxy_; - }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/inner_api/reminder_request_factory.h b/interfaces/inner_api/reminder_request_factory.h index 97d69648b..fb33ebbcb 100644 --- a/interfaces/inner_api/reminder_request_factory.h +++ b/interfaces/inner_api/reminder_request_factory.h @@ -16,12 +16,9 @@ #ifndef BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_FACTORY_H #define BASE_NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_INTERFACES_INNER_API_REMINDER_REQUEST_FACTORY_H - - #include "reminder_request.h" #include "string" - namespace OHOS { namespace Notification { class ReminderRequestFactory { diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 5f8c33be1..231b2a151 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -268,7 +268,7 @@ void ReminderDataManager::CancelRemindersImplLocked(const int32_t userId, if (isCancelAllPackage) { store_->DeleteUser(userId); } else { - // fengyang store_->Delete(packageName, userId, uid); + store_->Delete(userId, uid); } MUTEX.unlock(); StartRecentReminder(); @@ -563,7 +563,6 @@ std::shared_ptr ReminderDataManager::InitInstance() REMINDER_DATA_MANAGER = std::make_shared(); ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); } - StartReminderLoadTimer(); return REMINDER_DATA_MANAGER; } diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index 75265fae0..513c236f4 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -351,8 +351,7 @@ __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::str + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " - + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); if (uid != -1) { assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID -- Gitee From 586d2972c5df972964ffb40f98a8f787cbb2c3a8 Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 10:47:20 +0800 Subject: [PATCH 26/29] push Signed-off-by: fengyang --- frameworks/js/napi/src/reminder/publish.cpp | 3 ++- .../reminder/src/reminder_service_load_callback.cpp | 1 + interfaces/inner_api/reminder_request.h | 6 ------ services/reminder/include/reminder_store.h | 1 + services/reminder/src/reminder_data_manager.cpp | 6 ++++-- services/reminder/src/reminder_service.cpp | 1 + services/reminder/src/reminder_store.cpp | 12 +++++++++++- services/reminder/src/reminder_store_strategy.cpp | 2 +- .../reminder/test/unittest/reminder_store_test.cpp | 3 +-- 9 files changed, 22 insertions(+), 13 deletions(-) diff --git a/frameworks/js/napi/src/reminder/publish.cpp b/frameworks/js/napi/src/reminder/publish.cpp index ed48a8fc7..af48621f7 100644 --- a/frameworks/js/napi/src/reminder/publish.cpp +++ b/frameworks/js/napi/src/reminder/publish.cpp @@ -1025,7 +1025,8 @@ napi_value PublishReminderInner(napi_env env, napi_callback_info info, bool isTh ANSR_LOGI("Publish napi_create_async_work start"); AsyncCallbackInfo *asynccallbackinfo = static_cast(data); if (asynccallbackinfo) { - asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder), asynccallbackinfo->reminderId); + asynccallbackinfo->info.errorCode = + ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder), asynccallbackinfo->reminderId); ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminderId); } }, diff --git a/frameworks/reminder/src/reminder_service_load_callback.cpp b/frameworks/reminder/src/reminder_service_load_callback.cpp index 94bfdcb39..dae18f59d 100644 --- a/frameworks/reminder/src/reminder_service_load_callback.cpp +++ b/frameworks/reminder/src/reminder_service_load_callback.cpp @@ -17,6 +17,7 @@ #include "ans_log_wrapper.h" #include "reminder_request_client.h" +#include "singleton.h" namespace OHOS { class IRemoteObject; } namespace OHOS { diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index ac79dc143..f75fad12e 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -882,12 +882,6 @@ public: */ std::vector GetDaysOfWeek() const; - /** - * @brief Create notification request struct when recover from rdb or - * recv reminder info from ipc. - */ - bool InitNotificationRequest(); - /** * @brief Gets repeat days of week */ diff --git a/services/reminder/include/reminder_store.h b/services/reminder/include/reminder_store.h index 03d365e34..4cdd7704a 100644 --- a/services/reminder/include/reminder_store.h +++ b/services/reminder/include/reminder_store.h @@ -41,6 +41,7 @@ public: int32_t GetMaxId(); int32_t QueryActiveReminderCount(); std::vector> GetHalfHourReminders(); + std::vector> GetAllValidReminders(); public: static void GetUInt8Val(const std::shared_ptr& resultSet, diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index 231b2a151..d35ef18f5 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -223,7 +223,8 @@ void ReminderDataManager::GetValidReminders( { HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); std::lock_guard lock(ReminderDataManager::MUTEX); - for (auto& eachReminder : reminderVector_) { + auto reminderVector = store_->GetAllValidReminders(); + for (auto& eachReminder : reminderVector) { if (eachReminder->IsExpired()) { continue; } @@ -1043,7 +1044,8 @@ void ReminderDataManager::ShowReminder(const sptr &reminder, co if (alertingReminderId_ != -1) { TerminateAlerting(alertingReminder_, "PlaySoundAndVibration"); } - ErrCode errCode = NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, notificationRequest); + ErrCode errCode = NotificationHelper::PublishNotification(ReminderRequest::NOTIFICATION_LABEL, + notificationRequest); if (errCode != ERR_OK) { reminder->OnShowFail(); RemoveFromShowedReminders(reminder); diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index e30034c89..130fe456f 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -52,6 +52,7 @@ namespace Notification { constexpr int64_t DELAY_TIME = 60 * 1000 * 1000; sptr ReminderService::instance_; std::mutex ReminderService::instanceMutex_; +std::mutex ReminderService::unloadMutex_; sptr ReminderService::GetInstance() { std::lock_guard lock(instanceMutex_); diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index 513c236f4..719663acb 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -416,6 +416,16 @@ int32_t ReminderStore::GetMaxId() return maxId; } +__attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetAllValidReminders() +{ + std::string sql = "SELECT " + ReminderBaseTable::SELECT_COLUMNS + " FROM " + + ReminderBaseTable::TABLE_NAME + " WHERE " + + ReminderBaseTable::IS_EXPIRED + " = 'false' ORDER BY " + + ReminderBaseTable::TRIGGER_TIME + " ASC"; + ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); + return GetReminders(sql); +} + __attribute__((no_sanitize("cfi"))) std::vector> ReminderStore::GetHalfHourReminders() { int64_t nowTime = GetCurrentTime(); @@ -432,7 +442,7 @@ __attribute__((no_sanitize("cfi"))) std::vector> ReminderS + ReminderCalendarTable::TABLE_NAME + "." + ReminderCalendarTable::CALENDAR_DATE_TIME + " > " + std::to_string(nowTime) +") ORDER BY " + ReminderBaseTable::TRIGGER_TIME + " ASC"; - ANSR_LOGD("GetAllValidReminders sql =%{public}s", sql.c_str()); + ANSR_LOGD("GetHalfHourReminders sql =%{public}s", sql.c_str()); return GetReminders(sql); } diff --git a/services/reminder/src/reminder_store_strategy.cpp b/services/reminder/src/reminder_store_strategy.cpp index 2fefeb129..7192c2142 100644 --- a/services/reminder/src/reminder_store_strategy.cpp +++ b/services/reminder/src/reminder_store_strategy.cpp @@ -355,7 +355,7 @@ void ReminderStrategy::RecoverFromDb(sptr& reminder, ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); reminder->DeserializeButtonInfo(actionButtons); - reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent + // fengyang reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent std::string wantAgent; ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); reminder->DeserializeWantAgent(wantAgent, 0); diff --git a/services/reminder/test/unittest/reminder_store_test.cpp b/services/reminder/test/unittest/reminder_store_test.cpp index 12e7dd96a..2a4e67e2e 100644 --- a/services/reminder/test/unittest/reminder_store_test.cpp +++ b/services/reminder/test/unittest/reminder_store_test.cpp @@ -118,10 +118,9 @@ HWTEST_F(ReminderStoreTest, Delete_00001, Function | SmallTest | Level1) */ HWTEST_F(ReminderStoreTest, Delete_00002, Function | SmallTest | Level1) { - std::string pkg = "pkg"; int32_t userId = 1; ReminderStore reminderStore; - int32_t ret = reminderStore.Delete(pkg, userId, -1); + int32_t ret = reminderStore.Delete(userId, -1); EXPECT_EQ(ret, -1); } -- Gitee From 706b24e6bcd9321f7a164ed4ca929e04c4c5cf4e Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 11:19:23 +0800 Subject: [PATCH 27/29] push Signed-off-by: fengyang --- frameworks/reminder/src/reminder_request_client.cpp | 2 +- .../reminder_request_branch_test.cpp | 2 -- .../reminder_service_test/reminder_service_publish_test.cpp | 1 - .../reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp | 2 -- 4 files changed, 1 insertion(+), 6 deletions(-) diff --git a/frameworks/reminder/src/reminder_request_client.cpp b/frameworks/reminder/src/reminder_request_client.cpp index 5e1b07c16..d1594fee8 100644 --- a/frameworks/reminder/src/reminder_request_client.cpp +++ b/frameworks/reminder/src/reminder_request_client.cpp @@ -253,7 +253,7 @@ void ReminderRequestClient::LoadSystemAbilitySuccess(const sptr & ANS_LOGE("ReminderRequestClient FinishStartSA"); std::lock_guard lock(serviceLock_); if (remoteObject != nullptr) { - proxy_ = iface_cast(remoteObject); + proxy_ = iface_cast(remoteObject); proxyConVar_.notify_one(); } } diff --git a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp index 1755a8463..7f0708b63 100644 --- a/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp +++ b/frameworks/reminder/test/unittest/reminder_request_branch_test/reminder_request_branch_test.cpp @@ -281,7 +281,6 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00100, Function | SmallTest | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; ReminderRequest::ActionButtonType actionButtonType = ReminderRequest::ActionButtonType::CLOSE; ReminderRequest::ActionButtonInfo info; @@ -305,7 +304,6 @@ HWTEST_F(ReminderRequestBranchTest, GetButtonInfo_00200, Function | SmallTest | auto reminderRequest = std::make_shared(); EXPECT_NE(reminderRequest, nullptr); int32_t notificationId_ = 0; - auto notificationRequest = reminderRequest->CreateNotificationRequest(); std::string title = "aa"; std::string pkgName = "bb"; std::string abilityName = "cc"; diff --git a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp index 87208f8df..9ba484a3f 100644 --- a/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp +++ b/services/reminder/test/unittest/reminder_service_test/reminder_service_publish_test.cpp @@ -154,7 +154,6 @@ HWTEST_F(ReminderServicePublishTest, ReminderServicePublishTest_17900, Function int32_t reminderId = 1; ReminderRequest reminder; - reminder.CreateNotificationRequest(); ASSERT_EQ(reminderService_->PublishReminder(reminder, reminderId), ERR_REMINDER_NOTIFICATION_NOT_ENABLE); GTEST_LOG_(INFO) << "GetAppTargetBundle_1000 test end"; diff --git a/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp b/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp index fa363d2ce..4d98dd87c 100644 --- a/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp +++ b/test/fuzztest/reminderrequestannex_fuzzer/reminderrequestannex_fuzzer.cpp @@ -44,7 +44,6 @@ namespace OHOS { reminderRequest.GetExpiredContent(); reminderRequest.GetMaxScreenWantAgentInfo(); reminderRequest.GetNotificationId(); - reminderRequest.CreateNotificationRequest(); reminderRequest.GetReminderId(); reminderRequest.GetReminderTimeInMilli(); reminderRequest.SetReminderId(reminderId); @@ -66,7 +65,6 @@ namespace OHOS { reminderRequest.UpdateNextReminder(); reminderRequest.SetNextTriggerTime(); Parcel parcel; - reminderRequest.CreateNotificationRequest(); reminderRequest.InitServerObj(); return reminderRequest.IsAlerting(); } -- Gitee From 7afb0bc3abec7cd13b007b29a6126d9a149ee085 Mon Sep 17 00:00:00 2001 From: fengyang Date: Sat, 30 Nov 2024 15:06:26 +0800 Subject: [PATCH 28/29] push Signed-off-by: fengyang --- frameworks/js/napi/src/reminder/publish.cpp | 2 +- interfaces/inner_api/reminder_request.h | 2 -- services/ans/src/advanced_notification_service.cpp | 2 +- .../ans/src/advanced_notification_service_ability.cpp | 1 - services/reminder/include/reminder_data_manager.h | 6 +++--- .../include/reminder_os_account_manager_helper.h | 6 +++--- services/reminder/include/reminder_store.h | 1 - services/reminder/src/reminder_data_manager.cpp | 11 ++++++----- .../reminder/src/reminder_notification_inline.cpp | 11 ++++++----- services/reminder/src/reminder_service.cpp | 3 ++- services/reminder/src/reminder_service_ability.cpp | 2 -- services/reminder/src/reminder_store.cpp | 8 +++++--- .../test/unittest/reminder_data_manager_test.cpp | 4 ++-- .../reminderdatamanager_fuzzer.cpp | 5 +++-- 14 files changed, 32 insertions(+), 32 deletions(-) diff --git a/frameworks/js/napi/src/reminder/publish.cpp b/frameworks/js/napi/src/reminder/publish.cpp index af48621f7..9b2a9b4dd 100644 --- a/frameworks/js/napi/src/reminder/publish.cpp +++ b/frameworks/js/napi/src/reminder/publish.cpp @@ -713,7 +713,7 @@ void ParseMaxScreenWantAgent(const napi_env &env, const ReminderRequest &reminde napi_set_named_property(env, maxScreenWantAgentInfo, MAX_SCREEN_WANT_AGENT_ABILITY, info); } -napi_value SetValidReminder(const napi_env &env,const ReminderRequest &reminder, napi_value &result) +napi_value SetValidReminder(const napi_env &env, const ReminderRequest &reminder, napi_value &result) { ANSR_LOGI("enter"); napi_value value = nullptr; diff --git a/interfaces/inner_api/reminder_request.h b/interfaces/inner_api/reminder_request.h index f75fad12e..42eea4fe6 100644 --- a/interfaces/inner_api/reminder_request.h +++ b/interfaces/inner_api/reminder_request.h @@ -1123,8 +1123,6 @@ private: std::vector> actionButtons_ {}; std::string wantAgentStr_{}; std::string maxWantAgentStr_{}; - - // sptr notificationOption_ {nullptr}; }; } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 1a9d388bb..93520accf 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -600,7 +600,7 @@ ErrCode AdvancedNotificationService::FillNotificationRecord( ANS_LOGE("Failed to create notification."); return ERR_ANS_NO_MEMORY; } - //fengyang SetNotificationRemindType(record->notification, true); + SetNotificationRemindType(record->notification, true); record->bundleOption = requestdbObj.bundleOption; ErrCode ret = AssignValidNotificationSlot(record, record->bundleOption); diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index e190d2890..3326601fd 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -46,7 +46,6 @@ void AdvancedNotificationServiceAbility::OnStart() } service_->CreateDialogManager(); service_->InitPublishProcess(); - // reminderAgent_ = ReminderDataManager::InitInstance(service_); #ifdef ENABLE_ANS_EXT_WRAPPER EXTENTION_WRAPPER->InitExtentionWrapper(); diff --git a/services/reminder/include/reminder_data_manager.h b/services/reminder/include/reminder_data_manager.h index f45225523..db3d427ae 100644 --- a/services/reminder/include/reminder_data_manager.h +++ b/services/reminder/include/reminder_data_manager.h @@ -56,7 +56,7 @@ public: * @param uid Indicates the uid which the bundle belong to. * @return ERR_OK if success, else not. */ - ErrCode CancelAllReminders(const int32_t userId, const int32_t uid); + ErrCode CancelAllReminders(const std::string& packageName, const int32_t userId, const int32_t uid); /** * @brief Cancels the target reminder relative to the reminder id and bundle option. @@ -358,7 +358,8 @@ private: * @param packageName Indicates the packageName need to cancel. * @param userId Indicates the userId to cancel. */ - void CancelRemindersImplLocked(const int32_t userId, const int32_t uid, bool isCancelAllPackage = false); + void CancelRemindersImplLocked(const std::string& bundleName, + const int32_t userId, const int32_t uid, bool isCancelAllPackage = false); /** * @brief Close reminders with the same group id. @@ -743,7 +744,6 @@ private: std::mutex timeLoadMutex_; int32_t reminderLoadtimerId_ {0}; - }; } // namespace OHOS } // namespace Notification diff --git a/services/reminder/include/reminder_os_account_manager_helper.h b/services/reminder/include/reminder_os_account_manager_helper.h index f98d740e1..16f443357 100644 --- a/services/reminder/include/reminder_os_account_manager_helper.h +++ b/services/reminder/include/reminder_os_account_manager_helper.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H -#define NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H +#ifndef DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H +#define DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H #include "errors.h" #include "singleton.h" @@ -52,4 +52,4 @@ public: }; } // namespace OHOS } // namespace Notification -#endif // NOTIFICATION_DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file +#endif // DISTRIBUTED_NOTIFICATION_SERVICE_SERVICES_REMINDER_INCLUDE_REMINDER_OS_ACCOUNT_MANAGER_HELPER_H \ No newline at end of file diff --git a/services/reminder/include/reminder_store.h b/services/reminder/include/reminder_store.h index 4cdd7704a..b80fb1c59 100644 --- a/services/reminder/include/reminder_store.h +++ b/services/reminder/include/reminder_store.h @@ -86,7 +86,6 @@ private: std::shared_ptr Query(const std::string& tableName, const std::string& colums, const int32_t reminderId); std::shared_ptr Query(const std::string& queryCondition) const; - private: std::shared_ptr rdbStore_ = nullptr; diff --git a/services/reminder/src/reminder_data_manager.cpp b/services/reminder/src/reminder_data_manager.cpp index d35ef18f5..f9825adf9 100644 --- a/services/reminder/src/reminder_data_manager.cpp +++ b/services/reminder/src/reminder_data_manager.cpp @@ -140,11 +140,12 @@ ErrCode ReminderDataManager::CancelReminder( return ERR_OK; } -ErrCode ReminderDataManager::CancelAllReminders(const int32_t userId, const int32_t callingUid) +ErrCode ReminderDataManager::CancelAllReminders(const std::string& bundleName, + const int32_t userId, const int32_t callingUid) { HITRACE_METER_NAME(HITRACE_TAG_OHOS, __PRETTY_FUNCTION__); ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); - CancelRemindersImplLocked(userId, callingUid); + CancelRemindersImplLocked(bundleName, userId, callingUid); return ERR_OK; } @@ -238,10 +239,10 @@ void ReminderDataManager::GetValidReminders( void ReminderDataManager::CancelAllReminders(const int32_t userId) { ANSR_LOGD("CancelAllReminders, userId=%{private}d", userId); - CancelRemindersImplLocked(userId, -1, true); + CancelRemindersImplLocked(ALL_PACKAGES, userId, -1, true); } -void ReminderDataManager::CancelRemindersImplLocked(const int32_t userId, +void ReminderDataManager::CancelRemindersImplLocked(const std::string& packageName, const int32_t userId, const int32_t uid, bool isCancelAllPackage) { MUTEX.lock(); @@ -269,7 +270,7 @@ void ReminderDataManager::CancelRemindersImplLocked(const int32_t userId, if (isCancelAllPackage) { store_->DeleteUser(userId); } else { - store_->Delete(userId, uid); + store_->Delete(packageName, userId, uid); } MUTEX.unlock(); StartRecentReminder(); diff --git a/services/reminder/src/reminder_notification_inline.cpp b/services/reminder/src/reminder_notification_inline.cpp index 222a12560..aa66101d4 100644 --- a/services/reminder/src/reminder_notification_inline.cpp +++ b/services/reminder/src/reminder_notification_inline.cpp @@ -34,19 +34,20 @@ namespace OHOS { namespace Notification { #define REMINDER_CHECK_NULL_VOID(ptr, msg) \ do { \ - if (ptr == nullptr) { \ + if ((ptr) == nullptr) { \ ANSR_LOGW("%{public}s", msg); \ return; \ } \ - } while(0) - + } while (0) + #define REMINDER_CHECK_NULL_RETURN(ptr, msg, ret) \ do { \ - if (ptr == nullptr) { \ + if ((ptr) == nullptr) { \ ANSR_LOGW("%{public}s", msg); \ return ret; \ } \ - } while(0) + } while (0) + inline std::string GetClientBundleNameByUid(int32_t callingUid) { std::string bundle; diff --git a/services/reminder/src/reminder_service.cpp b/services/reminder/src/reminder_service.cpp index 130fe456f..6e7e457c3 100644 --- a/services/reminder/src/reminder_service.cpp +++ b/services/reminder/src/reminder_service.cpp @@ -213,13 +213,14 @@ ErrCode ReminderService::CancelAllReminders() return ERR_REMINDER_PERMISSION_DENIED; } int32_t callingUid = IPCSkeleton::GetCallingUid(); + std::string bundleName = GetClientBundleName(); int32_t userId = -1; AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(callingUid, userId); auto rdm = ReminderDataManager::GetInstance(); if (rdm == nullptr) { return ERR_NO_INIT; } - ErrCode result = rdm->CancelAllReminders(userId, callingUid); + ErrCode result = rdm->CancelAllReminders(bundleName, userId, callingUid); TryPostDelayUnloadTask(DELAY_TIME); return result; } diff --git a/services/reminder/src/reminder_service_ability.cpp b/services/reminder/src/reminder_service_ability.cpp index db3966ecc..b6d3edabe 100644 --- a/services/reminder/src/reminder_service_ability.cpp +++ b/services/reminder/src/reminder_service_ability.cpp @@ -14,8 +14,6 @@ */ #include "reminder_service_ability.h" -// #include "system_event_observer.h" -// #include "common_event_manager.h" namespace OHOS { namespace Notification { diff --git a/services/reminder/src/reminder_store.cpp b/services/reminder/src/reminder_store.cpp index 719663acb..2dd53d4ef 100644 --- a/services/reminder/src/reminder_store.cpp +++ b/services/reminder/src/reminder_store.cpp @@ -351,7 +351,8 @@ __attribute__((no_sanitize("cfi"))) int32_t ReminderStore::Delete(const std::str + " WHERE " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); - std::string baseCondtion = ReminderBaseTable::USER_ID + " = " + std::to_string(userId); + std::string baseCondtion = ReminderBaseTable::PACKAGE_NAME + " = '" + pkg + "' AND " + + ReminderBaseTable::USER_ID + " = " + std::to_string(userId); if (uid != -1) { assoConditon += " AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::UID @@ -433,7 +434,7 @@ __attribute__((no_sanitize("cfi"))) std::vector> ReminderS + ReminderBaseTable::TABLE_NAME + " WHERE (" + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::IS_EXPIRED + " = 'false' AND " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::REMINDER_TYPE + " != 1 AND " - + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::TRIGGER_TIME + " < " + + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::TRIGGER_TIME + " < " + std::to_string(nowTime + HALF_HOUR) + ") OR " + ReminderBaseTable::TABLE_NAME + "." + ReminderBaseTable::REMINDER_ID + " IN " + "(SELECT" + ReminderBaseTable::REMINDER_ID + " FROM " + ReminderCalendarTable::TABLE_NAME @@ -841,7 +842,8 @@ int32_t ReminderStore::QueryActiveReminderCount() int64_t nowTime = GetCurrentTime(); queryCondition.append(ReminderCalendarTable::TABLE_NAME).append(" WHERE (") .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append(" < ").append(std::to_string(nowTime)).append(" AND ") - .append(ReminderCalendarTable::CALENDAR_END_DATE_TIME).append(" > ").append(std::to_string(nowTime)).append(" ) OR ") + .append(ReminderCalendarTable::CALENDAR_END_DATE_TIME) + .append(" > ").append(std::to_string(nowTime)).append(" ) OR ") .append(ReminderCalendarTable::CALENDAR_DATE_TIME).append("> ").append(std::to_string(nowTime)); resultSet = rdbStore_->QuerySql(queryCondition, whereArgs); int32_t calenderTableNum = 0; diff --git a/services/reminder/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp index 086bf8810..4f73f50f2 100644 --- a/services/reminder/test/unittest/reminder_data_manager_test.cpp +++ b/services/reminder/test/unittest/reminder_data_manager_test.cpp @@ -71,7 +71,7 @@ HWTEST_F(ReminderDataManagerTest, ReminderDataManagerTest_001, Level1) int32_t reminderId = -1; manager->PublishReminder(reminder, reminderId); manager->CancelReminder(reminderId, -1); - manager->CancelAllReminders(-1, -1); + manager->CancelAllReminders("", -1, -1); manager->CancelAllReminders(-1); manager->IsMatched(reminder, -1, -1, true); system("rm -rf /data/service/el1/public/notification/"); @@ -770,7 +770,7 @@ HWTEST_F(ReminderDataManagerTest, InitStartExtensionAbility_0001, Level1) */ HWTEST_F(ReminderDataManagerTest, CancelAllReminders_00001, Level1) { - int32_t ret = manager->CancelAllReminders(-1, -1); + int32_t ret = manager->CancelAllReminders("", -1, -1); EXPECT_TRUE(ret == ERR_OK); ret = manager->CancelAllReminders(100, 20020152); diff --git a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp index 933dffbb6..d7d6087ce 100644 --- a/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp +++ b/test/fuzztest/reminderdatamanager_fuzzer/reminderdatamanager_fuzzer.cpp @@ -21,6 +21,7 @@ namespace OHOS { bool DoSomethingInterestingWithManager(FuzzedDataProvider* fdp) { + std::string bundleName = fdp->ConsumeRandomLengthString(); int32_t userId = fdp->ConsumeIntegral(); int32_t uid = fdp->ConsumeIntegral(); int32_t reminderId = fdp->ConsumeIntegral(); @@ -36,7 +37,7 @@ namespace OHOS { auto manager = Notification::ReminderDataManager::GetInstance(); manager->Init(false); manager->Dump(); - manager->CancelAllReminders(userId, uid); + manager->CancelAllReminders(bundleName, userId, uid); manager->CancelReminder(reminderId, callingUid); manager->CheckExcludeDateParam(reminderId, callingUid); manager->AddExcludeDate(reminderId, date, callingUid); @@ -88,7 +89,7 @@ namespace OHOS { manager->CheckUpdateConditions(reminder, Notification::ReminderRequest::ActionButtonType::INVALID, reminder->GetActionButtons()); manager->GetCustomRingUri(reminder); - manager->CancelRemindersImplLocked(userId, uid, value); + manager->CancelRemindersImplLocked(bundleName, userId, uid, value); manager->CloseRemindersByGroupId(reminderId, bundleName, bundleName); manager->CancelNotification(reminder); manager->CheckReminderLimitExceededLocked(callingUid, reminder); -- Gitee From 091336e5cd16f1fe037cb43f32145d2dbfbc4171 Mon Sep 17 00:00:00 2001 From: fengyang Date: Mon, 2 Dec 2024 10:10:27 +0800 Subject: [PATCH 29/29] push Signed-off-by: fengyang --- services/reminder/src/reminder_event_manager.cpp | 3 ++- services/reminder/src/reminder_store_strategy.cpp | 1 - services/reminder/test/unittest/reminder_data_manager_test.cpp | 2 +- services/reminder/test/unittest/reminder_store_test.cpp | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/reminder/src/reminder_event_manager.cpp b/services/reminder/src/reminder_event_manager.cpp index addb0884a..3ce88f932 100644 --- a/services/reminder/src/reminder_event_manager.cpp +++ b/services/reminder/src/reminder_event_manager.cpp @@ -222,9 +222,10 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(const EventFwk::Want &want) const { OHOS::AppExecFwk::ElementName ele = want.GetElement(); + std::string bundleName = ele.GetBundleName(); int32_t userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); int32_t uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); - reminderDataManager_->CancelAllReminders(userId, uid); + reminderDataManager_->CancelAllReminders(bundleName, userId, uid); } void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(const EventFwk::Want &want) const diff --git a/services/reminder/src/reminder_store_strategy.cpp b/services/reminder/src/reminder_store_strategy.cpp index 7192c2142..adf3c0085 100644 --- a/services/reminder/src/reminder_store_strategy.cpp +++ b/services/reminder/src/reminder_store_strategy.cpp @@ -355,7 +355,6 @@ void ReminderStrategy::RecoverFromDb(sptr& reminder, ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::ACTION_BUTTON_INFO, actionButtons); reminder->DeserializeButtonInfo(actionButtons); - // fengyang reminder->InitNotificationRequest(); // must set before wantAgent & maxScreenWantAgent std::string wantAgent; ReminderStrategy::GetRdbValue(resultSet, ReminderBaseTable::WANT_AGENT, wantAgent); reminder->DeserializeWantAgent(wantAgent, 0); diff --git a/services/reminder/test/unittest/reminder_data_manager_test.cpp b/services/reminder/test/unittest/reminder_data_manager_test.cpp index 4f73f50f2..ddfca76e6 100644 --- a/services/reminder/test/unittest/reminder_data_manager_test.cpp +++ b/services/reminder/test/unittest/reminder_data_manager_test.cpp @@ -773,7 +773,7 @@ HWTEST_F(ReminderDataManagerTest, CancelAllReminders_00001, Level1) int32_t ret = manager->CancelAllReminders("", -1, -1); EXPECT_TRUE(ret == ERR_OK); - ret = manager->CancelAllReminders(100, 20020152); + ret = manager->CancelAllReminders("", 100, 20020152); EXPECT_TRUE(ret == ERR_OK); } diff --git a/services/reminder/test/unittest/reminder_store_test.cpp b/services/reminder/test/unittest/reminder_store_test.cpp index 2a4e67e2e..d629397c3 100644 --- a/services/reminder/test/unittest/reminder_store_test.cpp +++ b/services/reminder/test/unittest/reminder_store_test.cpp @@ -120,7 +120,7 @@ HWTEST_F(ReminderStoreTest, Delete_00002, Function | SmallTest | Level1) { int32_t userId = 1; ReminderStore reminderStore; - int32_t ret = reminderStore.Delete(userId, -1); + int32_t ret = reminderStore.Delete("", userId, -1); EXPECT_EQ(ret, -1); } -- Gitee