diff --git a/README_zh.md b/README_zh.md index 4004597ce4ad23b8d4a3048c726a2ce9bed72300..dc90cb2735a133f031dbd89c4a25c08a9d57b131 100644 --- a/README_zh.md +++ b/README_zh.md @@ -45,7 +45,7 @@ ANS支持4种类型的通道,分别为: - 多行文本 - 社交 -并且可调整通知的分发时间、角标数字、分组、触发事件等属性。 +并且可调整通知的标签、分组、触发事件等属性。 ## 相关仓 diff --git a/ohos.build b/bundle.json similarity index 30% rename from ohos.build rename to bundle.json index 747cde429e369f12c3689bc4e4b002f292cd031c..397bdfd5026b61bb5be01bfb2f07f482698127dd 100644 --- a/ohos.build +++ b/bundle.json @@ -1,23 +1,93 @@ { - "parts": { - "ans_standard": { - "module_list": [ + "name": "@ohos/distributed_notification_service", + "version": "", + "description": "为应用程序提供发布通知的能力", + "homePage": "https://gitee.com/openharmony", + "license": "Apache V2", + "repository": "https://gitee.com/openharmony/notification_ans_standard", + "domain": "os", + "language": "", + "publishAs": "code-segment", + "private": false, + "scripts": {}, + "tags": [ + "base" + ], + "keywords": [ + "notification", + "ans" + ], + "envs": [], + "dirs": [], + "author": { + "name": "", + "email": "", + "url": "" + }, + "contributors": [ + { + "name": "", + "email": "", + "url": "" + } + ], + "segment": { + "destPath": "base/notification/ans_standard" + }, + "component": { + "name": "ans_standard", + "subsystem": "notification", + "syscap": [ + "SystemCapability.DistributedNotificationService" + ], + "features": [], + "adapted_system_type": [ + "standard" + ], + "rom": "3000KB", + "ram": "16000KB", + "deps": { + "components": [ + "samgr_standard", + "ipc", + "aafwk_standard", + "dmsfwk_standard", + "multimedia_image_standard", + "hiviewdfx_hilog_native", + "appexecfwk_standard", + "time_native", + "ces_standard", + "napi", + "safwk", + "distributeddatamgr", + "os_account_innerkits" + ], + "third_party": [ + "jsoncpp", + "libuv", + "icu", + "node", + "json" + ] + }, + "build": { + "sub_component": [ "//base/notification/ans_standard/frameworks:frameworks_target", "//base/notification/ans_standard/interfaces:interfaces_target", "//base/notification/ans_standard/sa_profile:ans_sa_profile", "//base/notification/ans_standard/services:services_target", "//base/notification/ans_standard/tools:tools_target" ], - "inner_kits": [ - ], - "test_list": [ + "inner_kits": [], + "test": [ "//base/notification/ans_standard/services/ans/test/unittest:ans_unit_test", + "//base/notification/ans_standard/services/distributed/test/unittest:ans_distributed_unit_test_target", "//base/notification/ans_standard/services/test/moduletest:ans_module_test", "//base/notification/ans_standard/frameworks/ans/test/moduletest:moduletest", + "//base/notification/ans_standard/frameworks/ans/native/test/unittest:ans_reminder_unit_test", "//base/notification/ans_standard/frameworks/wantagent/test/:unittest", "//base/notification/ans_standard/test:systemtest" ] } - }, - "subsystem": "notification" -} \ No newline at end of file + } +} diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 4929685205d0f14417400725acb9f5fd5078f20a..8cf575c0b090f713afbe6861b4d41eca97c445c4 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -27,15 +27,18 @@ config("public_ans_core_config") { "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", - "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//utils/native/base/include", + "//third_party/json/single_include", "//third_party/jsoncpp/include", ] + + cflags_cc = [ "-fexceptions" ] } ohos_shared_library("ans_core") { sources = [ "${core_path}/common/src/ans_log_wrapper.cpp", + "${core_path}/src/ans_image_util.cpp", "${core_path}/src/ans_manager_death_recipient.cpp", "${core_path}/src/ans_manager_proxy.cpp", "${core_path}/src/ans_manager_stub.cpp", @@ -51,6 +54,9 @@ ohos_shared_library("ans_core") { "${frameworks_path}/ans/native/src/notification_content.cpp", "${frameworks_path}/ans/native/src/notification_conversational_content.cpp", "${frameworks_path}/ans/native/src/notification_conversational_message.cpp", + "${frameworks_path}/ans/native/src/notification_distributed_options.cpp", + "${frameworks_path}/ans/native/src/notification_do_not_disturb_date.cpp", + "${frameworks_path}/ans/native/src/notification_flags.cpp", "${frameworks_path}/ans/native/src/notification_helper.cpp", "${frameworks_path}/ans/native/src/notification_long_text_content.cpp", "${frameworks_path}/ans/native/src/notification_media_content.cpp", @@ -64,7 +70,13 @@ ohos_shared_library("ans_core") { "${frameworks_path}/ans/native/src/notification_sorting_map.cpp", "${frameworks_path}/ans/native/src/notification_subscribe_info.cpp", "${frameworks_path}/ans/native/src/notification_subscriber.cpp", + "${frameworks_path}/ans/native/src/notification_template.cpp", "${frameworks_path}/ans/native/src/notification_user_input.cpp", + "${frameworks_path}/ans/native/src/reminder_helper.cpp", + "${frameworks_path}/ans/native/src/reminder_request.cpp", + "${frameworks_path}/ans/native/src/reminder_request_alarm.cpp", + "${frameworks_path}/ans/native/src/reminder_request_calendar.cpp", + "${frameworks_path}/ans/native/src/reminder_request_timer.cpp", ] configs = [ ":private_config" ] @@ -73,17 +85,20 @@ ohos_shared_library("ans_core") { deps = [ "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "multimedia_image_standard:image_native", + "samgr_standard:samgr_proxy", + "time_native:time_service", ] part_name = "ans_standard" diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 353899e52df69d5b48dfff7777d8ed701d1adf7c..9d842d285bdde4f22acb818e398e2f356fd4ad90 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -16,9 +16,14 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H #define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_CONST_DEFINE_H +#include + +#include "uri.h" + +#include "notification_constant.h" + namespace OHOS { namespace Notification { - // Max active notification number constexpr uint32_t MAX_ACTIVE_NUM = 1000; constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; @@ -27,7 +32,26 @@ constexpr uint32_t MAX_SLOT_NUM = 5; constexpr uint32_t MAX_SLOT_GROUP_NUM = 4; constexpr uint32_t MAX_ICON_SIZE = 50 * 1024; constexpr uint32_t MAX_PICTURE_SIZE = 2 * 1024 * 1024; +constexpr bool SUPPORT_DO_NOT_DISTRUB = true; +constexpr uint32_t SYSTEM_SERVICE_UID = 1000; + +constexpr int32_t SUBSCRIBE_USER_INIT = -1; +constexpr int32_t SUBSCRIBE_USER_ALL = -2; +constexpr int32_t SUBSCRIBE_USER_SYSTEM_BEGIN = 0; +constexpr int32_t SUBSCRIBE_USER_SYSTEM_END = 99; + +// Default sound for notification +const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); +const static std::vector DEFAULT_NOTIFICATION_VIBRATION = {200}; + +// Default path for template +const static std::string DEFAULT_TEMPLATE_PATH("/system/etc/NotificationTemplate/external.json"); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +constexpr NotificationConstant::DistributedReminderPolicy DEFAULT_DISTRIBUTED_REMINDER_POLICY = + NotificationConstant::DistributedReminderPolicy::DEFAULT; +constexpr bool DEFAULT_DISTRIBUTED_ENABLE_IN_APPLICATION_INFO = false; +#endif } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index 3552497d156d00306a96e074c4a3541276b4b90b..d8a4581b0ea10a88e188970d361257f88bdea9f4 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -46,6 +46,7 @@ enum ErrorCode : uint32_t { ERR_ANS_SERVICE_NOT_CONNECTED, ERR_ANS_INVALID_PARAM, ERR_ANS_INVALID_UID, + ERR_ANS_NOT_SYSTEM_SERVICE, ERR_ANS_INVALID_PID, ERR_ANS_INVALID_BUNDLE, ERR_ANS_NOT_ALLOWED, @@ -55,6 +56,7 @@ enum ErrorCode : uint32_t { ERR_ANS_NO_MEMORY, ERR_ANS_TASK_ERR, ERR_ANS_NON_SYSTEM_APP, + ERR_ANS_PERMISSION_DENIED, ERR_ANS_NOTIFICATION_NOT_EXISTS, ERR_ANS_NOTIFICATION_IS_UNREMOVABLE, ERR_ANS_OVER_MAX_ACITVE_PERSECOND, @@ -67,6 +69,10 @@ enum ErrorCode : uint32_t { ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST, ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID, ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_EXCEED_MAX_NUM, + ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED, + ERR_ANS_DISTRIBUTED_OPERATION_FAILED, + ERR_ANS_DISTRIBUTED_GET_INFO_FAILED, + ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED, }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/common/include/ans_log_wrapper.h b/frameworks/ans/core/common/include/ans_log_wrapper.h index 3f03294f465bd7eceec7d115770979fada7ad473..cbcc8a923dc870f735c88a3c881e91622965cb0e 100644 --- a/frameworks/ans/core/common/include/ans_log_wrapper.h +++ b/frameworks/ans/core/common/include/ans_log_wrapper.h @@ -22,7 +22,6 @@ namespace OHOS { namespace Notification { - #ifndef LOG_DOMAIN #define LOG_DOMAIN 0xD001800 #endif @@ -34,6 +33,7 @@ namespace Notification { enum class AnsLogLevel : uint8_t { DEBUG = 0, INFO, WARN, ERROR, FATAL }; static constexpr OHOS::HiviewDFX::HiLogLabel ANS_LABEL = {LOG_CORE, LOG_DOMAIN, "ANS_STANDARD"}; +static constexpr OHOS::HiviewDFX::HiLogLabel ANS_REMINDER_LABEL = {LOG_CORE, LOG_DOMAIN, "ANS_REMINDER"}; class AnsLogWrapper { public: @@ -72,6 +72,21 @@ private: #define ANS_LOGW(fmt, ...) PRINT_LOG(WARN, Warn, fmt, ##__VA_ARGS__) #define ANS_LOGE(fmt, ...) PRINT_LOG(ERROR, Error, fmt, ##__VA_ARGS__) #define ANS_LOGF(fmt, ...) PRINT_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) + +#define PRINT_REMINDER_LOG(LEVEL, Level, fmt, ...) \ + if (AnsLogWrapper::JudgeLevel(AnsLogLevel::LEVEL)) \ + OHOS::HiviewDFX::HiLog::Level(ANS_REMINDER_LABEL, \ + "[%{public}s(%{public}s):%{public}d] " fmt, \ + AnsLogWrapper::GetBriefFileName(__FILE__).c_str(), \ + __FUNCTION__, \ + __LINE__, \ + ##__VA_ARGS__) + +#define ANSR_LOGD(fmt, ...) PRINT_REMINDER_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define ANSR_LOGI(fmt, ...) PRINT_REMINDER_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define ANSR_LOGW(fmt, ...) PRINT_REMINDER_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define ANSR_LOGE(fmt, ...) PRINT_REMINDER_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define ANSR_LOGF(fmt, ...) PRINT_REMINDER_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/include/ans_image_util.h b/frameworks/ans/core/include/ans_image_util.h new file mode 100644 index 0000000000000000000000000000000000000000..8478efabe385a9a7db1bdbcd40722911ac1c4cdd --- /dev/null +++ b/frameworks/ans/core/include/ans_image_util.h @@ -0,0 +1,52 @@ +/* + * 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_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_IMAGE_UTIL_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_IMAGE_UTIL_H + +#include +#include +#include "pixel_map.h" + +namespace OHOS { +namespace Notification { +class AnsImageUtil { +public: + static const std::string IMAGE_FORMAT_JPEG; + static const uint8_t IMAGE_QUALITY; + static const uint8_t SHIFT_FOUR; + static const uint8_t NUM_TEN; + static const size_t TWO_TIMES; + + static std::string PackImage( + const std::shared_ptr &pixelMap, const std::string &format = IMAGE_FORMAT_JPEG); + + static std::shared_ptr UnPackImage(const std::string &pixelMapStr); + + static bool PackImage2File( + const std::shared_ptr &pixelMap, + const std::string &outFilePath, + const std::string &format = IMAGE_FORMAT_JPEG); + + static std::shared_ptr CreatePixelMap( + const std::string &inFilePath, const std::string &format = IMAGE_FORMAT_JPEG); + + static std::string BinToHex(const std::string &strBin); + + static std::string HexToBin(const std::string &strHex); +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_ANS_IMAGE_UTIL_H diff --git a/frameworks/ans/core/include/ans_manager_death_recipient.h b/frameworks/ans/core/include/ans_manager_death_recipient.h index a726115e961eb032ce4a5685808f3a3667e64857..671a4e33dc405b564d78839d1d6c880fc056f781 100644 --- a/frameworks/ans/core/include/ans_manager_death_recipient.h +++ b/frameworks/ans/core/include/ans_manager_death_recipient.h @@ -27,7 +27,6 @@ public: virtual void OnRemoteDied(const wptr &object) override; }; - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 9f71a1a09577848b01d207cf34740fbe5d78ff1e..f2e65ab62d9a0e683c734de3179fa10bc6f23279 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -23,11 +23,12 @@ #include "iremote_broker.h" #include "notification_bundle_option.h" #include "notification_constant.h" +#include "notification_do_not_disturb_date.h" #include "notification_request.h" #include "notification_slot.h" #include "notification_slot_group.h" -#include "notification_sorting.h" #include "notification_subscribe_info.h" +#include "reminder_request.h" namespace OHOS { namespace Notification { @@ -68,8 +69,6 @@ public: const sptr notification, const std::string &representativeBundle) = 0; virtual ErrCode SetNotificationBadgeNum(int num) = 0; virtual ErrCode GetBundleImportance(int &importance) = 0; - virtual ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) = 0; - virtual ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) = 0; virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) = 0; virtual ErrCode SetPrivateNotificationsAllowed(bool allow) = 0; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) = 0; @@ -104,7 +103,29 @@ public: virtual ErrCode IsAllowedNotify(bool &allowed) = 0; virtual ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) = 0; + virtual ErrCode SetDoNotDisturbDate(const sptr &date) = 0; + virtual ErrCode GetDoNotDisturbDate(sptr &date) = 0; + virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) = 0; + + virtual ErrCode CancelGroup(const std::string &groupName) = 0; + virtual ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) = 0; + + virtual ErrCode IsDistributedEnabled(bool &enabled) = 0; + virtual ErrCode EnableDistributed(bool enabled) = 0; + virtual ErrCode EnableDistributedByBundle(const sptr &bundleOption, bool enabled) = 0; + virtual ErrCode EnableDistributedSelf(bool enabled) = 0; + virtual ErrCode IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) = 0; + virtual ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType) = 0; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) = 0; + virtual ErrCode PublishContinuousTaskNotification(const sptr &request) = 0; + virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) = 0; + virtual ErrCode PublishReminder(sptr &reminder) = 0; + virtual ErrCode CancelReminder(const int32_t reminderId) = 0; + virtual ErrCode GetValidReminders(std::vector> &reminders) = 0; + virtual ErrCode CancelAllReminders() = 0; + virtual ErrCode IsSupportTemplate(const std::string &templateName, bool &support) = 0; protected: enum TransactId : uint32_t { @@ -133,8 +154,6 @@ protected: PUBLISH_AS_BUNDLE, SET_NOTIFICATION_BADGE_NUM, GET_BUNDLE_IMPORTANCE, - SET_DISTURB_MODE, - GET_DISTURB_MODE, IS_NOTIFICATION_POLICY_ACCESS_GRANTED, SET_PRIVATIVE_NOTIFICATIONS_ALLOWED, GET_PRIVATIVE_NOTIFICATIONS_ALLOWED, @@ -158,7 +177,25 @@ protected: GET_CURRENT_APP_SORTING, IS_ALLOWED_NOTIFY, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, + SET_DO_NOT_DISTURB_DATE, + GET_DO_NOT_DISTURB_DATE, + DOES_SUPPORT_DO_NOT_DISTURB_MODE, + CANCEL_GROUP, + REMOVE_GROUP_BY_BUNDLE, + IS_DISTRIBUTED_ENABLED, + ENABLE_DISTRIBUTED, + ENABLE_DISTRIBUTED_BY_BUNDLE, + ENABLE_DISTRIBUTED_SELF, + IS_DISTRIBUTED_ENABLED_BY_BUNDLE, + GET_DEVICE_REMIND_TYPE, SHELL_DUMP, + PUBLISH_CONTINUOUS_TASK_NOTIFICATION, + CANCEL_CONTINUOUS_TASK_NOTIFICATION, + PUBLISH_REMINDER, + CANCEL_REMINDER, + CANCEL_ALL_REMINDERS, + GET_ALL_VALID_REMINDERS, + IS_SUPPORT_TEMPLATE }; }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index 80214ca52d69ff6b41e7a4684657eb58f1c7449f..feed3ff2a628c804a2b7f80f6467cc46f1f591fd 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -57,8 +57,6 @@ public: const sptr notification, const std::string &representativeBundle) override; ErrCode SetNotificationBadgeNum(int num) override; ErrCode GetBundleImportance(int &importance) override; - ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; - ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; @@ -93,7 +91,29 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; + ErrCode SetDoNotDisturbDate(const sptr &date) override; + ErrCode GetDoNotDisturbDate(sptr &date) override; + ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + ErrCode CancelGroup(const std::string &groupName) override; + ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + + ErrCode IsDistributedEnabled(bool &enabled) override; + ErrCode EnableDistributed(bool enabled) override; + ErrCode EnableDistributedByBundle(const sptr &bundleOption, bool enabled) override; + ErrCode EnableDistributedSelf(bool enabled) override; + ErrCode IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) override; + ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + ErrCode PublishContinuousTaskNotification(const sptr &request) override; + ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; + ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; + + ErrCode PublishReminder(sptr &reminder) override; + ErrCode CancelReminder(const int32_t reminderId) override; + ErrCode GetValidReminders(std::vector> &reminders) override; + ErrCode CancelAllReminders() override; private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); @@ -104,6 +124,8 @@ private: template bool ReadParcelableVector(std::vector> &parcelableInfos, MessageParcel &reply, ErrCode &result); static inline BrokerDelegator delegator_; + + ErrCode ReadReminders(uint8_t &count, MessageParcel &reply, std::vector> &reminders); }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index f85ab605042ceddcd5ed8e3a27b2b71cea86ba39..f65b42c3ccc14d819f4f181534be7efaa2c587ab 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -62,8 +62,6 @@ public: const sptr notification, const std::string &representativeBundle) override; virtual ErrCode SetNotificationBadgeNum(int num) override; virtual ErrCode GetBundleImportance(int &importance) override; - virtual ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; - virtual ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; virtual ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; virtual ErrCode SetPrivateNotificationsAllowed(bool allow) override; virtual ErrCode GetPrivateNotificationsAllowed(bool &allow) override; @@ -98,7 +96,30 @@ public: virtual ErrCode IsSpecialBundleAllowedNotify( const sptr &bundleOption, bool &allowed) override; + virtual ErrCode SetDoNotDisturbDate(const sptr &date) override; + virtual ErrCode GetDoNotDisturbDate(sptr &date) override; + virtual ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + virtual ErrCode CancelGroup(const std::string &groupName) override; + virtual ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + + virtual ErrCode IsDistributedEnabled(bool &enabled) override; + virtual ErrCode EnableDistributed(bool enabled) override; + virtual ErrCode EnableDistributedByBundle( + const sptr &bundleOption, bool enabled) override; + virtual ErrCode EnableDistributedSelf(bool enabled) override; + virtual ErrCode IsDistributedEnableByBundle( + const sptr &bundleOption, bool &enabled) override; + virtual ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType) override; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + virtual ErrCode PublishContinuousTaskNotification(const sptr &request) override; + virtual ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; + virtual ErrCode PublishReminder(sptr &reminder) override; + virtual ErrCode CancelReminder(const int32_t reminderId) override; + virtual ErrCode GetValidReminders(std::vector> &reminders) override; + virtual ErrCode CancelAllReminders() override; + virtual ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; private: static const std::map> @@ -129,8 +150,6 @@ private: ErrCode HandlePublishAsBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetNotificationBadgeNum(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetBundleImportance(MessageParcel &data, MessageParcel &reply); - ErrCode HandleSetDisturbMode(MessageParcel &data, MessageParcel &reply); - ErrCode HandleGetDisturbMode(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsNotificationPolicyAccessGranted(MessageParcel &data, MessageParcel &reply); ErrCode HandleSetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetPrivateNotificationsAllowed(MessageParcel &data, MessageParcel &reply); @@ -154,7 +173,25 @@ private: ErrCode HandleGetCurrentAppSorting(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply); + ErrCode HandleEnableDistributed(MessageParcel &data, MessageParcel &reply); + ErrCode HandleEnableDistributedByBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleEnableDistributedSelf(MessageParcel &data, MessageParcel &reply); + ErrCode HandleIsDistributedEnableByBundle(MessageParcel &data, MessageParcel &reply); ErrCode HandleShellDump(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCancelGroup(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveGroupByBundle(MessageParcel &data, MessageParcel &reply); + ErrCode HandleSetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); + ErrCode HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); + ErrCode HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); + 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 HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply); template bool WriteParcelableVector(const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result); diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index 100bb3894fae9ed54f2bc9d9beac170b039d268c..a780fd5aa2cc3688493c71a0de01bdb2265272f0 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -20,11 +20,6 @@ #include "ans_manager_death_recipient.h" #include "ans_manager_interface.h" -#include "notification_bundle_option.h" -#include "notification_request.h" -#include "notification_slot.h" -#include "notification_slot_group.h" -#include "notification_sorting_map.h" #include "notification_subscriber.h" namespace OHOS { @@ -426,7 +421,7 @@ public: * @param bundleOption Indicates the bundle name and uid of the application whose notifications are to be removed. * @return Returns remove notification result. */ - ErrCode RemoveAllNotifications(const NotificationBundleOption &bundleOption); + ErrCode RemoveAllNotifications(const NotificationBundleOption &bundleOption); /** * Removes all removable notifications of a specified bundle. @@ -575,23 +570,131 @@ public: ErrCode GetShowBadgeEnabled(bool &enabled); /** - * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications - * that are allowed to interrupt users. + * Cancel the notification of the specified group of this application. + * + * @param groupName the specified group name. + * @return Returns cancel group result. + */ + ErrCode CancelGroup(const std::string &groupName); + + /** + * Remove the notification of the specified group of the specified application. + * + * @param bundleOption Indicates the bundle name and uid of the specified application. + * @param groupName the specified group name. + * @return Returns remove group by bundle result. + */ + ErrCode RemoveGroupByBundle(const NotificationBundleOption &bundleOption, const std::string &groupName); + + /** + * Sets the do not disturb time. + * @note Your application must have system signature to call this method. + * + * @param doNotDisturbDate Indicates the do not disturb time to set. + * @return Returns set do not disturb time result. + */ + ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Obtains the do not disturb time. + * @note Your application must have system signature to call this method. + * + * @param doNotDisturbDate Indicates the do not disturb time to get. + * @return Returns set do not disturb time result. + */ + ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Obtains the flag that whether to support do not disturb mode. + * + * @param doesSupport Specifies whether to support do not disturb mode. + * @return Returns check result. + */ + ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + + /** + * Check if the device supports distributed notification. + * + * @param enabled True if the device supports distributed notification; false otherwise. + * @return Returns is distributed enabled result. + */ + ErrCode IsDistributedEnabled(bool &enabled); + + /** + * Set whether the device supports distributed notifications. + * + * @param enable Specifies whether to enable the device to support distributed notification. + * The value true indicates that the device is enabled to support distributed notifications, and + * the value false indicates that the device is forbidden to support distributed notifications. + * @return Returns enable distributed result. + */ + ErrCode EnableDistributed(const bool enabled); + + /** + * Set whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled Specifies whether to enable an application to support distributed notification. + * The value true indicates that the application is enabled to support distributed notifications, + * and the value false indicates that the application is forbidden to support distributed + * notifications. + * @return Returns enable distributed by bundle result. + */ + ErrCode EnableDistributedByBundle(const NotificationBundleOption &bundleOption, const bool enabled); + + /** + * Set whether this application supports distributed notifications. + * + * @param enabled Specifies whether to enable this application to support distributed notification. + * The value true indicates that this application is enabled to support distributed notifications, + * and the value false indicates that this application is forbidden to support distributed + * notifications. + * @return Returns enable distributed self result. + */ + ErrCode EnableDistributedSelf(const bool enabled); + + /** + * Check whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled True if the application supports distributed notification; false otherwise. + * @return Returns is distributed enabled by bundle result. + */ + ErrCode IsDistributedEnableByBundle(const NotificationBundleOption &bundleOption, bool &enabled); + + /** + * Obtains the device remind type. * @note Your application must have system signature to call this method. * - * @param mode Indicates the Do Not Disturb mode to set. The value must be - * {NotificationConstant.DisturbMode.ALLOW_ALL}, {NotificationConstant.DisturbMode.ALLOW_PRIORITY}, - * {NotificationConstant.DisturbMode.ALLOW_NONE}, or {NotificationConstant.DisturbMode.ALLOW_ALARMS}. - * @return Returns set disturb mode result. + * @param remindType Indicates the device remind type to get. + * @return Returns get device reminder type result. + */ + ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType); + + /** + * Publishes a continuous task notification. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish continuous task notification result. */ - ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); + ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); /** - * Obtains the Disturb Mode. - * @param disturbMode The current type of the Do Not Disturb mode. - * @return Returns get disturb mode result. + * Cancels a published continuous task notification matching the specified label and notificationId. + * + * @param label Indicates the label of the continuous task notification to cancel. + * @param notificationId Indicates the ID of the continuous task notification to cancel. + * @return Returns cancel continuous task notification result. + */ + ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId); + + /** + * Obtains whether the template is supported by the system. + * + * @param support whether is it a system supported template. + * @return Returns check result. */ - ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); + ErrCode IsSupportTemplate(const std::string &templateName, bool &support); /** * Reset ans manager proxy when OnRemoteDied called. @@ -603,6 +706,36 @@ public: */ ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo); + /** + * Publishes a scheduled reminder. + * + * @param reminder Indicates a reminder. + * @return Returns publish result. + */ + ErrCode PublishReminder(ReminderRequest &reminder); + + /** + * Cancels a specified reminder. + * + * @return Returns cancel result. + */ + ErrCode CancelReminder(const int32_t reminderId); + + /** + * Cancels all reminders of current third part application. + * + * @return Returns cancel result. + */ + ErrCode CancelAllReminders(); + + /** + * 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); + private: /** * Get Ans Manager proxy. @@ -618,6 +751,21 @@ private: */ bool CanPublishMediaContent(const NotificationRequest &request) const; + /** + * Check whether the picture size exceeds the limit in PixelMap + * + * @return Returns true if the limit size is exceeded; returns false otherwise. + */ + bool CheckImageOverSizeForPixelMap( + const std::shared_ptr &pixelMap, uint32_t maxSize); + + /** + * Check whether the picture size exceeds the limit in NotificationRequest's content + * + * @return the ErrCode. + */ + ErrCode CheckImageSizeForContent(const NotificationRequest &request); + /** * Check whether the picture size exceeds the limit * @@ -625,12 +773,18 @@ private: */ ErrCode CheckImageSize(const NotificationRequest &request); + /** + * Check whether the notification doesn't support distribution + * + * @return Returns true if the notification doesn't support distribution; returns false otherwise. + */ + bool IsNonDistributedNotificationType(const NotificationContent::Type &type); + private: std::mutex mutex_; sptr ansManagerProxy_; sptr recipient_; }; - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/include/ans_subscriber_interface.h b/frameworks/ans/core/include/ans_subscriber_interface.h index 539f22a6005d18cf0ff2d8b6e18fb512ea91e182..326680107b45f00493ef7b0a534d35aa3f507272 100644 --- a/frameworks/ans/core/include/ans_subscriber_interface.h +++ b/frameworks/ans/core/include/ans_subscriber_interface.h @@ -20,6 +20,7 @@ #include "notification.h" #include "notification_constant.h" +#include "notification_do_not_disturb_date.h" #include "notification_request.h" #include "notification_sorting.h" #include "notification_sorting_map.h" @@ -34,8 +35,8 @@ public: DECLARE_INTERFACE_DESCRIPTOR(u"OHOS.Notification.IAnsSubscriber"); - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) = 0; - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) = 0; + virtual void OnConnected() = 0; + virtual void OnDisconnected() = 0; virtual void OnConsumed(const sptr ¬ification) = 0; virtual void OnConsumed( const sptr ¬ification, const sptr ¬ificationMap) = 0; @@ -43,18 +44,18 @@ public: virtual void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) = 0; virtual void OnUpdated(const sptr ¬ificationMap) = 0; - virtual void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) = 0; + virtual void OnDoNotDisturbDateChange(const sptr &date) = 0; protected: enum TransactId : uint32_t { - ON_SUBSCRIBE = FIRST_CALL_TRANSACTION, - ON_UNSUBSCRIBE, + ON_CONNECTED = FIRST_CALL_TRANSACTION, + ON_DISCONNECTED, ON_CONSUMED, ON_CONSUMED_MAP, ON_CANCELED, ON_CANCELED_MAP, ON_UPDATED, - ON_DISTURB_MODE_CHANGED, + ON_DND_DATE_CHANGED, }; }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_subscriber_proxy.h b/frameworks/ans/core/include/ans_subscriber_proxy.h index 1774567c236f3946efefca6d0b92785c3a9281e1..8739caf27fc5ee1086965993f72f7e99838f5c7d 100644 --- a/frameworks/ans/core/include/ans_subscriber_proxy.h +++ b/frameworks/ans/core/include/ans_subscriber_proxy.h @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - class AnsSubscriberProxy : public IRemoteProxy { public: AnsSubscriberProxy() = delete; @@ -29,8 +28,8 @@ public: ~AnsSubscriberProxy() override; DISALLOW_COPY_AND_MOVE(AnsSubscriberProxy); - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnConnected() override; + void OnDisconnected() override; void OnConsumed(const sptr ¬ification) override; void OnConsumed( const sptr ¬ification, const sptr ¬ificationMap) override; @@ -38,7 +37,7 @@ public: void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) override; void OnUpdated(const sptr ¬ificationMap) override; - void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + void OnDoNotDisturbDateChange(const sptr &date) override; private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/ans/core/include/ans_subscriber_stub.h b/frameworks/ans/core/include/ans_subscriber_stub.h index 4d60ccfc00c3c37bd30c4b992bb05eff68ce3035..26928cd84e11ac350ddbc43caaa60a5bce17ee15 100644 --- a/frameworks/ans/core/include/ans_subscriber_stub.h +++ b/frameworks/ans/core/include/ans_subscriber_stub.h @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - class AnsSubscriberStub : public IRemoteStub { public: AnsSubscriberStub(); @@ -31,8 +30,8 @@ public: virtual int OnRemoteRequest( uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override; - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnConnected() override; + void OnDisconnected() override; void OnConsumed(const sptr ¬ification) override; void OnConsumed( const sptr ¬ification, const sptr ¬ificationMap) override; @@ -40,19 +39,19 @@ public: void OnCanceled(const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) override; void OnUpdated(const sptr ¬ificationMap) override; - void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + void OnDoNotDisturbDateChange(const sptr &date) override; private: std::map> interfaces_; - ErrCode HandleOnSubscribe(MessageParcel &data, MessageParcel &reply); - ErrCode HandleOnUnsubscribe(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnConnected(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnDisconnected(MessageParcel &data, MessageParcel &reply); ErrCode HandleOnConsumed(MessageParcel &data, MessageParcel &reply); ErrCode HandleOnConsumedMap(MessageParcel &data, MessageParcel &reply); ErrCode HandleOnCanceled(MessageParcel &data, MessageParcel &reply); ErrCode HandleOnCanceledMap(MessageParcel &data, MessageParcel &reply); ErrCode HandleOnUpdated(MessageParcel &data, MessageParcel &reply); - ErrCode HandleOnDisturbModeChanged(MessageParcel &data, MessageParcel &reply); + ErrCode HandleOnDoNotDisturbDateChange(MessageParcel &data, MessageParcel &reply); }; } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_image_util.cpp b/frameworks/ans/core/src/ans_image_util.cpp new file mode 100644 index 0000000000000000000000000000000000000000..46b212b531778d015dba9af0e0ad35cbdda343d8 --- /dev/null +++ b/frameworks/ans/core/src/ans_image_util.cpp @@ -0,0 +1,215 @@ +/* + * 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 "ans_image_util.h" +#include "ans_log_wrapper.h" +#include "image_packer.h" +#include "image_source.h" + +namespace OHOS { +namespace Notification { +const std::string AnsImageUtil::IMAGE_FORMAT_JPEG {"image/jpeg"}; +const uint8_t AnsImageUtil::IMAGE_QUALITY {100}; +const uint8_t AnsImageUtil::SHIFT_FOUR {4}; +const uint8_t AnsImageUtil::NUM_TEN {10}; +const size_t AnsImageUtil::TWO_TIMES {2}; + +std::string AnsImageUtil::PackImage(const std::shared_ptr &pixelMap, const std::string &format) +{ + if (!pixelMap || format.empty()) { + ANS_LOGW("invalid parameters"); + return {}; + } + + Media::ImagePacker imagePacker; + Media::PackOption option; + option.format = format; + option.quality = IMAGE_QUALITY; + option.numberHint = 1; + + std::set formats; + auto ret = imagePacker.GetSupportedFormats(formats); + if (ret) { + ANS_LOGE("image packer get supported format failed, ret : %{public}u", ret); + return {}; + } + + auto size = static_cast(pixelMap->GetByteCount()); + ANS_LOGI("size of pixelMap : %{public}u", size); + auto pbuf = new (std::nothrow) uint8_t [size]; + if (pbuf == nullptr) { + ANS_LOGE("create buffer failed"); + return {}; + } + + imagePacker.StartPacking(pbuf, size, option); + imagePacker.AddImage(*pixelMap); + int64_t packedSize {0}; + imagePacker.FinalizePacking(packedSize); + ANS_LOGI("packed size : %{public}" PRId64, packedSize); + + std::string pixelMapStr(reinterpret_cast(pbuf), static_cast(packedSize)); + delete [] pbuf; + pbuf = nullptr; + + return BinToHex(pixelMapStr); +} + +std::shared_ptr AnsImageUtil::UnPackImage(const std::string &pixelMapStr) +{ + if (pixelMapStr.empty()) { + return {}; + } + + auto binStr = HexToBin(pixelMapStr); + + uint32_t errorCode {0}; + Media::SourceOptions opts; + auto imageSource = Media::ImageSource::CreateImageSource( + reinterpret_cast(binStr.data()), + static_cast(binStr.length()), + opts, errorCode); + if (errorCode || !imageSource) { + ANS_LOGE("create imageSource failed"); + return {}; + } + + Media::DecodeOptions decodeOpts; + auto pixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode); + if (errorCode || !pixelMap) { + ANS_LOGE("create pixelMap failed"); + return {}; + } + + return pixelMap; +} + +bool AnsImageUtil::PackImage2File( + const std::shared_ptr &pixelMap, + const std::string &outFilePath, + const std::string &format) +{ + if (!pixelMap || outFilePath.empty() || format.empty()) { + ANS_LOGW("invalid parameters"); + return false; + } + + Media::ImagePacker imagePacker; + Media::PackOption option; + option.format = format; + option.quality = IMAGE_QUALITY; + option.numberHint = 1; + + std::set formats; + auto ret = imagePacker.GetSupportedFormats(formats); + if (ret) { + ANS_LOGE("image packer get supported format failed, ret : %{public}u", ret); + return false; + } + + imagePacker.StartPacking(outFilePath, option); + imagePacker.AddImage(*pixelMap); + int64_t packedSize {0}; + imagePacker.FinalizePacking(packedSize); + ANS_LOGI("packed size : %{public}" PRId64, packedSize); + return true; +} + +std::shared_ptr AnsImageUtil::CreatePixelMap(const std::string &inFilePath, const std::string &format) +{ + if (inFilePath.empty() || format.empty()) { + ANS_LOGW("invalid parameters"); + return {}; + } + + uint32_t errorCode {0}; + Media::SourceOptions opts; + opts.formatHint = format; + auto imageSource = Media::ImageSource::CreateImageSource(inFilePath, opts, errorCode); + if (errorCode || !imageSource) { + ANS_LOGE("create imageSource failed"); + return {}; + } + + std::set formats; + auto ret = imageSource->GetSupportedFormats(formats); + if (ret) { + ANS_LOGE("image packer get supported format failed, ret : %{public}u", ret); + return {}; + } + + Media::DecodeOptions decodeOpts; + auto pixelMap = imageSource->CreatePixelMap(decodeOpts, errorCode); + if (errorCode || !pixelMap) { + ANS_LOGE("create pixelMap failed"); + return {}; + } + + return pixelMap; +} + +std::string AnsImageUtil::BinToHex(const std::string &strBin) +{ + if (strBin.empty()) { + return {}; + } + + std::string strHex; + strHex.resize(strBin.size() * TWO_TIMES); + for (size_t i = 0; i < strBin.size(); i++) { + uint8_t cTemp = strBin[i]; + for (size_t j = 0; j < TWO_TIMES; j++) { + uint8_t cCur = (cTemp & 0x0f); + if (cCur < NUM_TEN) { + cCur += '0'; + } else { + cCur += ('a' - NUM_TEN); + } + strHex[TWO_TIMES * i + 1 - j] = cCur; + cTemp >>= SHIFT_FOUR; + } + } + + return strHex; +} + +std::string AnsImageUtil::HexToBin(const std::string &strHex) +{ + if (strHex.size() % TWO_TIMES != 0) { + return {}; + } + + std::string strBin; + strBin.resize(strHex.size() / TWO_TIMES); + for (size_t i = 0; i < strBin.size(); i++) { + uint8_t cTemp = 0; + for (size_t j = 0; j < TWO_TIMES; j++) { + char cCur = strHex[TWO_TIMES * i + j]; + if (cCur >= '0' && cCur <= '9') { + cTemp = (cTemp << SHIFT_FOUR) + (cCur - '0'); + } else if (cCur >= 'a' && cCur <= 'f') { + cTemp = (cTemp << SHIFT_FOUR) + (cCur - 'a' + NUM_TEN); + } else if (cCur >= 'A' && cCur <= 'F') { + cTemp = (cTemp << SHIFT_FOUR) + (cCur - 'A' + NUM_TEN); + } else { + return {}; + } + } + strBin[i] = cTemp; + } + + return strBin; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index ae493cd9da4650a7e9b8d16dc5557db6d359d2ce..ce1d52cebc82ce0e0c3c0decacac5488fecb0529 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -20,10 +20,12 @@ #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" namespace OHOS { namespace Notification { - AnsManagerProxy::AnsManagerProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -354,10 +356,12 @@ ErrCode AnsManagerProxy::GetSlotByType(const NotificationConstant::SlotType &slo return ERR_ANS_PARCELABLE_FAILED; } - slot = reply.ReadParcelable(); - if (slot == nullptr) { - ANS_LOGW("[GetSlotByType] fail: read slot failed"); - return ERR_ANS_PARCELABLE_FAILED; + if (result == ERR_OK) { + slot = reply.ReadParcelable(); + if (slot == nullptr) { + ANS_LOGW("[GetSlotByType] fail: read slot failed"); + return ERR_ANS_PARCELABLE_FAILED; + } } return result; @@ -418,10 +422,12 @@ ErrCode AnsManagerProxy::GetSlotGroup(const std::string &groupId, sptr(); - if (group == nullptr) { - ANS_LOGW("[GetSlotGroup] fail: read group failed"); - return ERR_ANS_PARCELABLE_FAILED; + if (result == ERR_OK) { + group = reply.ReadParcelable(); + if (group == nullptr) { + ANS_LOGW("[GetSlotGroup] fail: read group failed"); + return ERR_ANS_PARCELABLE_FAILED; + } } return result; @@ -841,67 +847,6 @@ ErrCode AnsManagerProxy::GetBundleImportance(int &importance) return result; } -ErrCode AnsManagerProxy::SetDisturbMode(NotificationConstant::DisturbMode mode) -{ - if ((mode < NotificationConstant::DisturbMode::ALLOW_ALARMS) || - (mode > NotificationConstant::DisturbMode::ALLOW_UNKNOWN)) { - ANS_LOGW("[SetDisturbMode] fail: input mode is not in DisturbMode."); - return ERR_ANS_PARCELABLE_FAILED; - } - - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANS_LOGW("[SetDisturbMode] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - if (!data.WriteInt32(mode)) { - ANS_LOGW("[SetDisturbMode] fail: write mode failed"); - return ERR_ANS_PARCELABLE_FAILED; - } - - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(SET_DISTURB_MODE, option, data, reply); - if (result != ERR_OK) { - ANS_LOGW("[SetDisturbMode] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - - if (!reply.ReadInt32(result)) { - ANS_LOGW("[SetDisturbMode] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - return result; -} - -ErrCode AnsManagerProxy::GetDisturbMode(NotificationConstant::DisturbMode &mode) -{ - MessageParcel data; - if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - ANS_LOGW("[GetDisturbMode] fail: write interface token failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - MessageParcel reply; - MessageOption option = {MessageOption::TF_SYNC}; - ErrCode result = InnerTransact(GET_DISTURB_MODE, option, data, reply); - if (result != ERR_OK) { - ANS_LOGW("[GetDisturbMode] fail: transact ErrCode=%{public}d", result); - return ERR_ANS_TRANSACT_FAILED; - } - - if (!reply.ReadInt32(result)) { - ANS_LOGW("[GetDisturbMode] fail: read result failed."); - return ERR_ANS_PARCELABLE_FAILED; - } - - mode = static_cast(reply.ReadInt32()); - - return result; -} - ErrCode AnsManagerProxy::HasNotificationPolicyAccessPermission(bool &granted) { MessageParcel data; @@ -1499,7 +1444,6 @@ ErrCode AnsManagerProxy::GetShowBadgeEnabled(bool &enabled) MessageParcel reply; MessageOption option = {MessageOption::TF_SYNC}; ErrCode result = InnerTransact(GET_SHOW_BADGE_ENABLED, option, data, reply); - if (result != ERR_OK) { ANS_LOGW("[GetShowBadgeEnabled] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; @@ -1740,6 +1684,364 @@ ErrCode AnsManagerProxy::IsSpecialBundleAllowedNotify(const sptr &bundleOption, const std::string &groupName) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[RemoveGroupByBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[RemoveGroupByBundle] fail:: write bundleOption failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(groupName)) { + ANS_LOGW("[RemoveGroupByBundle] fail: write groupName failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(REMOVE_GROUP_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[RemoveGroupByBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[RemoveGroupByBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::SetDoNotDisturbDate(const sptr &date) +{ + if (date == nullptr) { + ANS_LOGW("[SetDoNotDisturbDate] fail: date is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[SetDoNotDisturbDate] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(date)) { + ANS_LOGW("[SetDoNotDisturbDate] fail: write date failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(SET_DO_NOT_DISTURB_DATE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[SetDoNotDisturbDate] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[SetDoNotDisturbDate] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetDoNotDisturbDate(sptr &date) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetDoNotDisturbDate] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_DO_NOT_DISTURB_DATE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetDoNotDisturbDate] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetDoNotDisturbDate] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + date = reply.ReadParcelable(); + if (date == nullptr) { + ANS_LOGW("[GetDoNotDisturbDate] fail: read date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + return result; +} + +ErrCode AnsManagerProxy::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[DoesSupportDoNotDisturbMode] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(DOES_SUPPORT_DO_NOT_DISTURB_MODE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[DoesSupportDoNotDisturbMode] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[DoesSupportDoNotDisturbMode] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(doesSupport)) { + ANS_LOGW("[DoesSupportDoNotDisturbMode] fail: read doesSupport failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsDistributedEnabled(bool &enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsDistributedEnabled] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_DISTRIBUTED_ENABLED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsDistributedEnabled] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsDistributedEnabled] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGW("[IsDistributedEnabled] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::EnableDistributed(bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[EnableDistributed] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[EnableDistributed] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ENABLE_DISTRIBUTED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[EnableDistributed] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[EnableDistributed] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::EnableDistributedByBundle(const sptr &bundleOption, bool enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGW("[EnableDistributedByBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[EnableDistributedByBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[EnableDistributedByBundle] fail:: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[EnableDistributedByBundle] fail:: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ENABLE_DISTRIBUTED_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[EnableDistributedByBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[EnableDistributedByBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::EnableDistributedSelf(bool enabled) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[EnableDistributedSelf] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteBool(enabled)) { + ANS_LOGW("[EnableDistributedSelf] fail: write enabled failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(ENABLE_DISTRIBUTED_SELF, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[EnableDistributedSelf] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[EnableDistributedSelf] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) +{ + if (bundleOption == nullptr) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: bundle is empty."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(bundleOption)) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: write bundle failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_DISTRIBUTED_ENABLED_BY_BUNDLE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(enabled)) { + ANS_LOGW("[IsDistributedEnableByBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[GetDeviceRemindType] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(GET_DEVICE_REMIND_TYPE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[GetDeviceRemindType] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[GetDeviceRemindType] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + int32_t rType {-1}; + if (!reply.ReadInt32(rType)) { + ANS_LOGW("[GetDeviceRemindType] fail: read remind type failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + remindType = static_cast(rType); + } + + return result; +} + ErrCode AnsManagerProxy::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { MessageParcel data; @@ -1774,6 +2076,218 @@ ErrCode AnsManagerProxy::ShellDump(const std::string &dumpOption, std::vector &request) +{ + if (request == nullptr) { + ANS_LOGW("[PublishContinuousTaskNotification] fail: notification request is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[PublishContinuousTaskNotification] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteParcelable(request)) { + ANS_LOGW("[PublishContinuousTaskNotification] fail: write request failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(PUBLISH_CONTINUOUS_TASK_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[PublishContinuousTaskNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[PublishContinuousTaskNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +ErrCode AnsManagerProxy::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[CancelContinuousTaskNotification] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(label)) { + ANS_LOGW("[CancelContinuousTaskNotification] fail: write label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteInt32(notificationId)) { + ANS_LOGW("[CancelContinuousTaskNotification] fail: write notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(CANCEL_CONTINUOUS_TASK_NOTIFICATION, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[CancelContinuousTaskNotification] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[CancelContinuousTaskNotification] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} + +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(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: derek read reminder id failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + reminder->SetReminderId(reminderId); + ANSR_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); + 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(CANCEL_REMINDER, option, data, reply); + if (result != ERR_OK) { + ANSR_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_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(CANCEL_ALL_REMINDERS, option, data, reply); + if (result != ERR_OK) { + ANSR_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_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(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}u", count); + reminders.clear(); + result = ReadReminders(count, reply, reminders); + if (result != ERR_OK) { + ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); + } else { + ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); + } + return result; +} + +ErrCode AnsManagerProxy::ReadReminders( + uint8_t &count, MessageParcel &reply, std::vector> &reminders) +{ + for (int 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}d", 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::InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) { auto remote = Remote(); @@ -1841,5 +2355,38 @@ bool AnsManagerProxy::ReadParcelableVector(std::vector> &parcelableInfos return true; } +ErrCode AnsManagerProxy::IsSupportTemplate(const std::string &templateName, bool &support) +{ + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + ANS_LOGW("[IsSupportTemplate] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!data.WriteString(templateName)) { + ANS_LOGW("[IsSupportTemplate] fail: write template name failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + MessageParcel reply; + MessageOption option = {MessageOption::TF_SYNC}; + ErrCode result = InnerTransact(IS_SUPPORT_TEMPLATE, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[IsSupportTemplate] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + + if (!reply.ReadInt32(result)) { + ANS_LOGW("[IsSupportTemplate] fail: read result failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.ReadBool(support)) { + ANS_LOGW("[IsSupportTemplate] fail: read support failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return result; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 55102470072ff600b6f2046ebacfe5222bb91235..979f0b2edf15d253cdaa1d1c23ced0255a5bddb6 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -20,10 +20,12 @@ #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" namespace OHOS { namespace Notification { - const std::map> AnsManagerStub::interfaces_ = { {AnsManagerStub::PUBLISH_NOTIFICATION, @@ -101,12 +103,6 @@ const std::map(data.ReadInt32()); - ErrCode result = AddSlotByType(slotType); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleAddSlotByType] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -332,7 +380,6 @@ ErrCode AnsManagerStub::HandleRemoveSlotByType(MessageParcel &data, MessageParce NotificationConstant::SlotType slotType = static_cast(data.ReadInt32()); ErrCode result = RemoveSlotByType(slotType); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleRemoveSlotByType] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -343,7 +390,6 @@ ErrCode AnsManagerStub::HandleRemoveSlotByType(MessageParcel &data, MessageParce ErrCode AnsManagerStub::HandleRemoveAllSlots(MessageParcel &data, MessageParcel &reply) { ErrCode result = RemoveAllSlots(); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleRemoveAllSlots] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -360,7 +406,6 @@ ErrCode AnsManagerStub::HandleAddSlotGroups(MessageParcel &data, MessageParcel & } ErrCode result = AddSlotGroups(groups); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleAddSlotGroups] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -372,7 +417,6 @@ ErrCode AnsManagerStub::HandleGetSlots(MessageParcel &data, MessageParcel &reply { std::vector> slots; ErrCode result = GetSlots(slots); - if (!WriteParcelableVector(slots, reply, result)) { ANS_LOGW("[HandleGetSlots] fail: write slots failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -387,7 +431,6 @@ ErrCode AnsManagerStub::HandleGetSlotByType(MessageParcel &data, MessageParcel & sptr slot; ErrCode result = GetSlotByType(slotType, slot); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetSlotByType] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -410,7 +453,6 @@ ErrCode AnsManagerStub::HandleGetSlotGroup(MessageParcel &data, MessageParcel &r sptr group; ErrCode result = GetSlotGroup(groupId, group); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetSlotGroup] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -427,7 +469,6 @@ ErrCode AnsManagerStub::HandleGetSlotGroups(MessageParcel &data, MessageParcel & { std::vector> groups; ErrCode result = GetSlotGroups(groups); - if (!WriteParcelableVector(groups, reply, result)) { ANS_LOGW("[HandleGetSlotGroups] fail: write groups failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -467,7 +508,6 @@ ErrCode AnsManagerStub::HandleRemoveSlotGroups(MessageParcel &data, MessageParce } ErrCode result = RemoveSlotGroups(groupIds); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleRemoveSlotGroups] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -479,7 +519,6 @@ ErrCode AnsManagerStub::HandleGetActiveNotifications(MessageParcel &data, Messag { std::vector> notifications; ErrCode result = GetActiveNotifications(notifications); - if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGW("[HandleGetActiveNotifications] fail: write notifications failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -491,7 +530,6 @@ ErrCode AnsManagerStub::HandleGetActiveNotificationNums(MessageParcel &data, Mes { int num = 0; ErrCode result = GetActiveNotificationNums(num); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetActiveNotificationNums] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -508,7 +546,6 @@ ErrCode AnsManagerStub::HandleGetAllActiveNotifications(MessageParcel &data, Mes { std::vector> notifications; ErrCode result = GetAllActiveNotifications(notifications); - if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGW("[HandleGetAllActiveNotifications] fail: write notifications failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -526,7 +563,6 @@ ErrCode AnsManagerStub::HandleGetSpecialActiveNotifications(MessageParcel &data, std::vector> notifications; ErrCode result = GetSpecialActiveNotifications(key, notifications); - if (!WriteParcelableVector(notifications, reply, result)) { ANS_LOGW("[HandleGetSpecialActiveNotifications] fail: write notifications failed"); return ERR_ANS_PARCELABLE_FAILED; @@ -554,7 +590,6 @@ ErrCode AnsManagerStub::HandleGetNotificationAgent(MessageParcel &data, MessageP { std::string agent; ErrCode result = GetNotificationAgent(agent); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetNotificationAgent] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -578,7 +613,6 @@ ErrCode AnsManagerStub::HandleCanPublishAsBundle(MessageParcel &data, MessagePar bool canPublish = false; ErrCode result = CanPublishAsBundle(representativeBundle, canPublish); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleCanPublishAsBundle] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -634,7 +668,6 @@ ErrCode AnsManagerStub::HandleGetBundleImportance(MessageParcel &data, MessagePa { int importance = 0; ErrCode result = GetBundleImportance(importance); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetBundleImportance] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -647,29 +680,94 @@ ErrCode AnsManagerStub::HandleGetBundleImportance(MessageParcel &data, MessagePa return ERR_OK; } -ErrCode AnsManagerStub::HandleSetDisturbMode(MessageParcel &data, MessageParcel &reply) +ErrCode AnsManagerStub::HandleSetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::DisturbMode mode = static_cast(data.ReadInt32()); - ErrCode result = SetDisturbMode(mode); + sptr date = data.ReadParcelable(); + if (date == nullptr) { + ANS_LOGW("[HandleSetDoNotDisturbDate] fail: read date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = SetDoNotDisturbDate(date); if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleSetDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + ANS_LOGW("[HandleSetDoNotDisturbDate] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } + return ERR_OK; } -ErrCode AnsManagerStub::HandleGetDisturbMode(MessageParcel &data, MessageParcel &reply) +ErrCode AnsManagerStub::HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::DisturbMode mode; - ErrCode result = GetDisturbMode(mode); + sptr date = nullptr; + ErrCode result = GetDoNotDisturbDate(date); if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleGetDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + ANS_LOGW("[HandleSetDoNotDisturbDate] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (result == ERR_OK) { + if (!reply.WriteParcelable(date)) { + ANS_LOGW("[HandleSetDoNotDisturbDate] fail: write date failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply) +{ + bool support = false; + + ErrCode result = DoesSupportDoNotDisturbMode(support); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleDoesSupportDoNotDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(support)) { + ANS_LOGW("[HandleDoesSupportDoNotDisturbMode] fail: write doesSupport failed."); return ERR_ANS_PARCELABLE_FAILED; } - if (!reply.WriteInt32(mode)) { - ANS_LOGW("[HandleGetDisturbMode] fail: write mode failed."); + return ERR_OK; +} + +ErrCode AnsManagerStub::HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply) +{ + sptr request = data.ReadParcelable(); + if (!request) { + ANS_LOGW("[HandlePublishContinuousTaskNotification] fail: notification ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = PublishContinuousTaskNotification(request); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandlePublishContinuousTaskNotification] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleCancelContinuousTaskNotification(MessageParcel &data, MessageParcel &reply) +{ + std::string label; + if (!data.ReadString(label)) { + ANS_LOGW("[HandleCancelContinuousTaskNotification] fail: read label failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + int notificationId = 0; + if (!data.ReadInt32(notificationId)) { + ANS_LOGW("[HandleCancelContinuousTaskNotification] fail: read notificationId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = CancelContinuousTaskNotification(label, notificationId); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleCancelContinuousTaskNotification] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } return ERR_OK; @@ -679,7 +777,6 @@ ErrCode AnsManagerStub::HandleIsNotificationPolicyAccessGranted(MessageParcel &d { bool granted = false; ErrCode result = HasNotificationPolicyAccessPermission(granted); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleIsNotificationPolicyAccessGranted] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -971,7 +1068,6 @@ ErrCode AnsManagerStub::HandleGetShowBadgeEnabledForBundle(MessageParcel &data, bool enabled = false; ErrCode result = GetShowBadgeEnabledForBundle(bundleOption, enabled); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetShowBadgeEnabledForBundle] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -988,7 +1084,6 @@ ErrCode AnsManagerStub::HandleGetShowBadgeEnabled(MessageParcel &data, MessagePa { bool enabled = false; ErrCode result = GetShowBadgeEnabled(enabled); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetShowBadgeEnabled] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1067,7 +1162,6 @@ ErrCode AnsManagerStub::HandleAreNotificationsSuspended(MessageParcel &data, Mes { bool suspended = false; ErrCode result = AreNotificationsSuspended(suspended); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleAreNotificationsSuspended] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1084,7 +1178,6 @@ ErrCode AnsManagerStub::HandleGetCurrentAppSorting(MessageParcel &data, MessageP { sptr sortingMap; ErrCode result = GetCurrentAppSorting(sortingMap); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetCurrentAppSorting] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1101,7 +1194,6 @@ ErrCode AnsManagerStub::HandleIsAllowedNotify(MessageParcel &data, MessageParcel { bool allowed = false; ErrCode result = IsAllowedNotify(allowed); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleIsAllowedNotify] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1124,7 +1216,6 @@ ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, bool allowed = false; ErrCode result = IsSpecialBundleAllowedNotify(bundleOption, allowed); - if (!reply.WriteInt32(result)) { ANS_LOGW("[IsSpecialBundleAllowedNotify] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1137,6 +1228,158 @@ ErrCode AnsManagerStub::HandleIsSpecialBundleAllowedNotify(MessageParcel &data, return ERR_OK; } +ErrCode AnsManagerStub::HandleCancelGroup(MessageParcel &data, MessageParcel &reply) +{ + std::string groupName; + if (!data.ReadString(groupName)) { + ANS_LOGW("[HandleCancelGroup] fail: read groupName failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = CancelGroup(groupName); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleCancelGroup] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleRemoveGroupByBundle(MessageParcel &data, MessageParcel &reply) +{ + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleRemoveGroupByBundle] fail: read bundleOption failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + std::string groupName; + if (!data.ReadString(groupName)) { + ANS_LOGW("[HandleRemoveGroupByBundle] fail: read groupName failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = RemoveGroupByBundle(bundleOption, groupName); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleRemoveGroupByBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleIsDistributedEnabled(MessageParcel &data, MessageParcel &reply) +{ + bool enabled = false; + ErrCode result = IsDistributedEnabled(enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleIsDistributedEnabled] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(enabled)) { + ANS_LOGW("[HandleIsDistributedEnabled] fail: write enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleEnableDistributed(MessageParcel &data, MessageParcel &reply) +{ + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleEnableDistributed] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = EnableDistributed(enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleEnableDistributed] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleEnableDistributedByBundle(MessageParcel &data, MessageParcel &reply) +{ + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleEnableDistributedByBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleEnableDistributedByBundle] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = EnableDistributedByBundle(bundleOption, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleEnableDistributedByBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleEnableDistributedSelf(MessageParcel &data, MessageParcel &reply) +{ + bool enabled = false; + if (!data.ReadBool(enabled)) { + ANS_LOGW("[HandleEnableDistributedSelf] fail: read enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = EnableDistributedSelf(enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleEnableDistributedSelf] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleIsDistributedEnableByBundle(MessageParcel &data, MessageParcel &reply) +{ + sptr bundleOption = data.ReadParcelable(); + if (bundleOption == nullptr) { + ANS_LOGW("[HandleIsDistributedEnableByBundle] fail: read bundle failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool enabled = false; + ErrCode result = IsDistributedEnableByBundle(bundleOption, enabled); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleIsDistributedEnableByBundle] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(enabled)) { + ANS_LOGW("[HandleIsDistributedEnableByBundle] fail: write enabled failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + +ErrCode AnsManagerStub::HandleGetDeviceRemindType(MessageParcel &data, MessageParcel &reply) +{ + auto rType {NotificationConstant::RemindType::NONE}; + ErrCode result = GetDeviceRemindType(rType); + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleGetDeviceRemindType] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteInt32(static_cast(rType))) { + ANS_LOGW("[HandleGetDeviceRemindType] fail: write remind type failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + return ERR_OK; +} + ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &reply) { std::string dumpOption; @@ -1147,7 +1390,6 @@ ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &repl std::vector notificationsInfo; ErrCode result = ShellDump(dumpOption, notificationsInfo); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleGetRecentNotificationsInfo] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1160,6 +1402,89 @@ 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; + } + 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; + } + + ANSR_LOGD("ReminderId=%{public}d", reminderId); + return CancelReminder(reminderId); +} + +ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply) +{ + return CancelAllReminders(); +} + +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; + } + } + return result; +} + template bool AnsManagerStub::WriteParcelableVector( const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) @@ -1205,6 +1530,29 @@ bool AnsManagerStub::ReadParcelableVector(std::vector> &parcelableInfos, return true; } +ErrCode AnsManagerStub::HandleIsSupportTemplate(MessageParcel &data, MessageParcel &reply) +{ + std::string templateName; + if (!data.ReadString(templateName)) { + ANS_LOGW("[HandleIsSupportTemplate] fail: read template name failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + bool support = false; + ErrCode result = IsSupportTemplate(templateName, support); + + if (!reply.WriteInt32(result)) { + ANS_LOGW("[HandleIsSupportTemplate] fail: write result failed, ErrCode=%{public}d", result); + return ERR_ANS_PARCELABLE_FAILED; + } + + if (!reply.WriteBool(support)) { + ANS_LOGW("[HandleIsSupportTemplate] fail: write support failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + return ERR_OK; +} + ErrCode AnsManagerStub::Publish(const std::string &label, const sptr ¬ification) { ANS_LOGW("AnsManagerStub::Publish called!"); @@ -1357,18 +1705,6 @@ ErrCode AnsManagerStub::GetBundleImportance(int &importance) return ERR_INVALID_OPERATION; } -ErrCode AnsManagerStub::SetDisturbMode(NotificationConstant::DisturbMode mode) -{ - ANS_LOGW("AnsManagerStub::SetDisturbMode called!"); - return ERR_INVALID_OPERATION; -} - -ErrCode AnsManagerStub::GetDisturbMode(NotificationConstant::DisturbMode &mode) -{ - ANS_LOGW("AnsManagerStub::GetDisturbMode called!"); - return ERR_INVALID_OPERATION; -} - ErrCode AnsManagerStub::HasNotificationPolicyAccessPermission(bool &granted) { ANS_LOGW("AnsManagerStub::HasNotificationPolicyAccessPermission called!"); @@ -1512,11 +1848,119 @@ ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const sptr &bundleOption, const std::string &groupName) +{ + ANS_LOGW("AnsManagerStub::RemoveGroupByBundle called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::SetDoNotDisturbDate(const sptr &date) +{ + ANS_LOGW("AnsManagerStub::SetDoNotDisturbDate called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetDoNotDisturbDate(sptr &date) +{ + ANS_LOGW("AnsManagerStub::GetDoNotDisturbDate called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + ANS_LOGW("AnsManagerStub::DoesSupportDoNotDisturbMode called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::IsDistributedEnabled(bool &enabled) +{ + ANS_LOGW("AnsManagerStub::IsDistributedEnabled called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::EnableDistributed(bool enabled) +{ + ANS_LOGW("AnsManagerStub::EnableDistributed called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::EnableDistributedByBundle(const sptr &bundleOption, bool enabled) +{ + ANS_LOGW("AnsManagerStub::EnableDistributedByBundle called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::EnableDistributedSelf(bool enabled) +{ + ANS_LOGW("AnsManagerStub::EnableDistributedSelf called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) +{ + ANS_LOGW("AnsManagerStub::IsDistributedEnableByBundle called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +{ + ANS_LOGW("AnsManagerStub::GetDeviceRemindType called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { ANS_LOGW("AnsManagerStub::ShellDump called!"); return ERR_INVALID_OPERATION; } +ErrCode AnsManagerStub::PublishContinuousTaskNotification(const sptr &request) +{ + ANS_LOGW("AnsManagerStub::PublishContinuousTaskNotification called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + ANS_LOGW("AnsManagerStub::CancelContinuousTaskNotification called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::PublishReminder(sptr &reminder) +{ + ANS_LOGW("AnsManagerStub::PublishReminder called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::CancelReminder(const int32_t reminderId) +{ + ANS_LOGW("AnsManagerStub::CancelReminder called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::GetValidReminders(std::vector> &reminders) +{ + ANS_LOGW("AnsManagerStub::getValidReminders called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::CancelAllReminders() +{ + ANS_LOGW("AnsManagerStub::cancelAllReminders called!"); + return ERR_INVALID_OPERATION; +} + +ErrCode AnsManagerStub::IsSupportTemplate(const std::string &templateName, bool &support) +{ + ANS_LOGW("AnsManagerStub::IsSupportTemplate called!"); + return ERR_INVALID_OPERATION; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index da55aed922b6b05cde374cecffb495014c3ce17e..6c4873d6cccdb784b7cd4e1abfbd824f73152d2b 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -14,13 +14,13 @@ */ #include "ans_notification.h" -#include #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "iservice_registry.h" -#include "notification_request.h" -#include "notification_sorting.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" #include "system_ability_definition.h" namespace OHOS { @@ -160,12 +160,17 @@ ErrCode AnsNotification::GetNotificationSlotGroups(std::vector bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->GetSlotNumAsBundle(bo, num); } @@ -206,6 +211,9 @@ ErrCode AnsNotification::PublishNotification(const std::string &label, const Not ANS_LOGE("Failed to create NotificationRequest ptr"); return ERR_ANS_NO_MEMORY; } + if (IsNonDistributedNotificationType(reqPtr->GetNotificationType())) { + reqPtr->SetDistributed(false); + } return ansManagerProxy_->Publish(label, reqPtr); } @@ -216,6 +224,12 @@ ErrCode AnsNotification::PublishNotification(const NotificationRequest &request, return ERR_ANS_INVALID_PARAM; } + if (!deviceId.empty() && + (IsNonDistributedNotificationType(request.GetNotificationType()))) { + ANS_LOGE("Refuse to publish the conversational and picture notification to the remote device"); + return ERR_ANS_INVALID_PARAM; + } + if (!CanPublishMediaContent(request)) { ANS_LOGE("Refuse to publish the notification because the sequence numbers actions not match those assigned to " "added action buttons."); @@ -358,6 +372,9 @@ ErrCode AnsNotification::PublishNotificationAsBundle( ANS_LOGE("Failed to create NotificationRequest ptr"); return ERR_ANS_NO_MEMORY; } + if (IsNonDistributedNotificationType(reqPtr->GetNotificationType())) { + reqPtr->SetDistributed(false); + } return ansManagerProxy_->PublishAsBundle(reqPtr, representativeBundle); } @@ -514,34 +531,49 @@ ErrCode AnsNotification::RemoveNotification(const std::string &key) ErrCode AnsNotification::RemoveNotification( const NotificationBundleOption &bundleOption, const int32_t notificationId, const std::string &label) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->RemoveNotification(bo, notificationId, label); } ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption &bundleOption) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->RemoveAllNotifications(bo); } ErrCode AnsNotification::RemoveNotificationsByBundle(const NotificationBundleOption &bundleOption) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->DeleteByBundle(bo); } @@ -567,31 +599,41 @@ ErrCode AnsNotification::GetNotificationSlotsForBundle( return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->GetSlotsByBundle(bo, slots); } ErrCode AnsNotification::UpdateNotificationSlots( const NotificationBundleOption &bundleOption, const std::vector> &slots) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->UpdateSlots(bo, slots); } ErrCode AnsNotification::UpdateNotificationSlotGroups( const NotificationBundleOption &bundleOption, const std::vector> &groups) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->UpdateSlotGroups(bo, groups); } @@ -626,7 +668,7 @@ ErrCode AnsNotification::IsAllowedNotify(const NotificationBundleOption &bundleO return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->IsSpecialBundleAllowedNotify(bo, allowed); } @@ -651,34 +693,49 @@ ErrCode AnsNotification::SetNotificationsEnabledForDefaultBundle(const std::stri ErrCode AnsNotification::SetNotificationsEnabledForSpecifiedBundle( const NotificationBundleOption &bundleOption, const std::string &deviceId, bool enabled) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->SetNotificationsEnabledForSpecialBundle(deviceId, bo, enabled); } ErrCode AnsNotification::SetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool enabled) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->SetShowBadgeEnabledForBundle(bo, enabled); } ErrCode AnsNotification::GetShowBadgeEnabledForBundle(const NotificationBundleOption &bundleOption, bool &enabled) { + if (bundleOption.GetBundleName().empty()) { + ANS_LOGE("Invalid bundle name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->GetShowBadgeEnabledForBundle(bo, enabled); } @@ -692,22 +749,195 @@ ErrCode AnsNotification::GetShowBadgeEnabled(bool &enabled) return ansManagerProxy_->GetShowBadgeEnabled(enabled); } -ErrCode AnsNotification::SetDisturbMode(NotificationConstant::DisturbMode mode) +ErrCode AnsNotification::CancelGroup(const std::string &groupName) { + if (groupName.empty()) { + ANS_LOGE("Invalid group name."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->SetDisturbMode(mode); + + return ansManagerProxy_->CancelGroup(groupName); } -ErrCode AnsNotification::GetDisturbMode(NotificationConstant::DisturbMode &disturbMode) +ErrCode AnsNotification::RemoveGroupByBundle( + const NotificationBundleOption &bundleOption, const std::string &groupName) { + if (bundleOption.GetBundleName().empty() || groupName.empty()) { + ANS_LOGE("Invalid parameter."); + return ERR_ANS_INVALID_PARAM; + } + if (!GetAnsManagerProxy()) { ANS_LOGE("GetAnsManagerProxy fail."); return ERR_ANS_SERVICE_NOT_CONNECTED; } - return ansManagerProxy_->GetDisturbMode(disturbMode); + + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); + return ansManagerProxy_->RemoveGroupByBundle(bo, groupName); +} + +ErrCode AnsNotification::SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + auto dndDatePtr = new (std::nothrow) NotificationDoNotDisturbDate(doNotDisturbDate); + if (dndDatePtr == nullptr) { + ANS_LOGE("create DoNotDisturbDate failed."); + return ERR_ANS_NO_MEMORY; + } + + sptr dndDate(dndDatePtr); + return ansManagerProxy_->SetDoNotDisturbDate(dndDate); +} + +ErrCode AnsNotification::GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr dndDate; + auto ret = ansManagerProxy_->GetDoNotDisturbDate(dndDate); + if (ret != ERR_OK) { + ANS_LOGE("Get DoNotDisturbDate failed."); + return ret; + } + + if (!dndDate) { + ANS_LOGE("Invalid DoNotDisturbDate."); + return ERR_ANS_NO_MEMORY; + } + + doNotDisturbDate = *dndDate; + return ret; +} + +ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->DoesSupportDoNotDisturbMode(doesSupport); +} + +ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationRequest &request) +{ + if (request.GetContent() == nullptr || request.GetNotificationType() == NotificationContent::Type::NONE) { + ANS_LOGE("Refuse to publish the notification without valid content"); + return ERR_ANS_INVALID_PARAM; + } + + if (!CanPublishMediaContent(request)) { + ANS_LOGE("Refuse to publish the notification because the sequence numbers actions not match those assigned to " + "added action buttons."); + return ERR_ANS_INVALID_PARAM; + } + + ErrCode checkErr = CheckImageSize(request); + if (checkErr != ERR_OK) { + ANS_LOGE("The size of one picture exceeds the limit"); + return checkErr; + } + + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + auto pReq = new (std::nothrow) NotificationRequest(request); + if (pReq == nullptr) { + ANS_LOGE("Failed to create NotificationRequest ptr."); + return ERR_ANS_NO_MEMORY; + } + + sptr sptrReq(pReq); + if (IsNonDistributedNotificationType(sptrReq->GetNotificationType())) { + sptrReq->SetDistributed(false); + } + return ansManagerProxy_->PublishContinuousTaskNotification(sptrReq); +} + +ErrCode AnsNotification::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->CancelContinuousTaskNotification(label, notificationId); +} + +ErrCode AnsNotification::IsDistributedEnabled(bool &enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->IsDistributedEnabled(enabled); +} + +ErrCode AnsNotification::EnableDistributed(const bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->EnableDistributed(enabled); +} + +ErrCode AnsNotification::EnableDistributedByBundle(const NotificationBundleOption &bundleOption, const bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); + return ansManagerProxy_->EnableDistributedByBundle(bo, enabled); +} + +ErrCode AnsNotification::EnableDistributedSelf(const bool enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->EnableDistributedSelf(enabled); +} + +ErrCode AnsNotification::IsDistributedEnableByBundle(const NotificationBundleOption &bundleOption, bool &enabled) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); + return ansManagerProxy_->IsDistributedEnableByBundle(bo, enabled); +} + +ErrCode AnsNotification::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->GetDeviceRemindType(remindType); } void AnsNotification::ResetAnsManagerProxy() @@ -729,6 +959,69 @@ ErrCode AnsNotification::ShellDump(const std::string &dumpOption, std::vectorShellDump(dumpOption, dumpInfo); } +ErrCode AnsNotification::PublishReminder(ReminderRequest &reminder) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + sptr tarReminder; + 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; + } + } + ErrCode code = ansManagerProxy_->PublishReminder(tarReminder); + reminder.SetReminderId(tarReminder->GetReminderId()); + return code; +} + +ErrCode AnsNotification::CancelReminder(const int32_t reminderId) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->CancelReminder(reminderId); +} + +ErrCode AnsNotification::CancelAllReminders() +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->CancelAllReminders(); +} + +ErrCode AnsNotification::GetValidReminders(std::vector> &validReminders) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + return ansManagerProxy_->GetValidReminders(validReminders); +} + bool AnsNotification::GetAnsManagerProxy() { if (!ansManagerProxy_) { @@ -754,7 +1047,7 @@ bool AnsNotification::GetAnsManagerProxy() return false; } - recipient_ = new AnsManagerDeathRecipient(); + recipient_ = new (std::nothrow) AnsManagerDeathRecipient(); if (!recipient_) { ANS_LOGE("Failed to create death recipient"); return false; @@ -798,61 +1091,92 @@ bool AnsNotification::CanPublishMediaContent(const NotificationRequest &request) return true; } +bool AnsNotification::CheckImageOverSizeForPixelMap(const std::shared_ptr &pixelMap, uint32_t maxSize) +{ + if (!pixelMap) { + return false; + } + + uint32_t size = static_cast(pixelMap->GetByteCount()); + if (size > maxSize) { + return true; + } + return false; +} + +ErrCode AnsNotification::CheckImageSizeForContent(const NotificationRequest &request) +{ + auto content = request.GetContent(); + if (!content) { + ANS_LOGW("Invalid content in NotificationRequest"); + return ERR_OK; + } + + auto basicContent = request.GetContent()->GetNotificationContent(); + if (!basicContent) { + ANS_LOGW("Invalid content in NotificationRequest"); + return ERR_OK; + } + + auto contentType = request.GetNotificationType(); + switch (contentType) { + case NotificationContent::Type::CONVERSATION: { + auto conversationalContent = std::static_pointer_cast(basicContent); + + auto picture = conversationalContent->GetMessageUser().GetPixelMap(); + if (CheckImageOverSizeForPixelMap(picture, MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in ConversationalContent's message user exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + + auto messages = conversationalContent->GetAllConversationalMessages(); + for (auto &msg : messages) { + if (!msg) { + continue; + } + + auto img = msg->GetSender().GetPixelMap(); + if (CheckImageOverSizeForPixelMap(img, MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in ConversationalContent's message exceeds limit"); + return ERR_ANS_ICON_OVER_SIZE; + } + } + break; + } + case NotificationContent::Type::PICTURE: { + auto pictureContent = std::static_pointer_cast(basicContent); + + auto bigPicture = pictureContent->GetBigPicture(); + if (CheckImageOverSizeForPixelMap(bigPicture, MAX_PICTURE_SIZE)) { + ANS_LOGE("The size of big picture in PictureContent exceeds limit"); + return ERR_ANS_PICTURE_OVER_SIZE; + } + break; + } + default: + break; + } + + return ERR_OK; +} + ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) { auto littleIcon = request.GetLittleIcon(); - if (littleIcon && (static_cast(littleIcon->GetByteCount()) > MAX_ICON_SIZE)) { + if (CheckImageOverSizeForPixelMap(littleIcon, MAX_ICON_SIZE)) { ANS_LOGE("The size of little icon exceeds limit"); return ERR_ANS_ICON_OVER_SIZE; } auto bigIcon = request.GetBigIcon(); - if (bigIcon && (static_cast(bigIcon->GetByteCount()) > MAX_ICON_SIZE)) { + if (CheckImageOverSizeForPixelMap(bigIcon, MAX_ICON_SIZE)) { ANS_LOGE("The size of big icon exceeds limit"); return ERR_ANS_ICON_OVER_SIZE; } - auto content = request.GetContent(); - if (content) { - auto basicContent = request.GetContent()->GetNotificationContent(); - if (basicContent) { - auto contentType = request.GetNotificationType(); - switch (contentType) { - case NotificationContent::Type::CONVERSATION: { - auto conversationalContent = std::static_pointer_cast(basicContent); - - auto picture = conversationalContent->GetMessageUser().GetPixelMap(); - if (picture && (static_cast(picture->GetByteCount()) > MAX_ICON_SIZE)) { - ANS_LOGE("The size of picture in conversationalContent exceeds limit"); - return ERR_ANS_ICON_OVER_SIZE; - } - - auto messages = conversationalContent->GetAllConversationalMessages(); - for (auto &msg : messages) { - if (!msg) { - continue; - } - - auto img = msg->GetSender().GetPixelMap(); - if (img && (static_cast(img->GetByteCount()) > MAX_ICON_SIZE)) { - ANS_LOGE("The size of picture in conversationalMessage exceeds limit"); - return ERR_ANS_ICON_OVER_SIZE; - } - } - } break; - case NotificationContent::Type::PICTURE: { - auto pictureContent = std::static_pointer_cast(basicContent); - - auto bigPicture = pictureContent->GetBigPicture(); - if (bigPicture && (static_cast(bigPicture->GetByteCount()) > MAX_PICTURE_SIZE)) { - ANS_LOGE("The size of big picture exceeds limit"); - return ERR_ANS_PICTURE_OVER_SIZE; - } - } break; - default: - break; - } - } + ErrCode err = CheckImageSizeForContent(request); + if (err != ERR_OK) { + return err; } auto buttons = request.GetActionButtons(); @@ -860,10 +1184,9 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) if (!btn) { continue; } - auto icon = btn->GetIcon(); - if (icon && (static_cast(icon->GetByteCount()) > MAX_ICON_SIZE)) { - ANS_LOGE("The size of icon in actionButton exceeds limit"); + if (CheckImageOverSizeForPixelMap(icon, MAX_ICON_SIZE)) { + ANS_LOGE("The size of icon in ActionButton exceeds limit"); return ERR_ANS_ICON_OVER_SIZE; } } @@ -873,15 +1196,33 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) if (!user) { continue; } - auto icon = user->GetPixelMap(); - if (icon && (static_cast(icon->GetByteCount()) > MAX_ICON_SIZE)) { - ANS_LOGE("The size of picture in messageUser exceeds limit"); + if (CheckImageOverSizeForPixelMap(icon, MAX_ICON_SIZE)) { + ANS_LOGE("The size of picture in MessageUser exceeds limit"); return ERR_ANS_ICON_OVER_SIZE; } } return ERR_OK; } + +ErrCode AnsNotification::IsSupportTemplate(const std::string &templateName, bool &support) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->IsSupportTemplate(templateName, support); +} + +bool AnsNotification::IsNonDistributedNotificationType(const NotificationContent::Type &type) +{ + if ((type == NotificationContent::Type::CONVERSATION) || + (type == NotificationContent::Type::PICTURE)) { + return true; + } + return false; +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/core/src/ans_subscriber_proxy.cpp b/frameworks/ans/core/src/ans_subscriber_proxy.cpp index f42f9a8c310e7d13efd89ee8a418a2b587e24df0..1952b3f6b602b45aa23cdccb6f5e44814212c782 100644 --- a/frameworks/ans/core/src/ans_subscriber_proxy.cpp +++ b/frameworks/ans/core/src/ans_subscriber_proxy.cpp @@ -53,46 +53,36 @@ ErrCode AnsSubscriberProxy::InnerTransact( } } -void AnsSubscriberProxy::OnSubscribeResult(NotificationConstant::SubscribeResult result) +void AnsSubscriberProxy::OnConnected() { MessageParcel data; if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { - ANS_LOGW("[OnSubscribeResult] fail: write interface token failed."); - return; - } - - if (!data.WriteUint32(result)) { - ANS_LOGW("[OnSubscribeResult] fail: write result failed"); + ANS_LOGW("[OnConnected] fail: write interface token failed."); return; } MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; - ErrCode transactResult = InnerTransact(ON_SUBSCRIBE, option, data, reply); - if (transactResult != ERR_OK) { - ANS_LOGW("[OnSubscribeResult] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + ErrCode result = InnerTransact(ON_CONNECTED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnConnected] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); return; } } -void AnsSubscriberProxy::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +void AnsSubscriberProxy::OnDisconnected() { MessageParcel data; if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { - ANS_LOGW("[OnUnsubscribeResult] fail: write interface token failed."); - return; - } - - if (!data.WriteUint32(result)) { - ANS_LOGW("[OnUnsubscribeResult] fail: write result failed"); + ANS_LOGW("[OnDisconnected] fail: write interface token failed."); return; } MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; - ErrCode transactResult = InnerTransact(ON_UNSUBSCRIBE, option, data, reply); - if (transactResult != ERR_OK) { - ANS_LOGW("[OnUnsubscribeResult] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + ErrCode result = InnerTransact(ON_DISCONNECTED, option, data, reply); + if (result != ERR_OK) { + ANS_LOGW("[OnDisconnected] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); return; } } @@ -263,27 +253,26 @@ void AnsSubscriberProxy::OnUpdated(const sptr ¬ificat } } -void AnsSubscriberProxy::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +void AnsSubscriberProxy::OnDoNotDisturbDateChange(const sptr &date) { MessageParcel data; if (!data.WriteInterfaceToken(AnsSubscriberProxy::GetDescriptor())) { - ANS_LOGW("[OnDisturbModeChanged] fail: write interface token failed."); + ANS_LOGW("[OnDoNotDisturbDateChange] fail: write interface token failed."); return; } - if (!data.WriteUint32(mode)) { - ANS_LOGW("[OnDisturbModeChanged] fail: write mode failed"); + if (!data.WriteParcelable(date)) { + ANS_LOGW("[OnDoNotDisturbDateChange] fail: write date failed"); return; } MessageParcel reply; MessageOption option = {MessageOption::TF_ASYNC}; - ErrCode result = InnerTransact(ON_DISTURB_MODE_CHANGED, option, data, reply); + ErrCode result = InnerTransact(ON_DND_DATE_CHANGED, option, data, reply); if (result != ERR_OK) { - ANS_LOGW("[OnDisturbModeChanged] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); + ANS_LOGW("[OnDoNotDisturbDateChange] fail: transact ErrCode=ERR_ANS_TRANSACT_FAILED"); return; } } - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp index 8ecb5721982416f3ddfd6cf698aeb97b4528c003..932238a92000cf14a82eeab5bff1448ec901f131 100644 --- a/frameworks/ans/core/src/ans_subscriber_stub.cpp +++ b/frameworks/ans/core/src/ans_subscriber_stub.cpp @@ -13,8 +13,6 @@ * limitations under the License. */ -#include - #include "ans_subscriber_stub.h" #include "ans_const_define.h" @@ -28,10 +26,10 @@ namespace OHOS { namespace Notification { AnsSubscriberStub::AnsSubscriberStub() { - interfaces_.emplace(ON_SUBSCRIBE, - std::bind(&AnsSubscriberStub::HandleOnSubscribe, this, std::placeholders::_1, std::placeholders::_2)); - interfaces_.emplace(ON_UNSUBSCRIBE, - std::bind(&AnsSubscriberStub::HandleOnUnsubscribe, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_CONNECTED, + std::bind(&AnsSubscriberStub::HandleOnConnected, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_DISCONNECTED, + std::bind(&AnsSubscriberStub::HandleOnDisconnected, this, std::placeholders::_1, std::placeholders::_2)); interfaces_.emplace(ON_CONSUMED, std::bind(&AnsSubscriberStub::HandleOnConsumed, this, std::placeholders::_1, std::placeholders::_2)); interfaces_.emplace(ON_CONSUMED_MAP, @@ -42,8 +40,9 @@ AnsSubscriberStub::AnsSubscriberStub() std::bind(&AnsSubscriberStub::HandleOnCanceledMap, this, std::placeholders::_1, std::placeholders::_2)); interfaces_.emplace( ON_UPDATED, std::bind(&AnsSubscriberStub::HandleOnUpdated, this, std::placeholders::_1, std::placeholders::_2)); - interfaces_.emplace(ON_DISTURB_MODE_CHANGED, - std::bind(&AnsSubscriberStub::HandleOnDisturbModeChanged, this, std::placeholders::_1, std::placeholders::_2)); + interfaces_.emplace(ON_DND_DATE_CHANGED, + std::bind( + &AnsSubscriberStub::HandleOnDoNotDisturbDateChange, this, std::placeholders::_1, std::placeholders::_2)); } AnsSubscriberStub::~AnsSubscriberStub() @@ -75,19 +74,15 @@ int32_t AnsSubscriberStub::OnRemoteRequest( return NO_ERROR; } -ErrCode AnsSubscriberStub::HandleOnSubscribe(MessageParcel &data, MessageParcel &reply) +ErrCode AnsSubscriberStub::HandleOnConnected(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::SubscribeResult result = - static_cast(data.ReadUint32()); - OnSubscribeResult(result); + OnConnected(); return ERR_OK; } -ErrCode AnsSubscriberStub::HandleOnUnsubscribe(MessageParcel &data, MessageParcel &reply) +ErrCode AnsSubscriberStub::HandleOnDisconnected(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::SubscribeResult result = - static_cast(data.ReadUint32()); - OnUnsubscribeResult(result); + OnDisconnected(); return ERR_OK; } @@ -187,17 +182,17 @@ ErrCode AnsSubscriberStub::HandleOnUpdated(MessageParcel &data, MessageParcel &r return ERR_OK; } -ErrCode AnsSubscriberStub::HandleOnDisturbModeChanged(MessageParcel &data, MessageParcel &reply) +ErrCode AnsSubscriberStub::HandleOnDoNotDisturbDateChange(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::DisturbMode mode = static_cast(data.ReadUint32()); - OnDisturbModeChanged(mode); + sptr date = data.ReadParcelable(); + OnDoNotDisturbDateChange(date); return ERR_OK; } -void AnsSubscriberStub::OnSubscribeResult(NotificationConstant::SubscribeResult result) +void AnsSubscriberStub::OnConnected() {} -void AnsSubscriberStub::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +void AnsSubscriberStub::OnDisconnected() {} void AnsSubscriberStub::OnConsumed(const sptr ¬ification) @@ -217,8 +212,7 @@ void AnsSubscriberStub::OnCanceled( void AnsSubscriberStub::OnUpdated(const sptr ¬ificationMap) {} -void AnsSubscriberStub::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +void AnsSubscriberStub::OnDoNotDisturbDateChange(const sptr &date) {} - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn old mode 100755 new mode 100644 index 502edd929611e61d2e74908d0637659db4fd2ec8..a27b1b04e34563c676319453caa00e1a18ce8dd6 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -25,6 +25,9 @@ config("ans_innerkits_public_config") { "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", + "//third_party/json/single_include", + "//third_party/jsoncpp/include", + "//utils/system/safwk/native/include", ] configs = [ "${frameworks_path}/wantagent:wantagent_innerkits_public_config" ] } @@ -32,8 +35,6 @@ config("ans_innerkits_public_config") { ohos_shared_library("ans_innerkits") { include_dirs = [ "${interfaces_path}/ans/native/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", - "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//utils/system/safwk/native/include", "//third_party/jsoncpp/include", ] @@ -48,6 +49,9 @@ ohos_shared_library("ans_innerkits") { "src/notification_content.cpp", "src/notification_conversational_content.cpp", "src/notification_conversational_message.cpp", + "src/notification_distributed_options.cpp", + "src/notification_do_not_disturb_date.cpp", + "src/notification_flags.cpp", "src/notification_helper.cpp", "src/notification_long_text_content.cpp", "src/notification_media_content.cpp", @@ -61,6 +65,7 @@ ohos_shared_library("ans_innerkits") { "src/notification_sorting_map.cpp", "src/notification_subscribe_info.cpp", "src/notification_subscriber.cpp", + "src/notification_template.cpp", "src/notification_user_input.cpp", ] @@ -74,17 +79,17 @@ ohos_shared_library("ans_innerkits") { deps = [ "${frameworks_path}/ans/core:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:want", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "multimedia_image_standard:image_native", + "samgr_standard:samgr_proxy", ] if (is_double_framework) { diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index 4e1632abd2381b21bd69c6524046d82c86edd326..385eafd0f6eee5a71a2cc4740d29038c64047202 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -14,13 +14,12 @@ */ #include "message_user.h" +#include "ans_image_util.h" #include "ans_log_wrapper.h" namespace OHOS { namespace Notification { - -MessageUser::MessageUser() - : uri_("") +MessageUser::MessageUser() : uri_("") {} MessageUser::~MessageUser() @@ -88,12 +87,68 @@ bool MessageUser::IsUserImportant() const std::string MessageUser::Dump() const { - return "MessageUser[key = " + key_ + - ", name = " + name_ + - ", pixelMap = " + (pixelMap_ ? "not null" : "null") + - ", uri = " + uri_.ToString() + - ", isMachine = " + (isMachine_ ? "true" : "false") + - ", isUserImportant = " + (isUserImportant_ ? "true" : "false") + "]"; + return "MessageUser{ " + "key = " + key_ + + ", name = " + name_ + + ", pixelMap = " + (pixelMap_ ? "not null" : "null") + + ", uri = " + uri_.ToString() + + ", isMachine = " + (isMachine_ ? "true" : "false") + + ", isUserImportant = " + (isUserImportant_ ? "true" : "false") + + " }"; +} + +bool MessageUser::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["key"] = key_; + jsonObject["name"] = name_; + jsonObject["pixelMap"] = AnsImageUtil::PackImage(pixelMap_); + jsonObject["uri"] = uri_.ToString(); + jsonObject["isMachine"] = isMachine_; + jsonObject["isUserImportant"] = isUserImportant_; + + return true; +} + +MessageUser *MessageUser::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + MessageUser *messageUser = new (std::nothrow) MessageUser(); + if (messageUser == nullptr) { + ANS_LOGE("Failed to create messageUse instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("key") != jsonEnd) { + messageUser->key_ = jsonObject.at("key").get(); + } + + if (jsonObject.find("name") != jsonEnd) { + messageUser->name_ = jsonObject.at("name").get(); + } + + if (jsonObject.find("pixelMap") != jsonEnd) { + auto pmStr = jsonObject.at("pixelMap").get(); + messageUser->pixelMap_ = AnsImageUtil::UnPackImage(pmStr); + } + + if (jsonObject.find("uri") != jsonEnd) { + messageUser->uri_ = Uri(jsonObject.at("uri").get()); + } + + if (jsonObject.find("isMachine") != jsonEnd) { + messageUser->isMachine_ = jsonObject.at("isMachine").get(); + } + + if (jsonObject.find("isUserImportant") != jsonEnd) { + messageUser->isUserImportant_ = jsonObject.at("isUserImportant").get(); + } + + return messageUser; } bool MessageUser::Marshalling(Parcel &parcel) const @@ -181,7 +236,7 @@ bool MessageUser::ReadFromParcel(Parcel &parcel) MessageUser *MessageUser::Unmarshalling(Parcel &parcel) { - MessageUser *messageUser = new MessageUser(); + MessageUser *messageUser = new (std::nothrow) MessageUser(); if (messageUser && !messageUser->ReadFromParcel(parcel)) { delete messageUser; diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index c69e0864ccb221fb4cecb966032cc3da124ded72..b94a72e22479edbd6300e2a329b7842397b5526c 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -21,12 +21,19 @@ namespace OHOS { namespace Notification { -Notification::Notification(){}; +Notification::Notification() {}; Notification::Notification(const sptr &request) { request_ = request; - key_ = GenerateNotificationKey(GetUid(), GetLabel(), GetId()); + key_ = GenerateNotificationKey("", GetUid(), GetLabel(), GetId()); +} + +Notification::Notification(const std::string &deviceId, const sptr &request) +{ + deviceId_ = deviceId; + request_ = request; + key_ = GenerateNotificationKey(deviceId, GetUid(), GetLabel(), GetId()); } Notification::Notification(const Notification &other) @@ -37,10 +44,14 @@ Notification::Notification(const Notification &other) key_ = other.key_; ledLightColor_ = other.ledLightColor_; lockscreenVisibleness_ = other.lockscreenVisibleness_; + remindType_ = other.remindType_; request_ = other.request_; postTime_ = other.postTime_; sound_ = other.sound_; vibrationStyle_ = other.vibrationStyle_; + isRemoveAllowed_ = other.isRemoveAllowed_; + sourceType_ = other.sourceType_; + deviceId_ = other.deviceId_; } Notification::~Notification() @@ -100,7 +111,7 @@ std::string Notification::GetGroup() const if (request_ == nullptr) { return ""; } - return request_->GetGroupValue(); + return request_->GetGroupName(); } int32_t Notification::GetId() const @@ -150,6 +161,14 @@ pid_t Notification::GetPid() const return request_->GetCreatorPid(); } +bool Notification::IsUnremovable() const +{ + if (request_ == nullptr) { + return false; + } + return request_->IsUnremovable(); +} + std::vector Notification::GetVibrationStyle() const { return vibrationStyle_; @@ -160,7 +179,7 @@ bool Notification::IsGroup() const if (request_ == nullptr) { return false; } - return !(request_->GetGroupValue() == ""); + return !(request_->GetGroupName() == ""); } bool Notification::IsFloatingIcon() const @@ -171,7 +190,35 @@ bool Notification::IsFloatingIcon() const return request_->IsFloatingIcon(); } -bool Notification::Marshalling(Parcel &parcel) const +NotificationConstant::RemindType Notification::GetRemindType() const +{ + return remindType_; +} + +bool Notification::IsRemoveAllowed() const +{ + return isRemoveAllowed_; +} + +NotificationConstant::SourceType Notification::GetSourceType() const +{ + return sourceType_; +} + +std::string Notification::GetDeviceId() const +{ + return deviceId_; +} + +int32_t Notification::GetUserId() const +{ + if (request_ == nullptr) { + return 0; + } + return request_->GetCreatorUserId(); +} + +bool Notification::MarshallingBool(Parcel &parcel) const { if (!parcel.WriteBool(enableLight_)) { ANS_LOGE("Can't write enableLight_"); @@ -188,10 +235,38 @@ bool Notification::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteBool(isRemoveAllowed_)) { + ANS_LOGE("Can't write isRemoveAllowed"); + return false; + } + + return true; +} + +bool Notification::MarshallingString(Parcel &parcel) const +{ if (!parcel.WriteString(key_)) { ANS_LOGE("Can't wirte key"); return false; } + + if (enableSound_ && sound_ != nullptr) { + if (!parcel.WriteString(sound_->ToString())) { + ANS_LOGE("Can't write sound"); + return false; + } + } + + if (!parcel.WriteString(deviceId_)) { + ANS_LOGE("Can't wirte deviceId"); + return false; + } + + return true; +} + +bool Notification::MarshallingInt32(Parcel &parcel) const +{ if (!parcel.WriteInt32(ledLightColor_)) { ANS_LOGE("Can't write ledLigthColor"); return false; @@ -202,21 +277,24 @@ bool Notification::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteStrongParcelable(request_)) { - ANS_LOGE("Can't write request"); + if (!parcel.WriteInt32(static_cast(remindType_))) { + ANS_LOGE("Can't write remindType"); return false; } - if (!parcel.WriteInt64(postTime_)) { - ANS_LOGE("Can't write postTime"); + if (!parcel.WriteInt32(static_cast(sourceType_))) { + ANS_LOGE("Can't write sourceType"); return false; } - if (enableSound_ && sound_ != nullptr) { - if (!parcel.WriteString(sound_->ToString())) { - ANS_LOGE("Can't write sound"); - return false; - } + return true; +} + +bool Notification::MarshallingInt64(Parcel &parcel) const +{ + if (!parcel.WriteInt64(postTime_)) { + ANS_LOGE("Can't write postTime"); + return false; } if (!parcel.WriteInt64Vector(vibrationStyle_)) { @@ -227,7 +305,38 @@ bool Notification::Marshalling(Parcel &parcel) const return true; } -bool Notification::ReadFromParcel(Parcel &parcel) +bool Notification::MarshallingParcelable(Parcel &parcel) const +{ + if (!parcel.WriteStrongParcelable(request_)) { + ANS_LOGE("Can't write request"); + return false; + } + + return true; +} + +bool Notification::Marshalling(Parcel &parcel) const +{ + if (!MarshallingBool(parcel)) { + return false; + } + if (!MarshallingString(parcel)) { + return false; + } + if (!MarshallingInt32(parcel)) { + return false; + } + if (!MarshallingInt64(parcel)) { + return false; + } + if (!MarshallingParcelable(parcel)) { + return false; + } + + return true; +} + +void Notification::ReadFromParcelBool(Parcel &parcel) { // Read enableLight_ enableLight_ = parcel.ReadBool(); @@ -238,35 +347,68 @@ bool Notification::ReadFromParcel(Parcel &parcel) // Read enableViration_ enableViration_ = parcel.ReadBool(); + // Read isRemoveAllowed_ + isRemoveAllowed_ = parcel.ReadBool(); +} + +void Notification::ReadFromParcelString(Parcel &parcel) +{ // Read key_ key_ = parcel.ReadString(); + // Read sound_ + if (enableSound_) { + sound_ = std::make_shared(parcel.ReadString()); + } + + // Read deviceId_ + deviceId_ = parcel.ReadString(); +} + +void Notification::ReadFromParcelInt32(Parcel &parcel) +{ // Read ledLightColor_ ledLightColor_ = parcel.ReadInt32(); // Read lockscreenVisibleness_ lockscreenVisibleness_ = static_cast(parcel.ReadInt32()); - // Read request_ - request_ = parcel.ReadStrongParcelable(); + // Read remindType_ + remindType_ = static_cast(parcel.ReadInt32()); + // Read sourceType_ + sourceType_ = static_cast(parcel.ReadInt32()); +} + +void Notification::ReadFromParcelInt64(Parcel &parcel) +{ // Read postTime_ postTime_ = parcel.ReadInt64(); - // Read sound_ - if (enableSound_) { - sound_ = std::make_shared(parcel.ReadString()); - } - // Read vibrationStyle_ parcel.ReadInt64Vector(&vibrationStyle_); +} + +void Notification::ReadFromParcelParcelable(Parcel &parcel) +{ + // Read request_ + request_ = parcel.ReadStrongParcelable(); +} + +bool Notification::ReadFromParcel(Parcel &parcel) +{ + ReadFromParcelBool(parcel); + ReadFromParcelString(parcel); + ReadFromParcelInt32(parcel); + ReadFromParcelInt64(parcel); + ReadFromParcelParcelable(parcel); return true; } Notification *Notification::Unmarshalling(Parcel &parcel) { - Notification *n = new Notification(); + Notification *n = new (std::nothrow) Notification(); if (n && !n->ReadFromParcel(parcel)) { ANS_LOGE("Read from parcel error"); delete n; @@ -315,33 +457,52 @@ void Notification::SetVibrationStyle(const std::vector &style) vibrationStyle_ = style; } -std::string Notification::GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id) +void Notification::SetRemindType(const NotificationConstant::RemindType &reminType) +{ + remindType_ = reminType; +} + +std::string Notification::GenerateNotificationKey( + const std::string &deviceId, int32_t uid, const std::string &label, int32_t id) { const char *KEY_SPLITER = "_"; std::stringstream stream; - stream << uid << KEY_SPLITER << label << KEY_SPLITER << id; + stream << deviceId << KEY_SPLITER << uid << KEY_SPLITER << label << KEY_SPLITER << id; return stream.str(); } +void Notification::SetRemoveAllowed(bool removeAllowed) +{ + isRemoveAllowed_ = removeAllowed; +} + +void Notification::SetSourceType(NotificationConstant::SourceType sourceType) +{ + sourceType_ = sourceType; +} + std::string Notification::Dump() const { - std::string dump = "Notification{ key = " + key_ + ", ledLightColor = " + std::to_string(ledLightColor_) + - ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + - ",request = "; - if (request_ == nullptr) { - dump += "nullptr"; - } else { - dump += request_->Dump(); - } - dump = dump + ",postTime = " + std::to_string(postTime_) + ",sound = " + sound_->ToString() + "vibrationStyle = "; + std::string vibrationStyle = ""; for (auto &style : vibrationStyle_) { - dump += std::to_string(style); - dump += ","; + vibrationStyle += std::to_string(style); + vibrationStyle += ", "; } - return dump; + return "Notification{ " + "key = " + key_ + + ", ledLightColor = " + std::to_string(ledLightColor_) + + ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + + ", remindType = " + std::to_string(static_cast(remindType_)) + + ", isRemoveAllowed = " + (isRemoveAllowed_ ? "true" : "false") + + ", sourceType = " + std::to_string(static_cast(sourceType_)) + + ", deviceId = " + deviceId_ + + ", request = " + (request_ == nullptr ? "nullptr" : request_->Dump()) + + ", postTime = " + std::to_string(postTime_) + + ", sound = " + (sound_ == nullptr ? "nullptr" : sound_->ToString()) + + ", vibrationStyle = [" + vibrationStyle + "]" + + " }"; } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index 4c114748e9b228046097642cf7370bd35c27e103..b61dbf836de2c688388226cdcc2f0da7ec85fde0 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -15,14 +15,16 @@ #include "notification_action_button.h" -#include +#include "ans_image_util.h" #include "ans_log_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" +#include "want_agent_helper.h" namespace OHOS { namespace Notification { std::shared_ptr NotificationActionButton::Create(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, - const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, + const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, const std::vector> &userInputs, bool isContextual) { @@ -33,10 +35,9 @@ std::shared_ptr NotificationActionButton::Create(const auto realExtras = extras; if (!realExtras) { - realExtras = std::make_shared(); - + realExtras = std::make_shared(); if (!realExtras) { - ANS_LOGE("create PacMap object failed"); + ANS_LOGE("create WantParams object failed"); return {}; } } @@ -75,6 +76,11 @@ std::shared_ptr NotificationActionButton::Create(const std::shared_ptr NotificationActionButton::Create( const std::shared_ptr &actionButton) { + if (!actionButton) { + ANS_LOGW("invalid input NotificationActionButton object"); + return {}; + } + return NotificationActionButton::Create(actionButton->GetIcon(), actionButton->GetTitle(), actionButton->GetWantAgent(), @@ -88,7 +94,7 @@ std::shared_ptr NotificationActionButton::Create( NotificationActionButton::NotificationActionButton(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, - const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, + const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, const std::vector> &userInputs, bool isContextual) : icon_(icon), @@ -117,12 +123,14 @@ const std::shared_ptr NotificationActionButton::GetWantAge return wantAgent_; } -void NotificationActionButton::AddAdditionalData(AppExecFwk::PacMap &pacMap) +void NotificationActionButton::AddAdditionalData(AAFwk::WantParams &extras) { - extras_->PutAll(pacMap); + if (extras_) { + *extras_ = extras; + } } -const std::shared_ptr NotificationActionButton::GetAdditionalData() const +const std::shared_ptr NotificationActionButton::GetAdditionalData() const { return extras_; } @@ -194,10 +202,89 @@ bool NotificationActionButton::IsContextDependent() const std::string NotificationActionButton::Dump() { - return "NotificationActionButton[ title = " + title_ + - ", semanticActionButton = " + std::to_string(static_cast(semanticActionButton_)) + - ", autoCreatedReplies = " + (autoCreatedReplies_ ? "true" : "false") + - ", isContextual = " + (isContextual_ ? "true" : "false") + " ]"; + std::string mimeTypeOnlyUserInputs = ""; + for (auto &item : mimeTypeOnlyUserInputs_) { + if (!item) { + mimeTypeOnlyUserInputs += "nullptr, "; + continue; + } + mimeTypeOnlyUserInputs += item->Dump(); + mimeTypeOnlyUserInputs += ", "; + } + + std::string userInputs = ""; + for (auto &item : userInputs_) { + if (!item) { + userInputs += "nullptr, "; + continue; + } + userInputs += item->Dump(); + userInputs += ", "; + } + + return "NotificationActionButton{ " + "title = " + title_ + + ", semanticActionButton = " + std::to_string(static_cast(semanticActionButton_)) + + ", autoCreatedReplies = " + (autoCreatedReplies_ ? "true" : "false") + + ", isContextual = " + (isContextual_ ? "true" : "false") + + ", mimeTypeOnlyUserInputs = [" + mimeTypeOnlyUserInputs + "]" + + ", userInputs = [" + userInputs + "]" + + " }"; +} + +bool NotificationActionButton::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["icon"] = AnsImageUtil::PackImage(icon_); + jsonObject["title"] = title_; + jsonObject["wantAgent"] = wantAgent_ ? WantAgent::WantAgentHelper::ToString(wantAgent_) : ""; + + std::string extrasStr; + if (extras_) { + AAFwk::WantParamWrapper wWrapper(*extras_); + extrasStr = wWrapper.ToString(); + } + jsonObject["extras"] = extrasStr; + + return true; +} + +NotificationActionButton *NotificationActionButton::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pButton = new (std::nothrow) NotificationActionButton(); + if (pButton == nullptr) { + ANS_LOGE("Failed to create actionButton instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("icon") != jsonEnd) { + auto iconStr = jsonObject.at("icon").get(); + pButton->icon_ = AnsImageUtil::UnPackImage(iconStr); + } + + if (jsonObject.find("title") != jsonEnd) { + pButton->title_ = jsonObject.at("title").get(); + } + + if (jsonObject.find("wantAgent") != jsonEnd) { + auto wantAgentValue = jsonObject.at("wantAgent").get(); + pButton->wantAgent_ = WantAgent::WantAgentHelper::FromString(wantAgentValue); + } + + if (jsonObject.find("extras") != jsonEnd) { + auto extrasString = jsonObject.at("extras").get(); + if (!extrasString.empty()) { + AAFwk::WantParams params = AAFwk::WantParamWrapper::ParseWantParams(extrasString); + pButton->extras_ = std::make_shared(params); + } + } + + return pButton; } bool NotificationActionButton::Marshalling(Parcel &parcel) const @@ -288,8 +375,8 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const NotificationActionButton *NotificationActionButton::Unmarshalling(Parcel &parcel) { - auto pButton = new NotificationActionButton(); - if ((nullptr != pButton) && !pButton->ReadFromParcel(parcel)) { + auto pButton = new (std::nothrow) NotificationActionButton(); + if ((pButton != nullptr) && !pButton->ReadFromParcel(parcel)) { delete pButton; pButton = nullptr; } @@ -332,7 +419,7 @@ bool NotificationActionButton::ReadFromParcel(Parcel &parcel) valid = parcel.ReadBool(); if (valid) { - extras_ = std::shared_ptr(parcel.ReadParcelable()); + extras_ = std::shared_ptr(parcel.ReadParcelable()); if (!extras_) { ANS_LOGE("Failed to read extras"); return false; @@ -345,7 +432,7 @@ bool NotificationActionButton::ReadFromParcel(Parcel &parcel) NotificationUserInput *member {nullptr}; if (valid) { member = parcel.ReadParcelable(); - if (nullptr == member) { + if (member == nullptr) { ANS_LOGE("Failed to read userInput"); return false; } diff --git a/frameworks/ans/native/src/notification_basic_content.cpp b/frameworks/ans/native/src/notification_basic_content.cpp index 4942104e27005aed6c96a26185e47e50a81796ac..0ab51a5c32f1697c0341cd9549c3ad8356730fa1 100644 --- a/frameworks/ans/native/src/notification_basic_content.cpp +++ b/frameworks/ans/native/src/notification_basic_content.cpp @@ -56,6 +56,36 @@ std::string NotificationBasicContent::Dump() return "title = " + title_ + ", text = " + text_ + ", additionalText = " + additionalText_; } +bool NotificationBasicContent::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["text"] = text_; + jsonObject["title"] = title_; + jsonObject["additionalText"] = additionalText_; + + return true; +} + +void NotificationBasicContent::ReadFromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("text") != jsonEnd) { + text_ = jsonObject.at("text").get(); + } + + if (jsonObject.find("title") != jsonEnd) { + title_ = jsonObject.at("title").get(); + } + + if (jsonObject.find("additionalText") != jsonEnd) { + additionalText_ = jsonObject.at("additionalText").get(); + } +} + bool NotificationBasicContent::Marshalling(Parcel &parcel) const { if (!parcel.WriteString(text_)) { diff --git a/frameworks/ans/native/src/notification_bundle_option.cpp b/frameworks/ans/native/src/notification_bundle_option.cpp index b5adae94ec9affbf19a620b61aafe74774d14544..7e83ebb8cd2ff6ca6809f8524c386a808f538c76 100644 --- a/frameworks/ans/native/src/notification_bundle_option.cpp +++ b/frameworks/ans/native/src/notification_bundle_option.cpp @@ -18,7 +18,8 @@ namespace OHOS { namespace Notification { -NotificationBundleOption::NotificationBundleOption(const std::string &bundleName, const int32_t uid) : bundleName_(bundleName), uid_(uid) +NotificationBundleOption::NotificationBundleOption(const std::string &bundleName, const int32_t uid) + : bundleName_(bundleName), uid_(uid) {} NotificationBundleOption::~NotificationBundleOption() @@ -46,7 +47,10 @@ int32_t NotificationBundleOption::GetUid() const std::string NotificationBundleOption::Dump() { - return "NotificationBundleOption[ bundleName = " + bundleName_ + ", uid = " + std::to_string(uid_) + " ]"; + return "NotificationBundleOption{ " + "bundleName = " + bundleName_ + + ", uid = " + std::to_string(uid_) + + " }"; } bool NotificationBundleOption::Marshalling(Parcel &parcel) const @@ -66,7 +70,7 @@ bool NotificationBundleOption::Marshalling(Parcel &parcel) const NotificationBundleOption *NotificationBundleOption::Unmarshalling(Parcel &parcel) { - auto pbundleOption = new NotificationBundleOption(); + auto pbundleOption = new (std::nothrow) NotificationBundleOption(); if ((nullptr != pbundleOption) && !pbundleOption->ReadFromParcel(parcel)) { delete pbundleOption; pbundleOption = nullptr; diff --git a/frameworks/ans/native/src/notification_constant.cpp b/frameworks/ans/native/src/notification_constant.cpp index 43f23d63c8a35e2e66e8127514e0c116ae88c98f..5637d588d029b01a062a52b4e2e00f93267e7a80 100644 --- a/frameworks/ans/native/src/notification_constant.cpp +++ b/frameworks/ans/native/src/notification_constant.cpp @@ -18,6 +18,5 @@ namespace OHOS { namespace Notification { const std::string NotificationConstant::EXTRA_INPUTS_SOURCE {"notification_user_input_source"}; - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp index 1accb1daafbfaf6c272bebb5f8d45039291df2f0..dbd39018996bea0abbe673bbffd8aaecac360848 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -106,8 +106,56 @@ std::string NotificationContent::Dump() : (contentType_ == NotificationContent::Type::MULTILINE) ? "MULTILINE" : (contentType_ == NotificationContent::Type::PICTURE) ? "PICTURE" : "NONE"; - return "NotificationContent[ contentType = " + contentTypeStr + - ", content = " + (content_ ? "not null" : "null") + "]"; + return "NotificationContent{ " + "contentType = " + contentTypeStr + + ", content = " + (content_ ? content_->Dump() : "null") + + " }"; +} + +bool NotificationContent::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["contentType"] = static_cast(contentType_); + + if (!content_) { + ANS_LOGE("Invalid content. Cannot convert to JSON."); + return false; + } + + nlohmann::json contentObj; + if (!NotificationJsonConverter::ConvertToJosn(content_.get(), contentObj)) { + ANS_LOGE("Cannot convert content to JSON"); + return false; + } + jsonObject["content"] = contentObj; + + return true; +} + +NotificationContent *NotificationContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + const auto &jsonEnd = jsonObject.cend(); + if ((jsonObject.find("contentType") == jsonEnd) || (jsonObject.find("content") == jsonEnd)) { + ANS_LOGE("Incomplete NotificationContent json object. Cannot convert content from JSON."); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create NotificationContent instance"); + return nullptr; + } + + if (!ConvertJsonToContent(pContent, jsonObject)) { + delete pContent; + pContent = nullptr; + return nullptr; + } + + return pContent; } bool NotificationContent::Marshalling(Parcel &parcel) const @@ -135,8 +183,8 @@ bool NotificationContent::Marshalling(Parcel &parcel) const NotificationContent *NotificationContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } @@ -154,63 +202,85 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) } switch (contentType_) { - case NotificationContent::Type::BASIC_TEXT: { - std::shared_ptr normalContent( - parcel.ReadParcelable()); - if (!normalContent) { - ANS_LOGE("Failed to read normal content"); - return false; - } - content_ = std::dynamic_pointer_cast(normalContent); - } break; - case NotificationContent::Type::CONVERSATION: { - std::shared_ptr conversationalContent( - parcel.ReadParcelable()); - if (!conversationalContent) { - ANS_LOGE("Failed to read conversational content"); - return false; - } - content_ = std::dynamic_pointer_cast(conversationalContent); - } break; - case NotificationContent::Type::LONG_TEXT: { - std::shared_ptr longTextContent( - parcel.ReadParcelable()); - if (!longTextContent) { - ANS_LOGE("Failed to read long text content"); - return false; - } - content_ = std::dynamic_pointer_cast(longTextContent); - } break; - case NotificationContent::Type::MEDIA: { - std::shared_ptr mediaContent(parcel.ReadParcelable()); - if (!mediaContent) { - ANS_LOGE("Failed to read media content"); - return false; - } - content_ = std::dynamic_pointer_cast(mediaContent); - } break; - case NotificationContent::Type::MULTILINE: { - std::shared_ptr multiLineContent( - parcel.ReadParcelable()); - if (!multiLineContent) { - ANS_LOGE("Failed to read multiLine content"); - return false; - } - content_ = std::dynamic_pointer_cast(multiLineContent); - } break; - case NotificationContent::Type::PICTURE: { - std::shared_ptr pictureContent( - parcel.ReadParcelable()); - if (!pictureContent) { - ANS_LOGE("Failed to read picture content"); - return false; - } - content_ = std::dynamic_pointer_cast(pictureContent); - } break; - default: { + case NotificationContent::Type::BASIC_TEXT: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); + break; + case NotificationContent::Type::CONVERSATION: + content_ = + std::static_pointer_cast(std::shared_ptr( + parcel.ReadParcelable())); + break; + case NotificationContent::Type::LONG_TEXT: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); + break; + case NotificationContent::Type::MEDIA: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); + break; + case NotificationContent::Type::MULTILINE: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); + break; + case NotificationContent::Type::PICTURE: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); + break; + default: + ANS_LOGE("Invalid contentType"); return false; - } break; } + if (!content_) { + ANS_LOGE("Failed to read content"); + return false; + } + + return true; +} + +bool NotificationContent::ConvertJsonToContent(NotificationContent *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return false; + } + + auto contentTypeValue = jsonObject.at("contentType").get(); + target->contentType_ = static_cast(contentTypeValue); + + auto contentObj = jsonObject.at("content"); + if (contentObj.is_null()) { + ANS_LOGE("Invalid json object. Cannot convert content from JSON."); + return false; + } + + NotificationBasicContent *pBasicContent {nullptr}; + switch (target->contentType_) { + case NotificationContent::Type::BASIC_TEXT: + pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + break; + case NotificationContent::Type::CONVERSATION: + pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + break; + case NotificationContent::Type::LONG_TEXT: + pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + break; + case NotificationContent::Type::MULTILINE: + pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + break; + case NotificationContent::Type::PICTURE: + pBasicContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + break; + default: + ANS_LOGE("Invalid contentType"); + break; + } + if (pBasicContent == nullptr) { + ANS_LOGE("Parse content error!"); + return false; + } + target->content_ = std::shared_ptr(pBasicContent); return true; } diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 2b1925d8432d563c48ef9a46e73001751b7a4051..08f3599b71af42ee59cf801cb61c56a16dc69216 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -76,10 +76,102 @@ NotificationConversationalContent::MessageVector NotificationConversationalConte std::string NotificationConversationalContent::Dump() { - return "NotificationConversationalContent[ " + NotificationBasicContent::Dump() + - ", conversationTitle = " + conversationTitle_ + ", isGroup = " + (isGroup_ ? "true" : "false") + - ", messageUser = " + messageUser_.Dump() + - ", messages = " + (!messages_.empty() ? "not empty" : "empty") + " ]"; + std::string messages = ""; + for (auto &message : messages_) { + if (!message) { + messages += "nullptr, "; + continue; + } + messages += message->Dump(); + messages += ", "; + } + return "NotificationConversationalContent{ " + NotificationBasicContent::Dump() + + ", conversationTitle = " + conversationTitle_ + + ", isGroup = " + (isGroup_ ? "true" : "false") + + ", messageUser = " + messageUser_.Dump() + + ", messages = " + messages + + " }"; +} + +bool NotificationConversationalContent::ToJson(nlohmann::json &jsonObject) const +{ + if (!NotificationBasicContent::ToJson(jsonObject)) { + ANS_LOGE("Cannot convert basicContent to JSON"); + return false; + } + + nlohmann::json userObj; + if (!NotificationJsonConverter::ConvertToJosn(&messageUser_, userObj)) { + ANS_LOGE("Cannot convert messageUser to JSON"); + return false; + } + jsonObject["messageUser"] = userObj; + + jsonObject["conversationTitle"] = conversationTitle_; + jsonObject["isGroup"] = isGroup_; + + nlohmann::json msgsArr = nlohmann::json::array(); + for (auto &msg : messages_) { + if (!msg) { + continue; + } + + nlohmann::json msgObj; + if (!NotificationJsonConverter::ConvertToJosn(msg.get(), msgObj)) { + ANS_LOGE("Cannot convert conversationalMessage to JSON"); + return false; + } + msgsArr.emplace_back(msgObj); + } + jsonObject["messages"] = msgsArr; + + return true; +} + +NotificationConversationalContent *NotificationConversationalContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationConversationalContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create conversationalContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("messageUser") != jsonEnd) { + auto userObj = jsonObject.at("messageUser"); + auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj); + if (pUser != nullptr) { + pContent->messageUser_ = *pUser; + + delete pUser; + pUser = nullptr; + } + } + + if (jsonObject.find("messages") != jsonEnd) { + nlohmann::json msgsArr = jsonObject.at("messages"); + for (auto &msgObj : msgsArr) { + auto pMsg = NotificationJsonConverter::ConvertFromJosn(msgObj); + if (pMsg == nullptr) { + ANS_LOGE("Failed to parse message "); + + delete pContent; + pContent = nullptr; + return nullptr; + } + + pContent->messages_.emplace_back(pMsg); + } + } + + return pContent; } bool NotificationConversationalContent::Marshalling(Parcel &parcel) const @@ -132,8 +224,8 @@ bool NotificationConversationalContent::Marshalling(Parcel &parcel) const NotificationConversationalContent *NotificationConversationalContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationConversationalContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationConversationalContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp index 9274ef8aa3fa392e3c6700da980a0621328d65e0..520a5fbfca36af631ac6a78b337c3edc8a2b25e2 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -56,9 +56,78 @@ const std::shared_ptr NotificationConversationalMessage::GetUri() const std::string NotificationConversationalMessage::Dump() { - return "NotificationConversationalMessage[ text = " + text_ + ", arrivedTime = " + std::to_string(arrivedTime_) + - ", mimeType = " + mimeType_ + ", uri = " + (uri_ ? uri_->ToString() : "null") + - ", sender = " + sender_.Dump() + " ]"; + return "NotificationConversationalMessage{ " + "text = " + text_ + + ", arrivedTime = " + std::to_string(arrivedTime_) + + ", mimeType = " + mimeType_ + + ", uri = " + (uri_ ? uri_->ToString() : "null") + + ", sender = " + sender_.Dump() + + " }"; +} + +bool NotificationConversationalMessage::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["arrivedTime"] = arrivedTime_; + jsonObject["text"] = text_; + + nlohmann::json userObj; + if (!NotificationJsonConverter::ConvertToJosn(&sender_, userObj)) { + ANS_LOGE("Cannot convert sender to JSON"); + return false; + } + jsonObject["sender"] = userObj; + + jsonObject["uri"] = uri_ ? uri_->ToString() : ""; + jsonObject["mimeType"] = mimeType_; + + return true; +} + +NotificationConversationalMessage *NotificationConversationalMessage::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pMessage = new (std::nothrow) NotificationConversationalMessage(); + if (pMessage == nullptr) { + ANS_LOGE("Failed to create conversationalMessage instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("arrivedTime") != jsonEnd) { + pMessage->arrivedTime_ = jsonObject.at("arrivedTime").get(); + } + + if (jsonObject.find("text") != jsonEnd) { + pMessage->text_ = jsonObject.at("text").get(); + } + + if (jsonObject.find("sender") != jsonEnd) { + auto userObj = jsonObject.at("sender"); + auto pUser = NotificationJsonConverter::ConvertFromJosn(userObj); + if (pUser != nullptr) { + pMessage->sender_ = *pUser; + + delete pUser; + pUser = nullptr; + } + } + + if (jsonObject.find("uri") != jsonEnd) { + auto uriStr = jsonObject.at("uri").get(); + if (!uriStr.empty()) { + pMessage->uri_ = std::make_shared(uriStr); + } + } + + if (jsonObject.find("mimeType") != jsonEnd) { + pMessage->mimeType_ = jsonObject.at("mimeType").get(); + } + + return pMessage; } bool NotificationConversationalMessage::Marshalling(Parcel &parcel) const @@ -101,8 +170,8 @@ bool NotificationConversationalMessage::Marshalling(Parcel &parcel) const NotificationConversationalMessage *NotificationConversationalMessage::Unmarshalling(Parcel &parcel) { - auto pMessage = new NotificationConversationalMessage(); - if ((nullptr != pMessage) && !pMessage->ReadFromParcel(parcel)) { + auto pMessage = new (std::nothrow) NotificationConversationalMessage(); + if ((pMessage != nullptr) && !pMessage->ReadFromParcel(parcel)) { delete pMessage; pMessage = nullptr; } diff --git a/frameworks/ans/native/src/notification_distributed_options.cpp b/frameworks/ans/native/src/notification_distributed_options.cpp new file mode 100644 index 0000000000000000000000000000000000000000..dbfb26a275de63819df7b2262afed6180f288f69 --- /dev/null +++ b/frameworks/ans/native/src/notification_distributed_options.cpp @@ -0,0 +1,163 @@ +/* + * 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 "notification_distributed_options.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationDistributedOptions::NotificationDistributedOptions( + bool distribute, const std::vector &dvsDisplay, const std::vector &dvsOperate) + : isDistributed_(distribute), devicesSupportDisplay_(dvsDisplay), devicesSupportOperate_(dvsOperate) +{} + +void NotificationDistributedOptions::SetDistributed(bool distribute) +{ + isDistributed_ = distribute; +} + +bool NotificationDistributedOptions::IsDistributed() const +{ + return isDistributed_; +} + +void NotificationDistributedOptions::SetDevicesSupportDisplay(const std::vector &devices) +{ + devicesSupportDisplay_ = devices; +} + +std::vector NotificationDistributedOptions::GetDevicesSupportDisplay() const +{ + return devicesSupportDisplay_; +} + +void NotificationDistributedOptions::SetDevicesSupportOperate(const std::vector &devices) +{ + devicesSupportOperate_ = devices; +} + +std::vector NotificationDistributedOptions::GetDevicesSupportOperate() const +{ + return devicesSupportOperate_; +} + +std::string NotificationDistributedOptions::Dump() +{ + std::string devicesSupportDisplay = ""; + for (auto &device : devicesSupportDisplay_) { + devicesSupportDisplay += device; + devicesSupportDisplay += ", "; + } + + std::string devicesSupportOperate = ""; + for (auto &device : devicesSupportOperate_) { + devicesSupportOperate += device; + devicesSupportOperate += ", "; + } + + return "NotificationDistributedOptions{ " + "isDistributed = " + std::string((isDistributed_ ? "true" : "false")) + + ", devicesSupportDisplay = [" + devicesSupportDisplay + "]" + + ", devicesSupportOperate = [" + devicesSupportOperate + "]" + + " }"; +} + +bool NotificationDistributedOptions::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["isDistributed"] = isDistributed_; + jsonObject["devicesSupportDisplay"] = nlohmann::json(devicesSupportDisplay_); + jsonObject["devicesSupportOperate"] = nlohmann::json(devicesSupportOperate_); + + return true; +} + +NotificationDistributedOptions *NotificationDistributedOptions::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pOpt = new (std::nothrow) NotificationDistributedOptions(); + if (pOpt == nullptr) { + ANS_LOGE("Failed to create distributedOptions instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("isDistributed") != jsonEnd) { + pOpt->isDistributed_ = jsonObject.at("isDistributed").get(); + } + + if (jsonObject.find("devicesSupportDisplay") != jsonEnd) { + pOpt->devicesSupportDisplay_ = jsonObject.at("devicesSupportDisplay").get>(); + } + + if (jsonObject.find("devicesSupportOperate") != jsonEnd) { + pOpt->devicesSupportOperate_ = jsonObject.at("devicesSupportOperate").get>(); + } + + return pOpt; +} + +bool NotificationDistributedOptions::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteBool(isDistributed_)) { + ANS_LOGE("Failed to write flag isdistributed"); + return false; + } + + if (!parcel.WriteStringVector(devicesSupportDisplay_)) { + ANS_LOGE("Failed to write devicesSupportDisplay"); + return false; + } + + if (!parcel.WriteStringVector(devicesSupportOperate_)) { + ANS_LOGE("Failed to write devicesSupportOperate"); + return false; + } + + return true; +} + +NotificationDistributedOptions *NotificationDistributedOptions::Unmarshalling(Parcel &parcel) +{ + auto objptr = new (std::nothrow) NotificationDistributedOptions(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + + return objptr; +} + +bool NotificationDistributedOptions::ReadFromParcel(Parcel &parcel) +{ + isDistributed_ = parcel.ReadBool(); + + if (!parcel.ReadStringVector(&devicesSupportDisplay_)) { + ANS_LOGE("Failed to read devicesSupportDisplay"); + return false; + } + + if (!parcel.ReadStringVector(&devicesSupportOperate_)) { + ANS_LOGE("Failed to read devicesSupportOperate"); + return false; + } + + return true; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_do_not_disturb_date.cpp b/frameworks/ans/native/src/notification_do_not_disturb_date.cpp new file mode 100644 index 0000000000000000000000000000000000000000..188018fd57c2068be1d64143a0d5f0a1dd87797a --- /dev/null +++ b/frameworks/ans/native/src/notification_do_not_disturb_date.cpp @@ -0,0 +1,105 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification_do_not_disturb_date.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +NotificationDoNotDisturbDate::NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType doNotDisturbType, + int64_t beginDate, int64_t endDate) + : doNotDisturbType_(doNotDisturbType), beginDate_(beginDate), endDate_(endDate) +{} + +void NotificationDoNotDisturbDate::SetDoNotDisturbType(NotificationConstant::DoNotDisturbType doNotDisturbType) +{ + doNotDisturbType_ = doNotDisturbType; +} + +NotificationConstant::DoNotDisturbType NotificationDoNotDisturbDate::GetDoNotDisturbType() const +{ + return doNotDisturbType_; +} + +void NotificationDoNotDisturbDate::SetBeginDate(const int64_t beginDate) +{ + beginDate_ = beginDate; +} + +int64_t NotificationDoNotDisturbDate::GetBeginDate() const +{ + return beginDate_; +} + +void NotificationDoNotDisturbDate::SetEndDate(const int64_t endDate) +{ + endDate_ = endDate; +} + +int64_t NotificationDoNotDisturbDate::GetEndDate() const +{ + return endDate_; +} + +std::string NotificationDoNotDisturbDate::Dump() +{ + return "NotificationDoNotDisturbDate{ " + "doNotDisturbType = " + std::to_string(static_cast(doNotDisturbType_)) + + ", beginDate = " + std::to_string(beginDate_) + + ", endDate = " + std::to_string(endDate_) + + " }"; +} + +bool NotificationDoNotDisturbDate::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteInt32(static_cast(doNotDisturbType_))) { + ANS_LOGE("Failed to write doNotDisturbType"); + return false; + } + + if (!parcel.WriteInt64(beginDate_)) { + ANS_LOGE("Failed to write begin time"); + return false; + } + + if (!parcel.WriteInt64(endDate_)) { + ANS_LOGE("Failed to write end time"); + return false; + } + + return true; +} + +NotificationDoNotDisturbDate *NotificationDoNotDisturbDate::Unmarshalling(Parcel &parcel) +{ + auto objptr = new (std::nothrow) NotificationDoNotDisturbDate(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + + return objptr; +} + +bool NotificationDoNotDisturbDate::ReadFromParcel(Parcel &parcel) +{ + doNotDisturbType_ = static_cast(parcel.ReadInt32()); + beginDate_ = parcel.ReadInt64(); + endDate_ = parcel.ReadInt64(); + + return true; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_flags.cpp b/frameworks/ans/native/src/notification_flags.cpp new file mode 100644 index 0000000000000000000000000000000000000000..901964bc74583c1d4390df4a91d6559e63b37856 --- /dev/null +++ b/frameworks/ans/native/src/notification_flags.cpp @@ -0,0 +1,114 @@ +/* + * 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 "notification_flags.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +void NotificationFlags::SetSoundEnabled(bool soundEnabled) +{ + soundEnabled_ = soundEnabled; +} + +bool NotificationFlags::IsSoundEnabled() const +{ + return soundEnabled_; +} + +void NotificationFlags::SetVibrationEnabled(bool vibrationEnabled) +{ + vibrationEnabled_ = vibrationEnabled; +} + +bool NotificationFlags::IsVibrationEnabled() const +{ + return vibrationEnabled_; +} + +std::string NotificationFlags::Dump() +{ + return "soundEnabled = " + std::string(soundEnabled_ ? "true" : "false") + + ", vibrationEnabled = " + std::string(vibrationEnabled_ ? "true" : "false"); +} + +bool NotificationFlags::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["soundEnabled"] = soundEnabled_; + jsonObject["vibrationEnabled"] = vibrationEnabled_; + + return true; +} + +NotificationFlags *NotificationFlags::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pFlags = new (std::nothrow) NotificationFlags(); + if (pFlags == nullptr) { + ANS_LOGE("Failed to create notificationFlags instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("soundEnabled") != jsonEnd) { + pFlags->soundEnabled_ = jsonObject.at("soundEnabled").get(); + } + + if (jsonObject.find("vibrationEnabled") != jsonEnd) { + pFlags->vibrationEnabled_ = jsonObject.at("vibrationEnabled").get(); + } + + return pFlags; +} + +bool NotificationFlags::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteBool(soundEnabled_)) { + ANS_LOGE("Failed to write flag sound enable for the notification"); + return false; + } + + if (!parcel.WriteBool(vibrationEnabled_)) { + ANS_LOGE("Failed to write flag vibration enable for the notification"); + return false; + } + + return true; +} + +NotificationFlags *NotificationFlags::Unmarshalling(Parcel &parcel) +{ + auto templ = new NotificationFlags(); + if ((templ != nullptr) && !templ->ReadFromParcel(parcel)) { + delete templ; + templ = nullptr; + } + + return templ; +} + +bool NotificationFlags::ReadFromParcel(Parcel &parcel) +{ + soundEnabled_ = parcel.ReadBool(); + vibrationEnabled_ = parcel.ReadBool(); + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 87d459c55ee5651eacefdcb4f55d24fb702e5a41..9452c6a5cc696a4ea2a245ae7670d2a3e145561e 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -296,14 +296,75 @@ ErrCode NotificationHelper::GetShowBadgeEnabled(bool &enabled) return DelayedSingleton::GetInstance()->GetShowBadgeEnabled(enabled); } -ErrCode NotificationHelper::SetDisturbMode(NotificationConstant::DisturbMode mode) +ErrCode NotificationHelper::CancelGroup(const std::string &groupName) { - return DelayedSingleton::GetInstance()->SetDisturbMode(mode); + return DelayedSingleton::GetInstance()->CancelGroup(groupName); } -ErrCode NotificationHelper::GetDisturbMode(NotificationConstant::DisturbMode &disturbMode) +ErrCode NotificationHelper::RemoveGroupByBundle( + const NotificationBundleOption &bundleOption, const std::string &groupName) { - return DelayedSingleton::GetInstance()->GetDisturbMode(disturbMode); + return DelayedSingleton::GetInstance()->RemoveGroupByBundle(bundleOption, groupName); +} + +ErrCode NotificationHelper::SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate) +{ + return DelayedSingleton::GetInstance()->SetDoNotDisturbDate(doNotDisturbDate); +} + +ErrCode NotificationHelper::GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate) +{ + return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(doNotDisturbDate); +} + +ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); +} + +ErrCode NotificationHelper::IsDistributedEnabled(bool &enabled) +{ + return DelayedSingleton::GetInstance()->IsDistributedEnabled(enabled); +} + +ErrCode NotificationHelper::EnableDistributed(const bool enabled) +{ + return DelayedSingleton::GetInstance()->EnableDistributed(enabled); +} + +ErrCode NotificationHelper::EnableDistributedByBundle(const NotificationBundleOption &bundleOption, const bool enabled) +{ + return DelayedSingleton::GetInstance()->EnableDistributedByBundle(bundleOption, enabled); +} + +ErrCode NotificationHelper::EnableDistributedSelf(const bool enabled) +{ + return DelayedSingleton::GetInstance()->EnableDistributedSelf(enabled); +} + +ErrCode NotificationHelper::IsDistributedEnableByBundle(const NotificationBundleOption &bundleOption, bool &enabled) +{ + return DelayedSingleton::GetInstance()->IsDistributedEnableByBundle(bundleOption, enabled); +} + +ErrCode NotificationHelper::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +{ + return DelayedSingleton::GetInstance()->GetDeviceRemindType(remindType); +} + +ErrCode NotificationHelper::PublishContinuousTaskNotification(const NotificationRequest &request) +{ + return DelayedSingleton::GetInstance()->PublishContinuousTaskNotification(request); +} + +ErrCode NotificationHelper::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + return DelayedSingleton::GetInstance()->CancelContinuousTaskNotification(label, notificationId); +} + +ErrCode NotificationHelper::IsSupportTemplate(const std::string &templateName, bool &support) +{ + return DelayedSingleton::GetInstance()->IsSupportTemplate(templateName, support); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp index c806df2ef08e8d4b0b8f9ce4d178a063e6a6fa55..7abf07403844dd0f3b79f89f40dcbecb15c5a522 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include #include "notification_long_text_content.h" + #include "ans_log_wrapper.h" namespace OHOS { @@ -64,9 +64,56 @@ std::string NotificationLongTextContent::GetLongText() const std::string NotificationLongTextContent::Dump() { - return "NotificationLongTextContent[ " + NotificationBasicContent::Dump() + - " longText = " + longText_ + " briefText = " + briefText_ + - " expandedTitle = " + expandedTitle_ + " ]"; + return "NotificationLongTextContent{ " + NotificationBasicContent::Dump() + + ", longText = " + longText_ + + ", briefText = " + briefText_ + + ", expandedTitle = " + expandedTitle_ + + " }"; +} + +bool NotificationLongTextContent::ToJson(nlohmann::json &jsonObject) const +{ + if (!NotificationBasicContent::ToJson(jsonObject)) { + ANS_LOGE("Cannot convert basicContent to JSON"); + return false; + } + + jsonObject["longText"] = longText_; + jsonObject["expandedTitle"] = expandedTitle_; + jsonObject["briefText"] = briefText_; + + return true; +} + +NotificationLongTextContent *NotificationLongTextContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationLongTextContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create longTextContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("longText") != jsonEnd) { + pContent->longText_ = jsonObject.at("longText").get(); + } + + if (jsonObject.find("expandedTitle") != jsonEnd) { + pContent->expandedTitle_ = jsonObject.at("expandedTitle").get(); + } + + if (jsonObject.find("briefText") != jsonEnd) { + pContent->briefText_ = jsonObject.at("briefText").get(); + } + + return pContent; } bool NotificationLongTextContent::Marshalling(Parcel &parcel) const @@ -96,8 +143,8 @@ bool NotificationLongTextContent::Marshalling(Parcel &parcel) const NotificationLongTextContent *NotificationLongTextContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationLongTextContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationLongTextContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_media_content.cpp b/frameworks/ans/native/src/notification_media_content.cpp index d66b8bc7afe9bfa8e7a3fd5a76941fcfcdf234b5..d65672e0ce0b02d5a6b8f61e659cd6fcea9c8672 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include #include "notification_media_content.h" + #include "ans_log_wrapper.h" namespace OHOS { @@ -43,11 +43,48 @@ std::string NotificationMediaContent::Dump() { std::string numbers {}; std::for_each(sequenceNumbers_.begin(), sequenceNumbers_.end(), [&numbers](int32_t num) { - numbers += std::to_string(num) + " "; + numbers += std::to_string(num) + ", "; }); - return "NotificationMediaContent[ " + NotificationBasicContent::Dump() + - ", avToken = " + (avToken_ ? "not null" : "null") + ", sequenceNumbers = " + numbers + " ]"; + return "NotificationMediaContent{ " + NotificationBasicContent::Dump() + + ", avToken = " + (avToken_ ? "not null" : "null") + + ", sequenceNumbers = " + numbers + + " }"; +} + +bool NotificationMediaContent::ToJson(nlohmann::json &jsonObject) const +{ + if (!NotificationBasicContent::ToJson(jsonObject)) { + ANS_LOGE("Cannot convert basicContent to JSON"); + return false; + } + + jsonObject["sequenceNumbers"] = nlohmann::json(sequenceNumbers_); + + return true; +} + +NotificationMediaContent *NotificationMediaContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationMediaContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create mediaContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + const auto& jsonEnd = jsonObject.cend(); + if (jsonObject.find("sequenceNumbers") != jsonEnd) { + pContent->sequenceNumbers_ = jsonObject.at("sequenceNumbers").get>(); + } + + return pContent; } bool NotificationMediaContent::Marshalling(Parcel &parcel) const @@ -67,8 +104,8 @@ bool NotificationMediaContent::Marshalling(Parcel &parcel) const NotificationMediaContent *NotificationMediaContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationMediaContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationMediaContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_multiline_content.cpp b/frameworks/ans/native/src/notification_multiline_content.cpp index abd88be57d106dc3bfc618f0535c91dc021ed089..ef11f4f1dfbfbf9bf6ba6f30a4bd6cf98b6d47cc 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -13,8 +13,10 @@ * limitations under the License. */ -#include #include "notification_multiline_content.h" + +#include + #include "ans_log_wrapper.h" namespace OHOS { @@ -63,8 +65,56 @@ std::string NotificationMultiLineContent::Dump() allLines_.begin(), allLines_.end(), [&lines](const std::string &line) { lines += " " + line + ","; }); lines.pop_back(); - return "NotificationMultiLineContent[ " + NotificationBasicContent::Dump() + ", briefText = " + briefText_ + - ", expandedTitle = " + expandedTitle_ + ", allLines = [" + lines + " ] ]"; + return "NotificationMultiLineContent{ " + NotificationBasicContent::Dump() + + ", briefText = " + briefText_ + + ", expandedTitle = " + expandedTitle_ + + ", allLines = [" + lines + "]" + + " }"; +} + +bool NotificationMultiLineContent::ToJson(nlohmann::json &jsonObject) const +{ + if (!NotificationBasicContent::ToJson(jsonObject)) { + ANS_LOGE("Cannot convert basicContent to JSON"); + return false; + } + + jsonObject["expandedTitle"] = expandedTitle_; + jsonObject["briefText"] = briefText_; + jsonObject["allLines"] = nlohmann::json(allLines_); + + return true; +} + +NotificationMultiLineContent *NotificationMultiLineContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationMultiLineContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create multiLineContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("expandedTitle") != jsonEnd) { + pContent->expandedTitle_ = jsonObject.at("expandedTitle").get(); + } + + if (jsonObject.find("briefText") != jsonEnd) { + pContent->briefText_ = jsonObject.at("briefText").get(); + } + + if (jsonObject.find("allLines") != jsonEnd) { + pContent->allLines_ = jsonObject.at("allLines").get>(); + } + + return pContent; } bool NotificationMultiLineContent::Marshalling(Parcel &parcel) const @@ -94,8 +144,8 @@ bool NotificationMultiLineContent::Marshalling(Parcel &parcel) const NotificationMultiLineContent *NotificationMultiLineContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationMultiLineContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationMultiLineContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_normal_content.cpp b/frameworks/ans/native/src/notification_normal_content.cpp index e9e253789e260af7f117c2cda145b396160ef0a2..a65c134721fe9b0ebcfb532ec3f6e9600836537c 100644 --- a/frameworks/ans/native/src/notification_normal_content.cpp +++ b/frameworks/ans/native/src/notification_normal_content.cpp @@ -14,12 +14,36 @@ */ #include "notification_normal_content.h" +#include "ans_log_wrapper.h" namespace OHOS { namespace Notification { std::string NotificationNormalContent::Dump() { - return "NotificationNormalContent[ " + NotificationBasicContent::Dump() + " ]"; + return "NotificationNormalContent{ " + NotificationBasicContent::Dump() + " }"; +} + +bool NotificationNormalContent::ToJson(nlohmann::json &jsonObject) const +{ + return NotificationBasicContent::ToJson(jsonObject); +} + +NotificationNormalContent *NotificationNormalContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationNormalContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create normalContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + return pContent; } bool NotificationNormalContent::Marshalling(Parcel &parcel) const @@ -29,8 +53,8 @@ bool NotificationNormalContent::Marshalling(Parcel &parcel) const NotificationNormalContent *NotificationNormalContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationNormalContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationNormalContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_picture_content.cpp b/frameworks/ans/native/src/notification_picture_content.cpp index 9138938cb6b1ff178b5f851ef685f2acaa9e3002..e683c5397689f19c65d7ffe5ee6a6092a31506f7 100644 --- a/frameworks/ans/native/src/notification_picture_content.cpp +++ b/frameworks/ans/native/src/notification_picture_content.cpp @@ -14,6 +14,7 @@ */ #include "notification_picture_content.h" +#include "ans_image_util.h" #include "ans_log_wrapper.h" namespace OHOS { @@ -50,8 +51,57 @@ const std::shared_ptr NotificationPictureContent::GetBigPicture std::string NotificationPictureContent::Dump() { - return "NotificationPictureContent[ " + NotificationBasicContent::Dump() + ", briefText = " + briefText_ + - ", expandedTitle = " + expandedTitle_ + ", bigPicture = " + (bigPicture_ ? "not null" : "null") + " ]"; + return "NotificationPictureContent{ " + NotificationBasicContent::Dump() + + ", briefText = " + briefText_ + + ", expandedTitle = " + expandedTitle_ + + ", bigPicture = " + (bigPicture_ ? "not null" : "null") + + " }"; +} + +bool NotificationPictureContent::ToJson(nlohmann::json &jsonObject) const +{ + if (!NotificationBasicContent::ToJson(jsonObject)) { + ANS_LOGE("Cannot convert basicContent to JSON"); + return false; + } + + jsonObject["expandedTitle"] = expandedTitle_; + jsonObject["briefText"] = briefText_; + jsonObject["bigPicture"] = AnsImageUtil::PackImage(bigPicture_); + + return true; +} + +NotificationPictureContent *NotificationPictureContent::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pContent = new (std::nothrow) NotificationPictureContent(); + if (pContent == nullptr) { + ANS_LOGE("Failed to create pictureContent instance"); + return nullptr; + } + + pContent->ReadFromJson(jsonObject); + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("expandedTitle") != jsonEnd) { + pContent->expandedTitle_ = jsonObject.at("expandedTitle").get(); + } + + if (jsonObject.find("briefText") != jsonEnd) { + pContent->briefText_ = jsonObject.at("briefText").get(); + } + + if (jsonObject.find("bigPicture") != jsonEnd) { + auto picStr = jsonObject.at("bigPicture").get(); + pContent->bigPicture_ = AnsImageUtil::UnPackImage(picStr); + } + + return pContent; } bool NotificationPictureContent::Marshalling(Parcel &parcel) const @@ -89,8 +139,8 @@ bool NotificationPictureContent::Marshalling(Parcel &parcel) const NotificationPictureContent *NotificationPictureContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationPictureContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + auto pContent = new (std::nothrow) NotificationPictureContent(); + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index b346882bd29d7610a742ace62a989255f200dec2..9807dace34bda86b9a1f1c13286baa33428126a2 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -13,10 +13,12 @@ * limitations under the License. */ -#include -#include #include "notification_request.h" + +#include "ans_image_util.h" #include "ans_log_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" +#include "want_agent_helper.h" namespace OHOS { namespace Notification { @@ -49,129 +51,16 @@ NotificationRequest::NotificationRequest(int32_t notificationId) : notificationI deliveryTime_ = GetNowSysTime(); } -NotificationRequest::NotificationRequest(const std::shared_ptr &context, int32_t notificationId) - : notificationId_(notificationId), context_(context) -{ - createTime_ = GetNowSysTime(); - deliveryTime_ = GetNowSysTime(); -} - NotificationRequest::NotificationRequest(const NotificationRequest &other) { - this->notificationId_ = other.notificationId_; - this->color_ = other.color_; - this->badgeNumber_ = other.badgeNumber_; - this->progressValue_ = other.progressValue_; - this->progressMax_ = other.progressMax_; - this->createTime_ = other.createTime_; - this->deliveryTime_ = other.deliveryTime_; - this->autoDeletedTime_ = other.autoDeletedTime_; - - this->creatorPid_ = other.creatorPid_; - this->creatorUid_ = other.creatorUid_; - - this->slotType_ = other.slotType_; - this->settingsText_ = other.settingsText_; - this->creatorBundleName_ = other.creatorBundleName_; - this->ownerBundleName_ = other.ownerBundleName_; - this->groupValue_ = other.groupValue_; - this->statusBarText_ = other.statusBarText_; - this->label_ = other.label_; - this->shortcutId_ = other.shortcutId_; - this->sortingKey_ = other.sortingKey_; - this->classification_ = other.classification_; - - this->groupAlertType_ = other.groupAlertType_; - this->visiblenessType_ = other.visiblenessType_; - this->badgeStyle_ = other.badgeStyle_; - this->notificationContentType_ = other.notificationContentType_; - - this->showDeliveryTime_ = other.showDeliveryTime_; - this->tapDismissed_ = other.tapDismissed_; - this->colorEnabled_ = other.colorEnabled_; - this->alertOneTime_ = other.alertOneTime_; - this->showStopwatch_ = other.showStopwatch_; - this->isCountdown_ = other.isCountdown_; - this->inProgress_ = other.inProgress_; - this->groupOverview_ = other.groupOverview_; - this->progressIndeterminate_ = other.progressIndeterminate_; - this->unremovable_ = other.unremovable_; - this->floatingIcon_ = other.floatingIcon_; - this->onlyLocal_ = other.onlyLocal_; - this->permitted_ = other.permitted_; - - this->context_ = other.context_; - this->wantAgent_ = other.wantAgent_; - this->removalWantAgent_ = other.removalWantAgent_; - this->maxScreenWantAgent_ = other.maxScreenWantAgent_; - this->additionalParams_ = other.additionalParams_; - this->littleIcon_ = other.littleIcon_; - this->bigIcon_ = other.bigIcon_; - this->notificationContent_ = other.notificationContent_; - this->publicNotification_ = other.publicNotification_; - - this->actionButtons_ = other.actionButtons_; - this->messageUsers_ = other.messageUsers_; - this->userInputHistory_ = other.userInputHistory_; + CopyBase(other); + CopyOther(other); } NotificationRequest &NotificationRequest::operator=(const NotificationRequest &other) { - this->notificationId_ = other.notificationId_; - this->color_ = other.color_; - this->badgeNumber_ = other.badgeNumber_; - this->progressValue_ = other.progressValue_; - this->progressMax_ = other.progressMax_; - this->createTime_ = other.createTime_; - this->deliveryTime_ = other.deliveryTime_; - this->autoDeletedTime_ = other.autoDeletedTime_; - - this->creatorPid_ = other.creatorPid_; - this->creatorUid_ = other.creatorUid_; - - this->slotType_ = other.slotType_; - this->settingsText_ = other.settingsText_; - this->creatorBundleName_ = other.creatorBundleName_; - this->ownerBundleName_ = other.ownerBundleName_; - this->groupValue_ = other.groupValue_; - this->statusBarText_ = other.statusBarText_; - this->label_ = other.label_; - this->shortcutId_ = other.shortcutId_; - this->sortingKey_ = other.sortingKey_; - this->classification_ = other.classification_; - - this->groupAlertType_ = other.groupAlertType_; - this->visiblenessType_ = other.visiblenessType_; - this->badgeStyle_ = other.badgeStyle_; - this->notificationContentType_ = other.notificationContentType_; - - this->showDeliveryTime_ = other.showDeliveryTime_; - this->tapDismissed_ = other.tapDismissed_; - this->colorEnabled_ = other.colorEnabled_; - this->alertOneTime_ = other.alertOneTime_; - this->showStopwatch_ = other.showStopwatch_; - this->isCountdown_ = other.isCountdown_; - this->inProgress_ = other.inProgress_; - this->groupOverview_ = other.groupOverview_; - this->progressIndeterminate_ = other.progressIndeterminate_; - this->unremovable_ = other.unremovable_; - this->floatingIcon_ = other.floatingIcon_; - this->onlyLocal_ = other.onlyLocal_; - this->permitted_ = other.permitted_; - - this->context_ = other.context_; - this->wantAgent_ = other.wantAgent_; - this->removalWantAgent_ = other.removalWantAgent_; - this->maxScreenWantAgent_ = other.maxScreenWantAgent_; - this->additionalParams_ = other.additionalParams_; - this->littleIcon_ = other.littleIcon_; - this->bigIcon_ = other.bigIcon_; - this->notificationContent_ = other.notificationContent_; - this->publicNotification_ = other.publicNotification_; - - this->actionButtons_ = other.actionButtons_; - this->messageUsers_ = other.messageUsers_; - this->userInputHistory_ = other.userInputHistory_; + CopyBase(other); + CopyOther(other); return *this; } @@ -271,7 +160,7 @@ int64_t NotificationRequest::GetDeliveryTime() const bool NotificationRequest::IsShowDeliveryTime() const { - return (0 != deliveryTime_) && showDeliveryTime_; + return (deliveryTime_ != 0) && showDeliveryTime_; } void NotificationRequest::SetShowDeliveryTime(bool showDeliveryTime) @@ -299,6 +188,11 @@ const std::vector> NotificationRequest return actionButtons_; } +void NotificationRequest::ClearActionButtons() +{ + actionButtons_.clear(); +} + bool NotificationRequest::IsPermitSystemGeneratedContextualActionButtons() const { return permitted_; @@ -387,7 +281,7 @@ uint32_t NotificationRequest::GetColor() const return color_; } -bool NotificationRequest::IsColorEnabled() +bool NotificationRequest::IsColorEnabled() const { if (!colorEnabled_) { return false; @@ -472,14 +366,14 @@ void NotificationRequest::SetGroupOverview(bool overView) groupOverview_ = overView; } -void NotificationRequest::SetGroupValue(const std::string &groupValue) +void NotificationRequest::SetGroupName(const std::string &groupName) { - groupValue_ = groupValue; + groupName_ = groupName; } -std::string NotificationRequest::GetGroupValue() const +std::string NotificationRequest::GetGroupName() const { - return groupValue_; + return groupName_; } bool NotificationRequest::IsOnlyLocal() const @@ -653,7 +547,7 @@ const std::shared_ptr NotificationRequest::GetPublicNotific std::string NotificationRequest::GetNotificationHashCode() const { - if (creatorBundleName_.empty() || (0 == creatorUid_) || ownerBundleName_.empty()) { + if (creatorBundleName_.empty() || (creatorUid_ == 0) || ownerBundleName_.empty()) { return ""; } @@ -711,48 +605,186 @@ std::string NotificationRequest::GetLabel() const return label_; } +void NotificationRequest::SetDistributed(bool distribute) +{ + distributedOptions_.SetDistributed(distribute); +} + +void NotificationRequest::SetDevicesSupportDisplay(const std::vector &devices) +{ + distributedOptions_.SetDevicesSupportDisplay(devices); +} + +void NotificationRequest::SetDevicesSupportOperate(const std::vector &devices) +{ + distributedOptions_.SetDevicesSupportOperate(devices); +} + +NotificationDistributedOptions NotificationRequest::GetNotificationDistributedOptions() const +{ + return distributedOptions_; +} + +void NotificationRequest::SetCreatorUserId(int32_t userId) +{ + creatorUserId_ = userId; +} + +int32_t NotificationRequest::GetCreatorUserId() const +{ + return creatorUserId_; +} + std::string NotificationRequest::Dump() { - return "NotificationRequest[ notificationId = " + std::to_string(notificationId_) + - ", slotType = " + std::to_string(static_cast(slotType_)) + - ", createTime = " + std::to_string(createTime_) + ", deliveryTime = " + std::to_string(deliveryTime_) + - ", autoDeletedTime = " + std::to_string(autoDeletedTime_) + ", settingsText = " + settingsText_ + - ", creatorBundleName = " + creatorBundleName_ + - ", creatorPid = " + std::to_string(static_cast(creatorPid_)) + - ", creatorUid = " + std::to_string(static_cast(creatorUid_)) + - ", ownerBundleName = " + ownerBundleName_ + ", groupValue = " + groupValue_ + - ", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ + - ", sortingKey = " + sortingKey_ + - ", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) + - ", color = " + std::to_string(color_) + ", badgeNumber = " + std::to_string(badgeNumber_) + - ", visiblenessType = " + std::to_string(static_cast(visiblenessType_)) + - ", progressValue = " + std::to_string(progressValue_) + ", progressMax = " + std::to_string(progressMax_) + - ", badgeStyle = " + std::to_string(static_cast(badgeStyle_)) + - ", classification = " + classification_ + - ", notificationContentType = " + std::to_string(static_cast(notificationContentType_)) + - ", showDeliveryTime = " + (showDeliveryTime_ ? "true" : "false") + - ", tapDismissed = " + (tapDismissed_ ? "true" : "false") + - ", colorEnabled = " + (colorEnabled_ ? "true" : "false") + - ", alertOneTime = " + (alertOneTime_ ? "true" : "false") + - ", showStopwatch = " + (showStopwatch_ ? "true" : "false") + - ", isCountdown = " + (isCountdown_ ? "true" : "false") + - ", inProgress = " + (inProgress_ ? "true" : "false") + - ", groupOverview = " + (groupOverview_ ? "true" : "false") + - ", progressIndeterminate = " + (progressIndeterminate_ ? "true" : "false") + - ", unremovable = " + (unremovable_ ? "true" : "false") + - ", floatingIcon = " + (floatingIcon_ ? "true" : "false") + - ", onlyLocal = " + (onlyLocal_ ? "true" : "false") + ", permitted = " + (permitted_ ? "true" : "false") + - ", context = " + (context_ ? "not null" : "null") + ", wantAgent = " + (wantAgent_ ? "not null" : "null") + - ", removalWantAgent = " + (removalWantAgent_ ? "not null" : "null") + - ", maxScreenWantAgent = " + (maxScreenWantAgent_ ? "not null" : "null") + - ", additionalParams = " + (additionalParams_ ? "not null" : "null") + - ", littleIcon = " + (littleIcon_ ? "not null" : "null") + - ", bigIcon = " + (bigIcon_ ? "not null" : "null") + - ", notificationContent = " + (notificationContent_ ? "not null" : "null") + - ", publicNotification = " + (publicNotification_ ? "not null" : "null") + - ", actionButtons = " + (!actionButtons_.empty() ? "not empty" : "empty") + - ", messageUsers = " + (!messageUsers_.empty() ? "not empty" : "empty") + - ", userInputHistory = " + (!userInputHistory_.empty() ? "not empty" : "empty") + " ]"; + return "NotificationRequest{ " + "notificationId = " + std::to_string(notificationId_) + + ", slotType = " + std::to_string(static_cast(slotType_)) + + ", createTime = " + std::to_string(createTime_) + ", deliveryTime = " + std::to_string(deliveryTime_) + + ", autoDeletedTime = " + std::to_string(autoDeletedTime_) + ", settingsText = " + settingsText_ + + ", creatorBundleName = " + creatorBundleName_ + + ", creatorPid = " + std::to_string(static_cast(creatorPid_)) + + ", creatorUid = " + std::to_string(static_cast(creatorUid_)) + + ", ownerBundleName = " + ownerBundleName_ + ", groupName = " + groupName_ + + ", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ + + ", sortingKey = " + sortingKey_ + + ", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) + + ", color = " + std::to_string(color_) + ", badgeNumber = " + std::to_string(badgeNumber_) + + ", visiblenessType = " + std::to_string(static_cast(visiblenessType_)) + + ", progressValue = " + std::to_string(progressValue_) + ", progressMax = " + std::to_string(progressMax_) + + ", badgeStyle = " + std::to_string(static_cast(badgeStyle_)) + + ", classification = " + classification_ + + ", notificationContentType = " + std::to_string(static_cast(notificationContentType_)) + + ", showDeliveryTime = " + (showDeliveryTime_ ? "true" : "false") + + ", tapDismissed = " + (tapDismissed_ ? "true" : "false") + + ", colorEnabled = " + (colorEnabled_ ? "true" : "false") + + ", alertOneTime = " + (alertOneTime_ ? "true" : "false") + + ", showStopwatch = " + (showStopwatch_ ? "true" : "false") + + ", isCountdown = " + (isCountdown_ ? "true" : "false") + + ", inProgress = " + (inProgress_ ? "true" : "false") + + ", groupOverview = " + (groupOverview_ ? "true" : "false") + + ", progressIndeterminate = " + (progressIndeterminate_ ? "true" : "false") + + ", unremovable = " + (unremovable_ ? "true" : "false") + + ", floatingIcon = " + (floatingIcon_ ? "true" : "false") + + ", onlyLocal = " + (onlyLocal_ ? "true" : "false") + ", permitted = " + (permitted_ ? "true" : "false") + + ", removalWantAgent = " + (removalWantAgent_ ? "not null" : "null") + + ", maxScreenWantAgent = " + (maxScreenWantAgent_ ? "not null" : "null") + + ", additionalParams = " + (additionalParams_ ? "not null" : "null") + + ", littleIcon = " + (littleIcon_ ? "not null" : "null") + + ", bigIcon = " + (bigIcon_ ? "not null" : "null") + + ", notificationContent = " + (notificationContent_ ? notificationContent_->Dump() : "null") + + ", publicNotification = " + (publicNotification_ ? "not null" : "null") + + ", notificationTemplate = " + (notificationTemplate_ ? "not null" : "null") + + ", actionButtons = " + (!actionButtons_.empty() ? actionButtons_.at(0)->Dump() : "empty") + + ", messageUsers = " + (!messageUsers_.empty() ? messageUsers_.at(0)->Dump() : "empty") + + ", userInputHistory = " + (!userInputHistory_.empty() ? userInputHistory_.at(0) : "empty") + + ", distributedOptions = " + distributedOptions_.Dump() + + ", notificationFlags = " + (notificationFlags_ ? "not null" : "null") + + " }"; +} + +bool NotificationRequest::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["version"] = 1; + + jsonObject["id"] = notificationId_; + jsonObject["color"] = color_; + jsonObject["deliveryTime"] = deliveryTime_; + jsonObject["autoDeletedTime"] = autoDeletedTime_; + + jsonObject["creatorBundleName"] = creatorBundleName_; + jsonObject["ownerBundleName"] = ownerBundleName_; + jsonObject["groupName"] = groupName_; + jsonObject["label"] = label_; + jsonObject["classification"] = classification_; + + jsonObject["slotType"] = static_cast(slotType_); + jsonObject["badgeIconStyle"] = static_cast(badgeStyle_); + + jsonObject["showDeliveryTime"] = showDeliveryTime_; + jsonObject["tapDismissed"] = tapDismissed_; + jsonObject["colorEnabled"] = colorEnabled_; + jsonObject["isOngoing"] = inProgress_; + jsonObject["isAlertOnce"] = alertOneTime_; + jsonObject["isStopwatch"] = showStopwatch_; + jsonObject["isCountdown"] = isCountdown_; + jsonObject["isUnremovable"] = unremovable_; + jsonObject["isFloatingIcon"] = floatingIcon_; + + if (!ConvertObjectsToJson(jsonObject)) { + ANS_LOGE("Cannot convert objects to JSON"); + return false; + } + + return true; +} + +NotificationRequest *NotificationRequest::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pRequest = new (std::nothrow) NotificationRequest(); + if (pRequest == nullptr) { + ANS_LOGE("Failed to create request instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("version") != jsonEnd) { + jsonObject.at("version").get(); + } + + ConvertJsonToNum(pRequest, jsonObject); + + ConvertJsonToString(pRequest, jsonObject); + + ConvertJsonToEnum(pRequest, jsonObject); + + ConvertJsonToBool(pRequest, jsonObject); + + if (jsonObject.find("wantAgent") != jsonEnd) { + auto wantAgentValue = jsonObject.at("wantAgent").get(); + pRequest->wantAgent_ = WantAgent::WantAgentHelper::FromString(wantAgentValue); + } + + if (!ConvertJsonToNotificationContent(pRequest, jsonObject)) { + delete pRequest; + pRequest = nullptr; + return nullptr; + } + + if (!ConvertJsonToNotificationActionButton(pRequest, jsonObject)) { + delete pRequest; + pRequest = nullptr; + return nullptr; + } + + if (jsonObject.find("extraInfo") != jsonEnd) { + auto extraInfoStr = jsonObject.at("extraInfo").get(); + if (!extraInfoStr.empty()) { + AAFwk::WantParams params = AAFwk::WantParamWrapper::ParseWantParams(extraInfoStr); + pRequest->additionalParams_ = std::make_shared(params); + } + } + + ConvertJsonToPixelMap(pRequest, jsonObject); + + if (!ConvertJsonToNotificationDistributedOptions(pRequest, jsonObject)) { + delete pRequest; + pRequest = nullptr; + return nullptr; + } + + if (!ConvertJsonToNotificationFlags(pRequest, jsonObject)) { + delete pRequest; + pRequest = nullptr; + return nullptr; + } + + return pRequest; } bool NotificationRequest::Marshalling(Parcel &parcel) const @@ -824,8 +856,8 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteString(groupValue_)) { - ANS_LOGE("Failed to write group value"); + if (!parcel.WriteString(groupName_)) { + ANS_LOGE("Failed to write group name"); return false; } @@ -1084,13 +1116,44 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const return false; } + if (!parcel.WriteParcelable(&distributedOptions_)) { + ANS_LOGE("Failed to write distributedOptions"); + return false; + } + + valid = notificationTemplate_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether publicNotification is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(notificationTemplate_.get())) { + ANS_LOGE("Failed to write notificationTemplate"); + return false; + } + } + + valid = notificationFlags_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write flags for the notification"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(notificationFlags_.get())) { + ANS_LOGE("Failed to write notification flags"); + return false; + } + } + return true; } NotificationRequest *NotificationRequest::Unmarshalling(Parcel &parcel) { - auto objptr = new NotificationRequest(); - if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + auto objptr = new (std::nothrow) NotificationRequest(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -1127,8 +1190,8 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) return false; } - if (!parcel.ReadString(groupValue_)) { - ANS_LOGE("Failed to read group value"); + if (!parcel.ReadString(groupName_)) { + ANS_LOGE("Failed to read group name"); return false; } @@ -1254,7 +1317,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) auto vsize = parcel.ReadInt32(); for (auto it = 0; it < vsize; ++it) { auto member = parcel.ReadParcelable(); - if (nullptr == member) { + if (member == nullptr) { ANS_LOGE("Failed to read actionButton"); return false; } @@ -1265,7 +1328,7 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) vsize = parcel.ReadInt32(); for (auto it = 0; it < vsize; ++it) { auto member = parcel.ReadParcelable(); - if (nullptr == member) { + if (member == nullptr) { ANS_LOGE("Failed to read messageUser"); return false; } @@ -1278,6 +1341,31 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) return false; } + auto pOpt = parcel.ReadParcelable(); + if (pOpt == nullptr) { + ANS_LOGE("Failed to read distributedOptions"); + return false; + } + distributedOptions_ = *pOpt; + + valid = parcel.ReadBool(); + if (valid) { + notificationTemplate_ = std::shared_ptr(parcel.ReadParcelable()); + if (!notificationTemplate_) { + ANS_LOGE("Failed to read notificationTemplate"); + return false; + } + } + + valid = parcel.ReadBool(); + if (valid) { + notificationFlags_ = std::shared_ptr(parcel.ReadParcelable()); + if (!notificationFlags_) { + ANS_LOGE("Failed to read notificationFlags"); + return false; + } + } + return true; } @@ -1289,5 +1377,393 @@ int64_t NotificationRequest::GetNowSysTime() int64_t duration = value.count(); return duration; } + +void NotificationRequest::SetTemplate(const std::shared_ptr &templ) +{ + notificationTemplate_ = templ; +} + +std::shared_ptr NotificationRequest::GetTemplate() const +{ + return notificationTemplate_; +} + +void NotificationRequest::SetFlags(const std::shared_ptr &flags) +{ + notificationFlags_ = flags; +} + +std::shared_ptr NotificationRequest::GetFlags() const +{ + return notificationFlags_; +} + +void NotificationRequest::CopyBase(const NotificationRequest &other) +{ + this->notificationId_ = other.notificationId_; + this->color_ = other.color_; + this->badgeNumber_ = other.badgeNumber_; + this->progressValue_ = other.progressValue_; + this->progressMax_ = other.progressMax_; + this->createTime_ = other.createTime_; + this->deliveryTime_ = other.deliveryTime_; + this->autoDeletedTime_ = other.autoDeletedTime_; + + this->creatorPid_ = other.creatorPid_; + this->creatorUid_ = other.creatorUid_; + + this->slotType_ = other.slotType_; + this->settingsText_ = other.settingsText_; + this->creatorBundleName_ = other.creatorBundleName_; + this->ownerBundleName_ = other.ownerBundleName_; + this->groupName_ = other.groupName_; + this->statusBarText_ = other.statusBarText_; + this->label_ = other.label_; + this->shortcutId_ = other.shortcutId_; + this->sortingKey_ = other.sortingKey_; + this->classification_ = other.classification_; + + this->groupAlertType_ = other.groupAlertType_; + this->visiblenessType_ = other.visiblenessType_; + this->badgeStyle_ = other.badgeStyle_; + this->notificationContentType_ = other.notificationContentType_; +} + +void NotificationRequest::CopyOther(const NotificationRequest &other) +{ + this->showDeliveryTime_ = other.showDeliveryTime_; + this->tapDismissed_ = other.tapDismissed_; + this->colorEnabled_ = other.colorEnabled_; + this->alertOneTime_ = other.alertOneTime_; + this->showStopwatch_ = other.showStopwatch_; + this->isCountdown_ = other.isCountdown_; + this->inProgress_ = other.inProgress_; + this->groupOverview_ = other.groupOverview_; + this->progressIndeterminate_ = other.progressIndeterminate_; + this->unremovable_ = other.unremovable_; + this->floatingIcon_ = other.floatingIcon_; + this->onlyLocal_ = other.onlyLocal_; + this->permitted_ = other.permitted_; + + this->wantAgent_ = other.wantAgent_; + this->removalWantAgent_ = other.removalWantAgent_; + this->maxScreenWantAgent_ = other.maxScreenWantAgent_; + this->additionalParams_ = other.additionalParams_; + this->littleIcon_ = other.littleIcon_; + this->bigIcon_ = other.bigIcon_; + this->notificationContent_ = other.notificationContent_; + this->publicNotification_ = other.publicNotification_; + + this->actionButtons_ = other.actionButtons_; + this->messageUsers_ = other.messageUsers_; + this->userInputHistory_ = other.userInputHistory_; + + this->distributedOptions_ = other.distributedOptions_; + + this->notificationTemplate_ = other.notificationTemplate_; + this->notificationFlags_ = other.notificationFlags_; +} + +bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const +{ + jsonObject["wantAgent"] = wantAgent_ ? WantAgent::WantAgentHelper::ToString(wantAgent_) : ""; + + nlohmann::json contentObj; + if (notificationContent_) { + if (!NotificationJsonConverter::ConvertToJosn(notificationContent_.get(), contentObj)) { + ANS_LOGE("Cannot convert notificationContent to JSON"); + return false; + } + } + jsonObject["content"] = contentObj; + + nlohmann::json buttonsArr = nlohmann::json::array(); + for (auto &btn : actionButtons_) { + if (!btn) { + continue; + } + + nlohmann::json btnObj; + if (!NotificationJsonConverter::ConvertToJosn(btn.get(), btnObj)) { + ANS_LOGE("Cannot convert actionButton to JSON"); + return false; + } + + buttonsArr.emplace_back(btnObj); + } + jsonObject["actionButtons"] = buttonsArr; + + std::string extraInfoStr; + if (additionalParams_) { + AAFwk::WantParamWrapper wWrapper(*additionalParams_); + extraInfoStr = wWrapper.ToString(); + } + jsonObject["extraInfo"] = extraInfoStr; + + jsonObject["smallIcon"] = AnsImageUtil::PackImage(littleIcon_); + jsonObject["largeIcon"] = AnsImageUtil::PackImage(bigIcon_); + + nlohmann::json optObj; + if (!NotificationJsonConverter::ConvertToJosn(&distributedOptions_, optObj)) { + ANS_LOGE("Cannot convert distributedOptions to JSON"); + return false; + } + jsonObject["distributedOptions"] = optObj; + + nlohmann::json flagsObj; + if (!NotificationJsonConverter::ConvertToJosn(notificationFlags_.get(), flagsObj)) { + ANS_LOGE("Cannot convert notificationFlags to JSON"); + return false; + } + jsonObject["notificationFlags"] = flagsObj; + + return true; +} + +void NotificationRequest::ConvertJsonToNum(NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("id") != jsonEnd) { + target->notificationId_ = jsonObject.at("id").get(); + } + + if (jsonObject.find("color") != jsonEnd) { + target->color_ = jsonObject.at("color").get(); + } + + if (jsonObject.find("deliveryTime") != jsonEnd) { + target->deliveryTime_ = jsonObject.at("deliveryTime").get(); + } + + if (jsonObject.find("autoDeletedTime") != jsonEnd) { + target->autoDeletedTime_ = jsonObject.at("autoDeletedTime").get(); + } +} + +void NotificationRequest::ConvertJsonToString(NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("creatorBundleName") != jsonEnd) { + target->creatorBundleName_ = jsonObject.at("creatorBundleName").get(); + } + + if (jsonObject.find("ownerBundleName") != jsonEnd) { + target->ownerBundleName_ = jsonObject.at("ownerBundleName").get(); + } + + if (jsonObject.find("groupName") != jsonEnd) { + target->groupName_ = jsonObject.at("groupName").get(); + } + + if (jsonObject.find("label") != jsonEnd) { + target->label_ = jsonObject.at("label").get(); + } + + if (jsonObject.find("classification") != jsonEnd) { + target->classification_ = jsonObject.at("classification").get(); + } +} + +void NotificationRequest::ConvertJsonToEnum(NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("slotType") != jsonEnd) { + auto slotTypeValue = jsonObject.at("slotType").get(); + target->slotType_ = static_cast(slotTypeValue); + } + + if (jsonObject.find("badgeIconStyle") != jsonEnd) { + auto badgeStyleValue = jsonObject.at("badgeIconStyle").get(); + target->badgeStyle_ = static_cast(badgeStyleValue); + } +} + +void NotificationRequest::ConvertJsonToBool(NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("showDeliveryTime") != jsonEnd) { + target->showDeliveryTime_ = jsonObject.at("showDeliveryTime").get(); + } + + if (jsonObject.find("tapDismissed") != jsonEnd) { + target->tapDismissed_ = jsonObject.at("tapDismissed").get(); + } + + if (jsonObject.find("colorEnabled") != jsonEnd) { + target->colorEnabled_ = jsonObject.at("colorEnabled").get(); + } + + if (jsonObject.find("isOngoing") != jsonEnd) { + target->inProgress_ = jsonObject.at("isOngoing").get(); + } + + if (jsonObject.find("isAlertOnce") != jsonEnd) { + target->alertOneTime_ = jsonObject.at("isAlertOnce").get(); + } + + if (jsonObject.find("isStopwatch") != jsonEnd) { + target->showStopwatch_ = jsonObject.at("isStopwatch").get(); + } + + if (jsonObject.find("isCountdown") != jsonEnd) { + target->isCountdown_ = jsonObject.at("isCountdown").get(); + } + + if (jsonObject.find("isUnremovable") != jsonEnd) { + target->unremovable_ = jsonObject.at("isUnremovable").get(); + } + + if (jsonObject.find("isFloatingIcon") != jsonEnd) { + target->floatingIcon_ = jsonObject.at("isFloatingIcon").get(); + } +} + +void NotificationRequest::ConvertJsonToPixelMap(NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("smallIcon") != jsonEnd) { + auto littleIconStr = jsonObject.at("smallIcon").get(); + target->littleIcon_ = AnsImageUtil::UnPackImage(littleIconStr); + } + + if (jsonObject.find("largeIcon") != jsonEnd) { + auto bigIconStr = jsonObject.at("largeIcon").get(); + target->bigIcon_ = AnsImageUtil::UnPackImage(bigIconStr); + } +} + +bool NotificationRequest::ConvertJsonToNotificationContent( + NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return false; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("content") != jsonEnd) { + auto contentObj = jsonObject.at("content"); + if (!contentObj.is_null()) { + auto pContent = NotificationJsonConverter::ConvertFromJosn(contentObj); + if (pContent == nullptr) { + ANS_LOGE("Failed to parse notification content!"); + return false; + } + + target->notificationContent_ = std::shared_ptr(pContent); + } + } + + return true; +} + +bool NotificationRequest::ConvertJsonToNotificationActionButton( + NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return false; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("actionButtons") != jsonEnd) { + auto buttonArr = jsonObject.at("actionButtons"); + for (auto &btnObj : buttonArr) { + auto pBtn = NotificationJsonConverter::ConvertFromJosn(btnObj); + if (pBtn == nullptr) { + ANS_LOGE("Failed to parse actionButton!"); + return false; + } + + target->actionButtons_.emplace_back(pBtn); + } + } + + return true; +} + +bool NotificationRequest::ConvertJsonToNotificationDistributedOptions( + NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return false; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("distributedOptions") != jsonEnd) { + auto optObj = jsonObject.at("distributedOptions"); + if (!optObj.is_null()) { + auto pOpt = NotificationJsonConverter::ConvertFromJosn(optObj); + if (pOpt == nullptr) { + ANS_LOGE("Failed to parse distributedOptions!"); + return false; + } + + target->distributedOptions_ = *pOpt; + } + } + + return true; +} + +bool NotificationRequest::ConvertJsonToNotificationFlags( + NotificationRequest *target, const nlohmann::json &jsonObject) +{ + if (target == nullptr) { + ANS_LOGE("Invalid input parameter"); + return false; + } + + const auto &jsonEnd = jsonObject.cend(); + + if (jsonObject.find("notificationFlags") != jsonEnd) { + auto flagsObj = jsonObject.at("notificationFlags"); + if (!flagsObj.is_null()) { + auto pFlags = NotificationJsonConverter::ConvertFromJosn(flagsObj); + if (pFlags == nullptr) { + ANS_LOGE("Failed to parse notificationFlags!"); + return false; + } + + target->notificationFlags_ = std::shared_ptr(pFlags); + } + } + + return true; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 5c57480054f664c4c27eed551377b24e1cd60a7e..04f4c9c5afac95d7e420395ab9bdedc368888549 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -14,11 +14,11 @@ */ #include "notification_slot.h" +#include "ans_const_define.h" #include "ans_log_wrapper.h" namespace OHOS { namespace Notification { - const int MAX_TEXT_LENGTH = 1000; NotificationSlot::NotificationSlot(NotificationConstant::SlotType type) : sound_("") @@ -97,14 +97,16 @@ void NotificationSlot::SetType(NotificationConstant::SlotType type) id_ = "SOCIAL_COMMUNICATION"; SetName("SOCIAL_COMMUNICATION"); SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); - SetEnableVibration(true); + SetSound(DEFAULT_NOTIFICATION_SOUND); + SetVibrationStyle(DEFAULT_NOTIFICATION_VIBRATION); SetLevel(LEVEL_HIGH); break; case NotificationConstant::SlotType::SERVICE_REMINDER: id_ = "SERVICE_REMINDER"; SetName("SERVICE_REMINDER"); SetLockscreenVisibleness(NotificationConstant::VisiblenessType::PUBLIC); - SetEnableVibration(true); + SetSound(DEFAULT_NOTIFICATION_SOUND); + SetVibrationStyle(DEFAULT_NOTIFICATION_VIBRATION); SetLevel(LEVEL_DEFAULT); break; case NotificationConstant::SlotType::CONTENT_INFORMATION: @@ -200,19 +202,22 @@ void NotificationSlot::EnableBadge(bool isShowBadge) std::string NotificationSlot::Dump() const { - return "NotificationSlot[ id = " + id_ + - ", name = " + name_ + - ", description = " + description_ + - ", type = " + std::to_string(static_cast(type_)) + - ", level = " + std::to_string(static_cast(level_)) + - ", isBypassDnd = " + (isBypassDnd_ ? "true" : "false") + - ", visibleness = " + std::to_string(static_cast(lockScreenVisibleness_)) + - ", sound = " + sound_.ToString() + - ", isLightEnabled = " + (isLightEnabled_ ? "true" : "false") + - ", lightColor = " + std::to_string(lightColor_) + - ", isVibrate = " + (isVibrationEnabled_ ? "true" : "false") + - ", vibration = " + MergeVectorToString(vibrationValues_) + - ", isShowBadge = " + (isShowBadge_ ? "true" : "false") + ", groupId = " + groupId_ + "]"; + return "NotificationSlot{ " + "id = " + id_ + + ", name = " + name_ + + ", description = " + description_ + + ", type = " + std::to_string(static_cast(type_)) + + ", level = " + std::to_string(static_cast(level_)) + + ", isBypassDnd = " + (isBypassDnd_ ? "true" : "false") + + ", visibleness = " + std::to_string(static_cast(lockScreenVisibleness_)) + + ", sound = " + sound_.ToString() + + ", isLightEnabled = " + (isLightEnabled_ ? "true" : "false") + + ", lightColor = " + std::to_string(lightColor_) + + ", isVibrate = " + (isVibrationEnabled_ ? "true" : "false") + + ", vibration = " + MergeVectorToString(vibrationValues_) + + ", isShowBadge = " + (isShowBadge_ ? "true" : "false") + + ", groupId = " + groupId_ + + " }"; } bool NotificationSlot::Marshalling(Parcel &parcel) const @@ -332,7 +337,7 @@ bool NotificationSlot::ReadFromParcel(Parcel &parcel) NotificationSlot *NotificationSlot::Unmarshalling(Parcel &parcel) { - NotificationSlot *notificationSlot = new NotificationSlot(NotificationConstant::SlotType::CUSTOM); + NotificationSlot *notificationSlot = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::CUSTOM); if (notificationSlot && !notificationSlot->ReadFromParcel(parcel)) { delete notificationSlot; diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp index 5f06ffc53694269c0addada01612536ad1b5d191..c870357e0e3b10edaddb281a343787f1a265e243 100644 --- a/frameworks/ans/native/src/notification_slot_group.cpp +++ b/frameworks/ans/native/src/notification_slot_group.cpp @@ -78,11 +78,13 @@ std::string NotificationSlotGroup::Dump() const contents += ","; } } - return "NotificationSlotGroup[id = " + id_ + - ", name = " + name_ + - ", description = " + description_ + - ", slots = " + contents + - ", isDisabled = " + (isDisabled_ ? "true" : "false") + "]"; + return "NotificationSlotGroup{ " + "id = " + id_ + + ", name = " + name_ + + ", description = " + description_ + + ", slots = " + contents + + ", isDisabled = " + (isDisabled_ ? "true" : "false") + + " }"; } bool NotificationSlotGroup::Marshalling(Parcel &parcel) const @@ -137,7 +139,7 @@ bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel) if (size) { for (int32_t i = 0; i < size; ++i) { auto slot = parcel.ReadParcelable(); - if (nullptr == slot) { + if (slot == nullptr) { ANS_LOGE("Failed to read slot"); return false; } @@ -150,7 +152,7 @@ bool NotificationSlotGroup::ReadFromParcel(Parcel &parcel) NotificationSlotGroup *NotificationSlotGroup::Unmarshalling(Parcel &parcel) { - NotificationSlotGroup *notificationSlotGroup = new NotificationSlotGroup(); + NotificationSlotGroup *notificationSlotGroup = new (std::nothrow) NotificationSlotGroup(); if (notificationSlotGroup && !notificationSlotGroup->ReadFromParcel(parcel)) { delete notificationSlotGroup; diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 0ff27d780b079bb00ea7cfa9404d36a7b35d8109..575141dbfcc0bb35b50f9c2811763e30f8cbcfef 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -39,6 +39,10 @@ NotificationSorting::NotificationSorting(const NotificationSorting &sorting) void NotificationSorting::SetSlot(const sptr &slot) { + if (slot == nullptr) { + slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); + return; + } slot_ = slot; } @@ -49,18 +53,16 @@ void NotificationSorting::SetGroupKeyOverride(const std::string &groupKeyOverrid std::string NotificationSorting::Dump() const { - std::string contents {""}; - if (slot_ != nullptr) { - contents = slot_->Dump(); - } else { - contents = "nullptr"; - } - return "NotificationSorting[key =" + key_ + ", ranking =" + std::to_string(ranking_) + - ", importance =" + std::to_string(importance_) + - ", visiblenessOverride =" + std::to_string(visiblenessOverride_) + - ", isDisplayBadge =" + (isDisplayBadge_ ? "true" : "false") + - ", isHiddenNotification =" + (isHiddenNotification_ ? "true" : "false") + - ", groupKeyOverride =" + groupKeyOverride_ + ", slot_ =" + contents + "]"; + return "NotificationSorting{ " + "key = " + key_ + + ", ranking = " + std::to_string(ranking_) + + ", importance = " + std::to_string(importance_) + + ", visiblenessOverride = " + std::to_string(visiblenessOverride_) + + ", isDisplayBadge = " + (isDisplayBadge_ ? "true" : "false") + + ", isHiddenNotification = " + (isHiddenNotification_ ? "true" : "false") + + ", groupKeyOverride = " + groupKeyOverride_ + + ", slot = " + (slot_ != nullptr ? slot_->Dump() : "nullptr") + + " }"; } bool NotificationSorting::Marshalling(Parcel &parcel) const @@ -139,7 +141,7 @@ bool NotificationSorting::ReadFromParcel(Parcel &parcel) NotificationSorting *NotificationSorting::Unmarshalling(Parcel &parcel) { - NotificationSorting *sorting = new NotificationSorting(); + NotificationSorting *sorting = new (std::nothrow) NotificationSorting(); if (sorting && !sorting->ReadFromParcel(parcel)) { delete sorting; sorting = nullptr; diff --git a/frameworks/ans/native/src/notification_sorting_map.cpp b/frameworks/ans/native/src/notification_sorting_map.cpp index 8e32c8bfe406d54ab29d6fdebf38f98b5d8a6888..2bd73d2f504f4b270616547b4da9d50490ba497a 100644 --- a/frameworks/ans/native/src/notification_sorting_map.cpp +++ b/frameworks/ans/native/src/notification_sorting_map.cpp @@ -93,24 +93,20 @@ NotificationSortingMap *NotificationSortingMap::Unmarshalling(Parcel &parcel) } } - NotificationSortingMap *sortingMap = new NotificationSortingMap(sortings); + NotificationSortingMap *sortingMap = new (std::nothrow) NotificationSortingMap(sortings); return sortingMap; } + std::string NotificationSortingMap::Dump() const { - int keyNum = 0; - std::string separator; - std::string keys = " sortedkey = "; - for (auto item : sortedKey_) { - if (keyNum == 0) { - separator = ""; - } else { - separator = ", "; - } - keys = keys + separator + item; - keyNum++; + std::string keys = ""; + for (auto key : sortedKey_) { + keys += key; + keys += ", "; } - return "NotificationSortingMap[" + keys + "]"; + return "NotificationSortingMap{ " + "sortedkey = [" + keys + "]" + " }"; } } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp index 542404270259238e4daaaec9fcaa56874dd20ec9..50cd3a934de9c142bb65bd57214775326a1263d9 100644 --- a/frameworks/ans/native/src/notification_subscribe_info.cpp +++ b/frameworks/ans/native/src/notification_subscribe_info.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace Notification { - NotificationSubscribeInfo::NotificationSubscribeInfo() {} @@ -46,6 +45,16 @@ std::vector NotificationSubscribeInfo::GetAppNames() const return appNames_; } +void NotificationSubscribeInfo::AddAppUserId(const int userId) +{ + userId_ = userId; +} + +int32_t NotificationSubscribeInfo::GetAppUserId() const +{ + return userId_; +} + bool NotificationSubscribeInfo::Marshalling(Parcel &parcel) const { // write appNames_ @@ -58,7 +67,7 @@ bool NotificationSubscribeInfo::Marshalling(Parcel &parcel) const NotificationSubscribeInfo *NotificationSubscribeInfo::Unmarshalling(Parcel &parcel) { - NotificationSubscribeInfo *info = new NotificationSubscribeInfo(); + NotificationSubscribeInfo *info = new (std::nothrow) NotificationSubscribeInfo(); if (info && !info->ReadFromParcel(parcel)) { delete info; info = nullptr; @@ -75,8 +84,14 @@ bool NotificationSubscribeInfo::ReadFromParcel(Parcel &parcel) std::string NotificationSubscribeInfo::Dump() { - return "Dump"; + std::string appNames = ""; + for (auto name : appNames_) { + appNames += name; + appNames += ", "; + } + return "NotificationSubscribeInfo{ " + "appNames = [" + appNames + "]" + + " }"; } - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index 4220ea0ec500180a2ec75ba27dd12ed3f56cccc9..291bc9ac75f5d2d7c86af8fa8254fb1baf452d13 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -20,10 +20,9 @@ namespace OHOS { namespace Notification { - NotificationSubscriber::NotificationSubscriber() { - impl_ = new SubscriberImpl(*this); + impl_ = new (std::nothrow) SubscriberImpl(*this); }; NotificationSubscriber::~NotificationSubscriber() @@ -36,25 +35,25 @@ const sptr NotificationSubscriber::GetIm NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &subscriber) : subscriber_(subscriber) { - recipient_ = new DeathRecipient(*this); + recipient_ = new (std::nothrow) DeathRecipient(*this); }; -void NotificationSubscriber::SubscriberImpl::OnSubscribeResult(NotificationConstant::SubscribeResult result) +void NotificationSubscriber::SubscriberImpl::OnConnected() { - if (result == 0 && GetAnsManagerProxy()) { + if (GetAnsManagerProxy()) { proxy_->AsObject()->AddDeathRecipient(recipient_); ANS_LOGD("%s, Add death recipient.", __func__); } - subscriber_.OnSubscribeResult(result); + subscriber_.OnConnected(); } -void NotificationSubscriber::SubscriberImpl::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +void NotificationSubscriber::SubscriberImpl::OnDisconnected() { - if (result == 0 && GetAnsManagerProxy()) { + if (GetAnsManagerProxy()) { proxy_->AsObject()->RemoveDeathRecipient(recipient_); ANS_LOGD("%s, Remove death recipient.", __func__); } - subscriber_.OnUnsubscribeResult(result); + subscriber_.OnDisconnected(); } void NotificationSubscriber::SubscriberImpl::OnConsumed(const sptr ¬ification) @@ -87,9 +86,9 @@ void NotificationSubscriber::SubscriberImpl::OnUpdated(const sptr(*notificationMap)); } -void NotificationSubscriber::SubscriberImpl::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +void NotificationSubscriber::SubscriberImpl::OnDoNotDisturbDateChange(const sptr &date) { - subscriber_.OnDisturbModeChanged(mode); + subscriber_.OnDoNotDisturbDateChange(std::make_shared(*date)); } bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy() @@ -110,7 +109,7 @@ bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy() } proxy_ = iface_cast(remoteObject); - if ((nullptr == proxy_) || (nullptr == proxy_->AsObject())) { + if ((proxy_ == nullptr) || (proxy_->AsObject() == nullptr)) { return false; } } @@ -120,15 +119,14 @@ bool NotificationSubscriber::SubscriberImpl::GetAnsManagerProxy() } NotificationSubscriber::SubscriberImpl::DeathRecipient::DeathRecipient(SubscriberImpl &subscriberImpl) - : subscriberImpl_(subscriberImpl){}; + : subscriberImpl_(subscriberImpl) {}; -NotificationSubscriber::SubscriberImpl::DeathRecipient::~DeathRecipient(){}; +NotificationSubscriber::SubscriberImpl::DeathRecipient::~DeathRecipient() {}; void NotificationSubscriber::SubscriberImpl::DeathRecipient::OnRemoteDied(const wptr &object) { subscriberImpl_.proxy_ = nullptr; subscriberImpl_.subscriber_.OnDied(); } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_template.cpp b/frameworks/ans/native/src/notification_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..894bd0e34403a863a78466ab6ffedaa42d085dc4 --- /dev/null +++ b/frameworks/ans/native/src/notification_template.cpp @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "notification_template.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +void NotificationTemplate::SetTemplateName(const std::string &name) +{ + templateName_ = name; +} + +std::string NotificationTemplate::GetTemplateName() const +{ + return templateName_; +} + +void NotificationTemplate::SetTemplateData(const std::shared_ptr &data) +{ + templateData_ = data; +} + +std::shared_ptr NotificationTemplate::GetTemplateData() const +{ + return templateData_; +} + +std::string NotificationTemplate::Dump() +{ + return "templateName = " + templateName_ + + ", templateData = " + (templateData_ ? "not null" : "null"); +} + +bool NotificationTemplate::Marshalling(Parcel &parcel) const +{ + if (!parcel.WriteString(templateName_)) { + ANS_LOGE("Failed to write text"); + return false; + } + + bool valid = templateData_ ? true : false; + if (!parcel.WriteBool(valid)) { + ANS_LOGE("Failed to write the flag which indicate whether templateData is null"); + return false; + } + + if (valid) { + if (!parcel.WriteParcelable(templateData_.get())) { + ANS_LOGE("Failed to write templateData"); + return false; + } + } + + return true; +} + +NotificationTemplate *NotificationTemplate::Unmarshalling(Parcel &parcel) +{ + auto templ = new NotificationTemplate(); + if ((templ != nullptr) && !templ->ReadFromParcel(parcel)) { + delete templ; + templ = nullptr; + } + + return templ; +} + +bool NotificationTemplate::ReadFromParcel(Parcel &parcel) +{ + if (!parcel.ReadString(templateName_)) { + ANS_LOGE("Failed to read template name"); + return false; + } + + bool valid = parcel.ReadBool(); + if (valid) { + templateData_ = std::shared_ptr(parcel.ReadParcelable()); + if (!templateData_) { + ANS_LOGE("Failed to read template data"); + return false; + } + } + + return true; +} +} // namespace Notification +} // namespace OHOS diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index 0115c3ba4c5d7adc8128dc664ed24807d1fa498c..337eeb50cdd3e8f5d4c2cf6057604474984a85ca 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -15,8 +15,8 @@ #include "notification_user_input.h" -#include #include "ans_log_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -33,10 +33,10 @@ NotificationConstant::InputsSource NotificationUserInput::GetInputsSource(const } void NotificationUserInput::AddInputsToWant(const std::vector> &userInputs, - AAFwk::Want &want, const AppExecFwk::PacMap &pacMap) + AAFwk::Want &want, const AAFwk::WantParams &additional) {} -std::shared_ptr NotificationUserInput::GetInputsFromWant(const AAFwk::Want &want) +std::shared_ptr NotificationUserInput::GetInputsFromWant(const AAFwk::Want &want) { return {}; } @@ -69,7 +69,7 @@ std::shared_ptr NotificationUserInput::Create(const std:: std::shared_ptr NotificationUserInput::Create(const std::string &inputKey, const std::string &tag, const std::vector &options, bool permitFreeFormInput, - const std::set &permitMimeTypes, const std::shared_ptr &pacMap, + const std::set &permitMimeTypes, const std::shared_ptr &additional, NotificationConstant::InputEditType editType) { if (inputKey.empty()) { @@ -89,13 +89,13 @@ std::shared_ptr NotificationUserInput::Create(const std:: } } - auto realPacMap = pacMap; - if (!realPacMap) { - realPacMap = std::make_shared(); + auto realAdditional = additional; + if (!realAdditional) { + realAdditional = std::make_shared(); } auto pUserInput = new (std::nothrow) - NotificationUserInput(inputKey, tag, options, permitFreeFormInput, permitMimeTypes, realPacMap, editType); + NotificationUserInput(inputKey, tag, options, permitFreeFormInput, permitMimeTypes, realAdditional, editType); if (pUserInput == nullptr) { ANS_LOGE("create NotificationUserInput object failed"); return {}; @@ -105,18 +105,18 @@ std::shared_ptr NotificationUserInput::Create(const std:: } NotificationUserInput::NotificationUserInput(const std::string &inputKey) - : inputKey_(inputKey), pacMap_(std::make_shared()) + : inputKey_(inputKey), additionalData_(std::make_shared()) {} NotificationUserInput::NotificationUserInput(const std::string &inputKey, const std::string &tag, const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, - const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType) + const std::shared_ptr &additional, NotificationConstant::InputEditType editType) : inputKey_(inputKey), tag_(tag), options_(options), permitFreeFormInput_(permitFreeFormInput), permitMimeTypes_(permitMimeTypes), - pacMap_(pacMap), + additionalData_(additional), editType_(editType) {} @@ -125,14 +125,16 @@ std::string NotificationUserInput::GetInputKey() const return inputKey_; } -void NotificationUserInput::AddAdditionalData(AppExecFwk::PacMap &pacMap) +void NotificationUserInput::AddAdditionalData(AAFwk::WantParams &additional) { - pacMap_->PutAll(pacMap); + if (additionalData_) { + *additionalData_ = additional; + } } -const std::shared_ptr NotificationUserInput::GetAdditionalData() const +const std::shared_ptr NotificationUserInput::GetAdditionalData() const { - return pacMap_; + return additionalData_; } void NotificationUserInput::SetEditType(NotificationConstant::InputEditType inputEditType) @@ -216,11 +218,82 @@ std::string NotificationUserInput::Dump() permitMimeTypes.pop_back(); permitMimeTypes.pop_back(); - return "NotificationUserInput[ inputKey = " + inputKey_ + " tag = " + tag_ + - "options = [ " + options + " ]" + - " permitFreeFormInput = " + (permitFreeFormInput_ ? "true" : "false") + - " permitMimeTypes = [ " + permitMimeTypes + " ]" + - " editType = " + std::to_string(static_cast(editType_)) + " ]"; + return "NotificationUserInput{ " + "inputKey = " + inputKey_ + + ", tag = " + tag_ + + ", options = [" + options + "]" + + ", permitFreeFormInput = " + (permitFreeFormInput_ ? "true" : "false") + + ", permitMimeTypes = [" + permitMimeTypes + "]" + + ", editType = " + std::to_string(static_cast(editType_)) + + " }"; +} + +bool NotificationUserInput::ToJson(nlohmann::json &jsonObject) const +{ + jsonObject["inputKey"] = inputKey_; + jsonObject["tag"] = tag_; + jsonObject["options"] = nlohmann::json(options_); + jsonObject["permitFreeFormInput"] = permitFreeFormInput_; + jsonObject["permitMimeTypes"] = nlohmann::json(permitMimeTypes_); + jsonObject["editType"] = static_cast(editType_); + std::string additionalDataStr; + if (additionalData_) { + AAFwk::WantParamWrapper wWrapper(*additionalData_); + additionalDataStr = wWrapper.ToString(); + } + jsonObject["additionalData"] = additionalDataStr; + + return true; +} + +NotificationUserInput *NotificationUserInput::FromJson(const nlohmann::json &jsonObject) +{ + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Invalid JSON object"); + return nullptr; + } + + auto pUserInput = new (std::nothrow) NotificationUserInput(); + if (pUserInput == nullptr) { + ANS_LOGE("Failed to create userInput instance"); + return nullptr; + } + + const auto &jsonEnd = jsonObject.cend(); + if (jsonObject.find("inputKey") != jsonEnd) { + pUserInput->inputKey_ = jsonObject.at("inputKey").get(); + } + + if (jsonObject.find("tag") != jsonEnd) { + pUserInput->tag_ = jsonObject.at("tag").get(); + } + + if (jsonObject.find("options") != jsonEnd) { + pUserInput->options_ = jsonObject.at("options").get>(); + } + + if (jsonObject.find("permitFreeFormInput") != jsonEnd) { + pUserInput->permitFreeFormInput_ = jsonObject.at("permitFreeFormInput").get(); + } + + if (jsonObject.find("permitMimeTypes") != jsonEnd) { + pUserInput->permitMimeTypes_ = jsonObject.at("permitMimeTypes").get>(); + } + + if (jsonObject.find("additionalData") != jsonEnd) { + auto additionalDataString = jsonObject.at("additionalData").get(); + if (!additionalDataString.empty()) { + AAFwk::WantParams params = AAFwk::WantParamWrapper::ParseWantParams(additionalDataString); + pUserInput->additionalData_ = std::make_shared(params); + } + } + + if (jsonObject.find("editType") != jsonEnd) { + auto editTypeValue = jsonObject.at("editType").get(); + pUserInput->editType_ = static_cast(editTypeValue); + } + + return pUserInput; } bool NotificationUserInput::Marshalling(Parcel &parcel) const @@ -245,15 +318,15 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const return false; } - auto valid = pacMap_ ? true : false; + auto valid = additionalData_ ? true : false; if (!parcel.WriteBool(valid)) { - ANS_LOGE("Failed to write the flag which indicate whether pacMap is null"); + ANS_LOGE("Failed to write the flag which indicate whether additionalData is null"); return false; } if (valid) { - if (!parcel.WriteParcelable(pacMap_.get())) { - ANS_LOGE("Failed to write pacMap"); + if (!parcel.WriteParcelable(additionalData_.get())) { + ANS_LOGE("Failed to write additionalData"); return false; } } @@ -280,8 +353,8 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const NotificationUserInput *NotificationUserInput::Unmarshalling(Parcel &parcel) { - auto pUserInput = new NotificationUserInput(); - if ((nullptr != pUserInput) && !pUserInput->ReadFromParcel(parcel)) { + auto pUserInput = new (std::nothrow) NotificationUserInput(); + if ((pUserInput != nullptr) && !pUserInput->ReadFromParcel(parcel)) { delete pUserInput; pUserInput = nullptr; } @@ -307,9 +380,9 @@ bool NotificationUserInput::ReadFromParcel(Parcel &parcel) auto valid = parcel.ReadBool(); if (valid) { - pacMap_ = std::shared_ptr(parcel.ReadParcelable()); - if (!pacMap_) { - ANS_LOGE("Failed to read pacMap"); + additionalData_ = std::shared_ptr(parcel.ReadParcelable()); + if (!additionalData_) { + ANS_LOGE("Failed to read additionalData"); return false; } } @@ -333,4 +406,4 @@ bool NotificationUserInput::ReadFromParcel(Parcel &parcel) return true; } } // namespace Notification -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_helper.cpp b/frameworks/ans/native/src/reminder_helper.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3197916aec4e4f7c1608785cb4759518bdf28f8e --- /dev/null +++ b/frameworks/ans/native/src/reminder_helper.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "ans_notification.h" +#include "application_env_impl.h" +#include "bundle_mgr_interface.h" +#include "iservice_registry.h" +#include "notification_helper.h" +#include "singleton.h" +#include "system_ability_definition.h" + +#include "reminder_helper.h" + +namespace OHOS { +namespace Notification { +ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) +{ + ANSR_LOGI("PublishReminder start"); + + NotificationSlot slot(reminder.GetSlotType()); + NotificationHelper::AddNotificationSlot(slot); + return DelayedSingleton::GetInstance()->PublishReminder(reminder); +} + +ErrCode ReminderHelper::CancelReminder(const int32_t reminderId) +{ + ANSR_LOGI("CancelReminder start"); + return DelayedSingleton::GetInstance()->CancelReminder(reminderId); +} + +ErrCode ReminderHelper::CancelAllReminders() +{ + ANSR_LOGI("CancelAllReminders start"); + return DelayedSingleton::GetInstance()->CancelAllReminders(); +} + +bool ReminderHelper::CheckPermission() +{ + ANSR_LOGI("CheckPermission"); + AppExecFwk::ApplicationEnvImpl* application = AppExecFwk::ApplicationEnvImpl::GetInstance(); + std::string pkgName = application->GetBundleName(); + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + ANSR_LOGE("Permission denied"); + return false; + } + auto bundleManager = + iface_cast(systemManager->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID)); + if (bundleManager->CheckPermission(pkgName, "ohos.permission.PUBLISH_AGENT_REMINDER") != 0) { + ANSR_LOGE("Permission denied"); + return false; + } + return true; +} + +ErrCode ReminderHelper::GetValidReminders(std::vector> &validReminders) +{ + ANSR_LOGI("GetValidReminders start"); + return DelayedSingleton::GetInstance()->GetValidReminders(validReminders); +} + +ErrCode AddNotificationSlot(const NotificationSlot &slot) +{ + ANSR_LOGI("AddNotificationSlot start"); + return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); +} + +ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) +{ + ANSR_LOGI("RemoveNotificationSlot start"); + return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3b27d3b01f52972a8298a678963e3e5a25f9e8d0 --- /dev/null +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -0,0 +1,1184 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "want_agent_helper.h" + +#include "reminder_request.h" + +namespace OHOS { +namespace Notification { +int32_t ReminderRequest::GLOBAL_ID = 0; +const uint64_t ReminderRequest::INVALID_LONG_LONG_VALUE = 0; +const uint16_t ReminderRequest::INVALID_U16_VALUE = 0; +const uint16_t ReminderRequest::MILLI_SECONDS = 1000; +const uint16_t ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS = 1000; +const uint32_t ReminderRequest::MIN_TIME_INTERVAL_IN_MILLI = 5 * 60 * 1000; +const uint8_t ReminderRequest::INVALID_U8_VALUE = 0; +const uint8_t ReminderRequest::REMINDER_STATUS_INACTIVE = 0; +const uint8_t ReminderRequest::REMINDER_STATUS_ACTIVE = 1; +const uint8_t ReminderRequest::REMINDER_STATUS_ALERTING = 2; +const uint8_t ReminderRequest::REMINDER_STATUS_SHOWING = 4; +const uint8_t ReminderRequest::REMINDER_STATUS_SNOOZE = 8; +const std::string ReminderRequest::NOTIFICATION_LABEL = "REMINDER_AGENT"; +const std::string ReminderRequest::REMINDER_EVENT_ALARM_ALERT = "ohos.event.notification.reminder.ALARM_ALERT"; +const std::string ReminderRequest::REMINDER_EVENT_CLOSE_ALERT = "ohos.event.notification.reminder.CLOSE_ALERT"; +const std::string ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT = "ohos.event.notification.reminder.SNOOZE_ALERT"; +const std::string ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT = "ohos.event.notification.reminder.ALERT_TIMEOUT"; +const std::string ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION = + "ohos.event.notification.reminder.REMOVE_NOTIFICATION"; +const std::string ReminderRequest::PARAM_REMINDER_ID = "REMINDER_ID"; +const int ReminderRequest::BASE_YEAR = 1900; + +ReminderRequest::ReminderRequest() +{ + wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; + maxScreenWantAgentInfo_ = + maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; +} + +ReminderRequest::ReminderRequest(const ReminderRequest &other) +{ + this->content_ = other.content_; + this->expiredContent_ = other.expiredContent_; + this->snoozeContent_ = other.snoozeContent_; + this->displayContent_ = other.displayContent_; + this->title_ = other.title_; + this->isExpired_ = other.isExpired_; + this->snoozeTimes_ = other.snoozeTimes_; + this->snoozeTimesDynamic_ = other.snoozeTimesDynamic_; + this->state_ = other.state_; + this->notificationId_ = other.notificationId_; + this->reminderId_ = other.reminderId_; + this->reminderTimeInMilli_ = other.reminderTimeInMilli_; + this->ringDurationInMilli_ = other.ringDurationInMilli_; + this->triggerTimeInMilli_ = other.triggerTimeInMilli_; + this->timeIntervalInMilli_ = other.timeIntervalInMilli_; + this->reminderType_ = other.reminderType_; + this->slotType_ = other.slotType_; + this->notificationRequest_ = other.notificationRequest_; + this->wantAgentInfo_ = other.wantAgentInfo_; + this->maxScreenWantAgentInfo_ = other.maxScreenWantAgentInfo_; + this->actionButtonMap_ = other.actionButtonMap_; +} + +ReminderRequest::ReminderRequest(ReminderType reminderType) +{ + reminderType_ = reminderType; + wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; + maxScreenWantAgentInfo_ = + maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; +} + +bool ReminderRequest::CanRemove() const +{ + if ((state_ & (REMINDER_STATUS_SHOWING | REMINDER_STATUS_ALERTING | REMINDER_STATUS_ACTIVE)) == 0) { + return true; + } + return false; +} + +bool ReminderRequest::CanShow() const +{ + // when system time change by user manually, and the reminde is to show immediately, + // the show reminder just need to be triggered by ReminderDataManager#RefreshRemindersLocked(uint8_t). + // we need to make the REMINDER_EVENT_ALARM_ALERT do nothing. + uint64_t nowInstantMilli = GetNowInstantMilli(); + if (nowInstantMilli == 0) { + return false; + } + if ((nowInstantMilli - GetReminderTimeInMilli()) < MIN_TIME_INTERVAL_IN_MILLI) { + return false; + } + return true; +} + +std::string ReminderRequest::Dump() const +{ + const time_t nextTriggerTime = static_cast(triggerTimeInMilli_ / MILLI_SECONDS); + std::string dateTimeInfo = GetTimeInfoInner(nextTriggerTime, TimeFormat::YMDHMS); + return "Reminder[" + "reminderId=" + std::to_string(reminderId_) + + ", type=" + std::to_string(static_cast(reminderType_)) + + ", state=" + GetState(state_) + + ", nextTriggerTime=" + dateTimeInfo.c_str() + + "]"; +} + +ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type) +{ + if (type != ActionButtonType::CLOSE && type != ActionButtonType::SNOOZE) { + ANSR_LOGI("Button type only support: %{public}d or %{public}d", + static_cast(ActionButtonType::CLOSE), static_cast(ActionButtonType::SNOOZE)); + return *this; + } + ActionButtonInfo actionButtonInfo; + actionButtonInfo.type = type; + actionButtonInfo.title = title; + actionButtonMap_.insert(std::pair(type, actionButtonInfo)); + return *this; +} + +ReminderRequest& ReminderRequest::SetContent(const std::string &content) +{ + content_ = content; + return *this; +} + +ReminderRequest& ReminderRequest::SetExpiredContent(const std::string &expiredContent) +{ + expiredContent_ = expiredContent; + return *this; +} + +void ReminderRequest::SetExpired(bool isExpired) +{ + isExpired_ = isExpired; +} + +void ReminderRequest::InitReminderId() +{ + std::lock_guard lock(std::mutex); + if (GLOBAL_ID < 0) { + ANSR_LOGW("GLOBAL_ID overdule"); + GLOBAL_ID = 0; + } + reminderId_ = ++GLOBAL_ID; + ANSR_LOGI("reminderId_=%{public}d", reminderId_); +} + +bool ReminderRequest::IsExpired() const +{ + return isExpired_; +} + +bool ReminderRequest::IsShowing() const +{ + if ((state_ & REMINDER_STATUS_SHOWING) != 0) { + return true; + } + return false; +} + +void ReminderRequest::OnClose(bool updateNext) +{ + if ((state_ & REMINDER_STATUS_SHOWING) == 0) { + ANSR_LOGE("onClose, the state of reminder is incorrect, state:%{public}s", GetState(state_).c_str()); + return; + } + SetState(false, REMINDER_STATUS_SHOWING | REMINDER_STATUS_SNOOZE, "onClose()"); + if ((state_ & REMINDER_STATUS_ALERTING) != 0) { + SetState(false, REMINDER_STATUS_ALERTING, "onClose"); + } + if (updateNext) { + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false); + if (nextTriggerTime == INVALID_LONG_LONG_VALUE) { + isExpired_ = true; + } else { + SetTriggerTimeInMilli(nextTriggerTime); + snoozeTimesDynamic_ = snoozeTimes_; + } + } +} + +bool ReminderRequest::OnDateTimeChange() +{ + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false); + return HandleSysTimeChange(triggerTimeInMilli_, nextTriggerTime); +} + +bool ReminderRequest::HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optTriggerTime) +{ + if (isExpired_) { + return false; + } + bool showImmediately = false; + if (optTriggerTime != INVALID_LONG_LONG_VALUE && optTriggerTime <= oriTriggerTime) { + // case1. switch to a previous time + SetTriggerTimeInMilli(optTriggerTime); + snoozeTimesDynamic_ = snoozeTimes_; + } else { + uint64_t now = GetNowInstantMilli(); + if (now == 0) { + return false; + } + if (oriTriggerTime <= now) { + // case2. switch to a future time, trigger time is less than now time. + // when the reminder show immediately, trigger time will update in onShow function. + snoozeTimesDynamic_ = 0; + showImmediately = true; + } else { + // case3. switch to a future time, trigger time is larger than now time. + showImmediately = false; + } + } + return showImmediately; +} + +bool ReminderRequest::HandleTimeZoneChange( + uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime) +{ + if (isExpired_) { + return false; + } + ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", + (unsigned long long)oldZoneTriggerTime, (unsigned long long)newZoneTriggerTime); + if (oldZoneTriggerTime == newZoneTriggerTime) { + return false; + } + bool showImmediately = false; + if (optTriggerTime != INVALID_LONG_LONG_VALUE && oldZoneTriggerTime < newZoneTriggerTime) { + // case1. timezone change to smaller + SetTriggerTimeInMilli(optTriggerTime); + snoozeTimesDynamic_ = snoozeTimes_; + } else { + // case2. timezone change to larger + time_t now; + (void)time(&now); // unit is seconds. + if (static_cast(now) < 0) { + ANSR_LOGE("Get now time error"); + return false; + } + if (newZoneTriggerTime <= (static_cast(now))) { + snoozeTimesDynamic_ = 0; + showImmediately = true; + } else { + SetTriggerTimeInMilli(newZoneTriggerTime * MILLI_SECONDS); + showImmediately = false; + } + } + return showImmediately; +} + +void ReminderRequest::OnSameNotificationIdCovered() +{ + SetState(false, REMINDER_STATUS_ALERTING | REMINDER_STATUS_SHOWING | REMINDER_STATUS_SNOOZE, + "OnSameNotificationIdCovered"); +} + +void ReminderRequest::OnShow(bool isPlaySoundOrVibration, bool isSysTimeChanged, bool allowToNotify) +{ + if ((state_ & (REMINDER_STATUS_ACTIVE | REMINDER_STATUS_SNOOZE)) != 0) { + SetState(false, REMINDER_STATUS_ACTIVE | REMINDER_STATUS_SNOOZE, "onShow()"); + } + if (isSysTimeChanged) { + uint64_t nowInstantMilli = GetNowInstantMilli(); + if (nowInstantMilli == 0) { + ANSR_LOGW("Onshow, get now time error"); + } + reminderTimeInMilli_ = nowInstantMilli; + } else { + reminderTimeInMilli_ = triggerTimeInMilli_; + } + UpdateNextReminder(false); + if (allowToNotify) { + SetState(true, REMINDER_STATUS_SHOWING, "OnShow"); + if (isPlaySoundOrVibration) { + SetState(true, REMINDER_STATUS_ALERTING, "OnShow"); + } + UpdateNotificationStateForAlert(); + } +} + +void ReminderRequest::OnShowFail() +{ + SetState(false, REMINDER_STATUS_SHOWING, "OnShowFailed()"); +} + +bool ReminderRequest::OnSnooze() +{ + if ((state_ & REMINDER_STATUS_SNOOZE) != 0) { + ANSR_LOGW("onSnooze, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str()); + return false; + } + if ((state_ & REMINDER_STATUS_ALERTING) != 0) { + SetState(false, REMINDER_STATUS_ALERTING, "onSnooze()"); + } + if (!UpdateNextReminder(true)) { + return false; + } + UpdateNotificationStateForSnooze(); + if (timeIntervalInMilli_ > 0) { + SetState(true, REMINDER_STATUS_SNOOZE, "onSnooze()"); + } + return true; +} + +void ReminderRequest::OnStart() +{ + if ((state_ & REMINDER_STATUS_ACTIVE) != 0) { + ANSR_LOGE( + "start failed, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str()); + return; + } + if (isExpired_) { + ANSR_LOGE("start failed, the reminder is expired"); + return; + } + SetState(true, REMINDER_STATUS_ACTIVE, "OnStart()"); +} + +void ReminderRequest::OnStop() +{ + ANSR_LOGI("Stop the previous active reminder, %{public}s", this->Dump().c_str()); + if ((state_ & REMINDER_STATUS_ACTIVE) == 0) { + ANSR_LOGW("onStop, the state of reminder is incorrect, state: %{public}s", (GetState(state_)).c_str()); + return; + } + SetState(false, REMINDER_STATUS_ACTIVE, "OnStop"); +} + +bool ReminderRequest::OnTerminate() +{ + if ((state_ & REMINDER_STATUS_ALERTING) == 0) { + ANSR_LOGW("onTerminate, the state of reminder is %{public}s", (GetState(state_)).c_str()); + return false; + } + SetState(false, REMINDER_STATUS_ALERTING, "onTerminate"); + UpdateNotificationStateForAlert(); + return true; +} + +bool ReminderRequest::OnTimeZoneChange() +{ + time_t oldZoneTriggerTime = static_cast(triggerTimeInMilli_ / MILLI_SECONDS); + struct tm *oriTime = gmtime(&oldZoneTriggerTime); + time_t newZoneTriggerTime = mktime(oriTime); + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(true, false); + return HandleTimeZoneChange(oldZoneTriggerTime, newZoneTriggerTime, nextTriggerTime); +} + +ReminderRequest& ReminderRequest::SetMaxScreenWantAgentInfo( + const std::shared_ptr &maxScreenWantAgentInfo) +{ + maxScreenWantAgentInfo_ = maxScreenWantAgentInfo; + return *this; +} + +ReminderRequest& ReminderRequest::SetNotificationId(int32_t notificationId) +{ + notificationId_ = notificationId; + return *this; +} + +ReminderRequest& ReminderRequest::SetSlotType(const NotificationConstant::SlotType &slotType) +{ + slotType_ = slotType; + return *this; +} + +ReminderRequest& ReminderRequest::SetSnoozeContent(const std::string &snoozeContent) +{ + snoozeContent_ = snoozeContent; + return *this; +} + +ReminderRequest& ReminderRequest::SetSnoozeTimes(const uint8_t snoozeTimes) +{ + snoozeTimes_ = snoozeTimes; + SetSnoozeTimesDynamic(snoozeTimes); + return *this; +} + +ReminderRequest& ReminderRequest::SetSnoozeTimesDynamic(const uint8_t snooziTimes) +{ + snoozeTimesDynamic_ = snooziTimes; + return *this; +} + +ReminderRequest& ReminderRequest::SetTimeInterval(const uint64_t timeIntervalInSeconds) +{ + if (timeIntervalInSeconds < 0 || timeIntervalInSeconds > (UINT64_MAX / MILLI_SECONDS)) { + ANSR_LOGW("SetTimeInterval, replace to set (0s), for the given is out of legal range"); + timeIntervalInMilli_ = 0; + } else { + uint64_t timeIntervalInMilli = timeIntervalInSeconds * MILLI_SECONDS; + if (timeIntervalInMilli > 0 && timeIntervalInMilli < MIN_TIME_INTERVAL_IN_MILLI) { + ANSR_LOGW("SetTimeInterval, replace to set %{public}u, for the given is 0<%{public}llu<%{public}u", + MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS, (unsigned long long)timeIntervalInSeconds, + MIN_TIME_INTERVAL_IN_MILLI / MILLI_SECONDS); + timeIntervalInMilli_ = MIN_TIME_INTERVAL_IN_MILLI; + } else { + timeIntervalInMilli_ = timeIntervalInMilli; + } + } + return *this; +} + +ReminderRequest& ReminderRequest::SetTitle(const std::string &title) +{ + title_ = title; + return *this; +} + +void ReminderRequest::SetTriggerTimeInMilli(uint64_t triggerTimeInMilli) +{ + triggerTimeInMilli_ = triggerTimeInMilli; +} + +ReminderRequest& ReminderRequest::SetWantAgentInfo(const std::shared_ptr &wantAgentInfo) +{ + wantAgentInfo_ = wantAgentInfo; + return *this; +} + +bool ReminderRequest::ShouldShowImmediately() const +{ + uint64_t nowInstantMilli = GetNowInstantMilli(); + if (nowInstantMilli == 0) { + return false; + } + if (triggerTimeInMilli_ > nowInstantMilli) { + return false; + } + return true; +} + +std::map ReminderRequest::GetActionButtons( + ) const +{ + return actionButtonMap_; +} + +std::string ReminderRequest::GetContent() const +{ + return content_; +} + +std::string ReminderRequest::GetExpiredContent() const +{ + return expiredContent_; +} + +std::shared_ptr ReminderRequest::GetMaxScreenWantAgentInfo() const +{ + return maxScreenWantAgentInfo_; +} + +int32_t ReminderRequest::GetNotificationId() const +{ + return notificationId_; +} + +sptr ReminderRequest::GetNotificationRequest() const +{ + return notificationRequest_; +} + +int32_t ReminderRequest::GetReminderId() const +{ + return reminderId_; +} + +uint64_t ReminderRequest::GetReminderTimeInMilli() const +{ + return reminderTimeInMilli_; +} + +void ReminderRequest::SetReminderId(int32_t reminderId) +{ + reminderId_ = reminderId; +} + +void ReminderRequest::SetReminderTimeInMilli(const uint64_t reminderTimeInMilli) +{ + reminderTimeInMilli_ = reminderTimeInMilli; +} + +ReminderRequest& ReminderRequest::SetRingDuration(const uint64_t ringDurationInSeconds) +{ + if (ringDurationInSeconds <= 0 || ringDurationInSeconds > (UINT64_MAX / MILLI_SECONDS)) { + ANSR_LOGW("setRingDuration, replace to set (1s), for the given is out of legal range"); + ringDurationInMilli_ = MILLI_SECONDS; + } else { + ringDurationInMilli_ = ringDurationInSeconds * MILLI_SECONDS; + } + return *this; +} + +NotificationConstant::SlotType ReminderRequest::GetSlotType() const +{ + return slotType_; +} + +std::string ReminderRequest::GetSnoozeContent() const +{ + return snoozeContent_; +} + +uint8_t ReminderRequest::GetSnoozeTimes() const +{ + return snoozeTimes_; +} + +uint8_t ReminderRequest::GetSnoozeTimesDynamic() const +{ + return snoozeTimesDynamic_; +} + +uint8_t ReminderRequest::GetState() const +{ + return state_; +} + +uint64_t ReminderRequest::GetTimeInterval() const +{ + return timeIntervalInMilli_ / MILLI_SECONDS; +} + +std::string ReminderRequest::GetTitle() const +{ + return title_; +} + +uint64_t ReminderRequest::GetTriggerTimeInMilli() const +{ + return triggerTimeInMilli_; +} + +std::shared_ptr ReminderRequest::GetWantAgentInfo() const +{ + return wantAgentInfo_; +} + +ReminderRequest::ReminderType ReminderRequest::GetReminderType() const +{ + return reminderType_; +} + +uint16_t ReminderRequest::GetRingDuration() const +{ + return ringDurationInMilli_ / MILLI_SECONDS; +} + +bool ReminderRequest::UpdateNextReminder() +{ + return false; +} + +void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra) +{ + switch (type) { + case UpdateNotificationType::COMMON: { + ANSR_LOGI("UpdateNotification common information"); + UpdateNotificationCommon(); + 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); + 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::CONTENT: { + break; + } + default: + break; + } +} + +bool ReminderRequest::Marshalling(Parcel &parcel) const +{ + // write string + if (!parcel.WriteString(content_)) { + ANSR_LOGE("Failed to write content"); + return false; + } + if (!parcel.WriteString(expiredContent_)) { + ANSR_LOGE("Failed to write expiredContent"); + return false; + } + if (!parcel.WriteString(snoozeContent_)) { + ANSR_LOGE("Failed to write snoozeContent"); + return false; + } + if (!parcel.WriteString(title_)) { + ANSR_LOGE("Failed to write title"); + return false; + } + if (!parcel.WriteString(wantAgentInfo_->abilityName)) { + ANSR_LOGE("Failed to write wantAgentInfo`s abilityName"); + return false; + } + if (!parcel.WriteString(wantAgentInfo_->pkgName)) { + ANSR_LOGE("Failed to write wantAgentInfo`s pkgName"); + return false; + } + if (!parcel.WriteString(maxScreenWantAgentInfo_->abilityName)) { + ANSR_LOGE("Failed to write maxScreenWantAgentInfo`s abilityName"); + return false; + } + if (!parcel.WriteString(maxScreenWantAgentInfo_->pkgName)) { + ANSR_LOGE("Failed to write maxScreenWantAgentInfo`s pkgName"); + return false; + } + + // write bool + if (!parcel.WriteBool(isExpired_)) { + ANSR_LOGE("Failed to write isExpired"); + return false; + } + + // write int + if (!parcel.WriteInt32(reminderId_)) { + ANSR_LOGE("Failed to write reminderId"); + return false; + } + if (!parcel.WriteInt32(notificationId_)) { + ANSR_LOGE("Failed to write notificationId"); + return false; + } + if (!parcel.WriteUint64(triggerTimeInMilli_)) { + ANSR_LOGE("Failed to write triggerTimeInMilli"); + return false; + } + if (!parcel.WriteUint64(timeIntervalInMilli_)) { + ANSR_LOGE("Failed to write timeIntervalInMilli"); + return false; + } + if (!parcel.WriteUint64(ringDurationInMilli_)) { + ANSR_LOGE("Failed to write ringDurationInMilli"); + return false; + } + if (!parcel.WriteUint64(reminderTimeInMilli_)) { + ANSR_LOGE("Failed to write reminderTimeInMilli"); + return false; + } + if (!parcel.WriteUint8(snoozeTimes_)) { + ANSR_LOGE("Failed to write snoozeTimes"); + return false; + } + if (!parcel.WriteUint8(snoozeTimesDynamic_)) { + ANSR_LOGE("Failed to write snoozeTimesDynamic"); + return false; + } + if (!parcel.WriteUint8(state_)) { + ANSR_LOGE("Failed to write state"); + return false; + } + + // write enum + if (!parcel.WriteUint8(static_cast(reminderType_))) { + ANSR_LOGE("Failed to write reminder type"); + return false; + } + if (!parcel.WriteInt32(static_cast(slotType_))) { + ANSR_LOGE("Failed to write slot type"); + return false; + } + + // write map + int32_t buttonMapSize = static_cast(actionButtonMap_.size()); + if (!parcel.WriteInt32(buttonMapSize)) { + ANSR_LOGE("Failed to write action button size"); + return false; + } + for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) { + if (!parcel.WriteUint8(static_cast(it->first))) { + ANSR_LOGE("Failed to write action button type"); + return false; + } + if (!parcel.WriteString(static_cast(it->second.title))) { + ANSR_LOGE("Failed to write action button title"); + return false; + } + } + return true; +} + +ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) +{ + auto objptr = new ReminderRequest(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + + return objptr; +} + +bool ReminderRequest::ReadFromParcel(Parcel &parcel) +{ + // read string + if (!parcel.ReadString(content_)) { + ANSR_LOGE("Failed to read content"); + return false; + } + if (!parcel.ReadString(expiredContent_)) { + ANSR_LOGE("to read expiredContent"); + return false; + } + if (!parcel.ReadString(snoozeContent_)) { + ANSR_LOGE("to read snoozeContent"); + return false; + } + if (!parcel.ReadString(title_)) { + ANSR_LOGE("Failed to read title"); + return false; + } + if (!parcel.ReadString(wantAgentInfo_->abilityName)) { + ANSR_LOGE("Failed to read wantAgentInfo`s abilityName"); + return false; + } + if (!parcel.ReadString(wantAgentInfo_->pkgName)) { + ANSR_LOGE("Failed to read wantAgentInfo`s pkgName"); + return false; + } + if (!parcel.ReadString(maxScreenWantAgentInfo_->abilityName)) { + ANSR_LOGE("Failed to read maxScreenWantAgentInfo`s abilityName"); + return false; + } + if (!parcel.ReadString(maxScreenWantAgentInfo_->pkgName)) { + ANSR_LOGE("Failed to read maxScreenWantAgentInfo`s pkgName"); + return false; + } + + // read bool + if (!parcel.ReadBool(isExpired_)) { + ANSR_LOGE("Failed to read isExpired"); + return false; + } + + // read int + int32_t tempReminderId = -1; + if (!parcel.ReadInt32(tempReminderId)) { + ANSR_LOGE("Failed to read tempReminderId"); + return false; + } + reminderId_ = tempReminderId == -1 ? reminderId_ : tempReminderId; + + if (!parcel.ReadInt32(notificationId_)) { + ANSR_LOGE("Failed to read notificationId"); + return false; + } + if (!parcel.ReadUint64(triggerTimeInMilli_)) { + ANSR_LOGE("Failed to read triggerTimeInMilli"); + return false; + } + if (!parcel.ReadUint64(timeIntervalInMilli_)) { + ANSR_LOGE("Failed to read timeIntervalInMilli"); + return false; + } + if (!parcel.ReadUint64(ringDurationInMilli_)) { + ANSR_LOGE("Failed to read ringDurationInMilli"); + return false; + } + if (!parcel.ReadUint64(reminderTimeInMilli_)) { + ANSR_LOGE("Failed to read reminderTimeInMilli"); + return false; + } + if (!parcel.ReadUint8(snoozeTimes_)) { + ANSR_LOGE("Failed to read snoozeTimes"); + return false; + } + if (!parcel.ReadUint8(snoozeTimesDynamic_)) { + ANSR_LOGE("Failed to read snoozeTimesDynamic"); + return false; + } + if (!parcel.ReadUint8(state_)) { + ANSR_LOGE("Failed to read state"); + return false; + } + + // read enum + uint8_t reminderType = static_cast(ReminderType::INVALID); + if (!parcel.ReadUint8(reminderType)) { + ANSR_LOGE("Failed to read reminderType"); + return false; + } + reminderType_ = static_cast(reminderType); + + int32_t slotType = static_cast(NotificationConstant::SlotType::OTHER); + if (!parcel.ReadInt32(slotType)) { + ANSR_LOGE("Failed to read slotType"); + return false; + } + slotType_ = static_cast(slotType); + + // read map + int32_t buttonMapSize = 0; + if (!parcel.ReadInt32(buttonMapSize)) { + ANSR_LOGE("Failed to read buttonMapSize"); + return false; + } + for (int i = 0; i < buttonMapSize; i++) { + uint8_t buttonType = static_cast(ActionButtonType::INVALID); + if (!parcel.ReadUint8(buttonType)) { + ANSR_LOGE("Failed to read buttonType"); + return false; + } + ActionButtonType type = static_cast(buttonType); + std::string title = parcel.ReadString(); + ActionButtonInfo info; + info.type = type; + info.title = title; + actionButtonMap_.insert(std::pair(type, info)); + } + InitNotificationRequest(); + return true; +} + +void ReminderRequest::InitNotificationRequest() +{ + ANSR_LOGI("Init notification"); + notificationRequest_ = new NotificationRequest(notificationId_); + displayContent_ = content_; + AddActionButtons(true); +} + +bool ReminderRequest::IsAlerting() const +{ + return (state_ & REMINDER_STATUS_ALERTING) != 0; +} + +std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const +{ + return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS); +} + +uint64_t ReminderRequest::GetNowInstantMilli() const +{ + time_t now; + (void)time(&now); // unit is seconds. + if (static_cast(now) < 0) { + ANSR_LOGE("Get now time error"); + return 0; + } + return static_cast(now * MILLI_SECONDS); +} + +std::string ReminderRequest::GetShowTime(const uint64_t showTime) const +{ + if (reminderType_ == ReminderType::TIMER) { + return ""; + } else { + const time_t showTimeInSecond = static_cast(showTime / MILLI_SECONDS); + return GetTimeInfoInner(showTimeInSecond, TimeFormat::HM); + } +} + +std::string ReminderRequest::GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format) const +{ + uint8_t dateTimeLen = 80; + char dateTimeBuffer[dateTimeLen]; + struct tm *timeInfo = localtime(&timeInSecond); + if (timeInfo == nullptr) { + ANSR_LOGW("GetTimeInfoInner fail."); + } else { + switch (format) { + case TimeFormat::YMDHMS: { + (void)strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); + break; + } + case TimeFormat::HM: { + (void)strftime(dateTimeBuffer, dateTimeLen, "%H:%M", timeInfo); + break; + } + default: { + ANSR_LOGW("Time format not support."); + break; + } + } + } + std::string dateTimeInfo(dateTimeBuffer); + return dateTimeInfo; +} + +std::string ReminderRequest::GetState(const uint8_t state) const +{ + std::string stateInfo = "'"; + if (state == REMINDER_STATUS_INACTIVE) { + stateInfo += "Inactive"; + } else { + bool hasSeparator = false; + if ((state & REMINDER_STATUS_ACTIVE) != 0) { + stateInfo += "Active"; + hasSeparator = true; + } + if ((state & REMINDER_STATUS_ALERTING) != 0) { + if (hasSeparator) { + stateInfo += ","; + } + stateInfo += "Alerting"; + hasSeparator = true; + } + if ((state & REMINDER_STATUS_SHOWING) != 0) { + if (hasSeparator) { + stateInfo += ","; + } + stateInfo += "Showing"; + hasSeparator = true; + } + if ((state & REMINDER_STATUS_SNOOZE) != 0) { + if (hasSeparator) { + stateInfo += ","; + } + stateInfo += "Snooze"; + } + stateInfo += "'"; + } + return stateInfo; +} + +void ReminderRequest::AddActionButtons(const bool includeSnooze) +{ + int requestCode = 10; + std::vector flags; + flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + for (auto it = actionButtonMap_.begin(); it != actionButtonMap_.end(); ++it) { + auto want = std::make_shared(); + auto type = it->first; + if (type == ActionButtonType::CLOSE) { + want->SetAction(REMINDER_EVENT_CLOSE_ALERT); + ANSR_LOGD("Add action button, type is close"); + } + if (type == ActionButtonType::SNOOZE) { + if (includeSnooze) { + want->SetAction(REMINDER_EVENT_SNOOZE_ALERT); + ANSR_LOGD("Add action button, type is snooze"); + } else { + ANSR_LOGD("Not add action button, type is snooze, as includeSnooze is false"); + continue; + } + } + want->SetParam("REMINDER_ID", reminderId_); + std::vector> wants; + wants.push_back(want); + auto title = static_cast(it->second.title); + WantAgent::WantAgentInfo buttonWantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, + wants, + nullptr + ); + std::shared_ptr buttonWantAgent = + WantAgent::WantAgentHelper::GetWantAgent(buttonWantAgentInfo); + std::shared_ptr actionButton + = NotificationActionButton::Create(nullptr, title, buttonWantAgent); + notificationRequest_->AddActionButton(actionButton); + } +} + +void ReminderRequest::AddRemovalWantAgent() +{ + int requestCode = 10; + std::vector flags; + flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + auto want = std::make_shared(); + want->SetAction(REMINDER_EVENT_REMOVE_NOTIFICATION); + want->SetParam(PARAM_REMINDER_ID, reminderId_); + std::vector> wants; + wants.push_back(want); + WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, + wants, + nullptr + ); + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); + notificationRequest_->SetRemovalWantAgent(wantAgent); +} + +std::shared_ptr ReminderRequest::CreateWantAgent(AppExecFwk::ElementName &element) const +{ + int requestCode = 10; + std::vector flags; + flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + auto want = std::make_shared(); + want->SetElement(element); + std::vector> wants; + wants.push_back(want); + WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::START_ABILITY, + flags, + wants, + nullptr + ); + return WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); +} + +void ReminderRequest::SetMaxScreenWantAgent(AppExecFwk::ElementName &element) +{ + std::shared_ptr wantAgent = CreateWantAgent(element); + notificationRequest_->SetMaxScreenWantAgent(wantAgent); +} + +void ReminderRequest::SetWantAgent(AppExecFwk::ElementName &element) +{ + std::shared_ptr wantAgent = CreateWantAgent(element); + notificationRequest_->SetWantAgent(wantAgent); +} + +void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string function) +{ + uint8_t oldState = state_; + if (deSet) { + state_ |= newState; + } else { + state_ &= ~newState; + } + ANSR_LOGI("Switch the reminder(reminderId=%{public}d) state, from %{public}s to %{public}s, called by %{public}s", + reminderId_, GetState(oldState).c_str(), GetState(state_).c_str(), function.c_str()); +} + +void ReminderRequest::UpdateActionButtons(const bool &setSnooze) +{ + if (notificationRequest_ == nullptr) { + ANSR_LOGE("updateActionButtons failed, the notificationRequest is null"); + return; + } + notificationRequest_->ClearActionButtons(); + if (setSnooze || snoozeTimesDynamic_ == snoozeTimes_) { + AddActionButtons(false); + } else { + AddActionButtons(true); + } +} + +bool ReminderRequest::UpdateNextReminder(const bool &force) +{ + bool result = true; + if (force) { + uint64_t nowInstantMilli = GetNowInstantMilli(); + if (nowInstantMilli == 0) { + result = false; + } else { + triggerTimeInMilli_ = nowInstantMilli + timeIntervalInMilli_; + snoozeTimesDynamic_ = snoozeTimes_; + if (timeIntervalInMilli_ != 0) { + isExpired_ = false; + } + } + } else { + result = UpdateNextReminder(); + } + std::string info = result == true ? "success" : "no next"; + ANSR_LOGI("updateNextReminder(id=%{public}d, %{public}s): force=%{public}d, trigger time is: %{public}s", + reminderId_, info.c_str(), force, + GetDateTimeInfo(static_cast(triggerTimeInMilli_ / MILLI_SECONDS)).c_str()); + return result; +} + +void ReminderRequest::UpdateNotificationCommon() +{ + notificationRequest_->SetLabel(NOTIFICATION_LABEL); + notificationRequest_->SetShowDeliveryTime(true); + notificationRequest_->SetTapDismissed(true); + notificationRequest_->SetSlotType(slotType_); + auto notificationNormalContent = std::make_shared(); + notificationNormalContent->SetText(displayContent_); + notificationNormalContent->SetTitle(title_); + auto notificationContent = std::make_shared(notificationNormalContent); + notificationRequest_->SetContent(notificationContent); + if (reminderType_ == ReminderRequest::ReminderType::TIMER + || reminderType_ == ReminderRequest::ReminderType::ALARM) { + notificationRequest_->SetUnremovable(true); + } + time_t now; + (void)time(&now); // unit is seconds. + notificationRequest_->SetDeliveryTime(static_cast(now * MILLI_SECONDS)); +} + +void ReminderRequest::UpdateNotificationContent(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 = GetShowTime(triggerTimeInMilli_) + + snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"); + } else { + // the reminder is expired now, when timeInterval is 0 + extendContent = GetShowTime(reminderTimeInMilli_) + + expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"); + } + } else if (IsAlerting()) { + // the reminder is alerting, or ring duration is 0 + extendContent = GetShowTime(reminderTimeInMilli_); + } else if (snoozeTimesDynamic_ != snoozeTimes_) { + // the reminder is snoozing by period artithmetic, when the ring duration is over. + extendContent = GetShowTime(triggerTimeInMilli_) + + snoozeContent_ == "" ? "" : (" (" + snoozeContent_ + ")"); + notificationRequest_->SetTapDismissed(false); + } else { + // the reminder has already snoozed by period arithmetic, when the ring duration is over. + extendContent = GetShowTime(reminderTimeInMilli_) + + expiredContent_ == "" ? "" : (" (" + expiredContent_ + ")"); + } + displayContent_ = content_ + " " + extendContent; + ANSR_LOGD("Display content=%{public}s", displayContent_.c_str()); +} + +void ReminderRequest::UpdateNotificationStateForAlert() +{ + UpdateNotificationContent(false); + UpdateActionButtons(false); +} + +void ReminderRequest::UpdateNotificationStateForSnooze() +{ + UpdateNotificationContent(true); + UpdateActionButtons(true); +} + +int ReminderRequest::GetActualTime(const TimeTransferType &type, int cTime) +{ + switch (type) { + case (TimeTransferType::YEAR): // year + return BASE_YEAR + cTime; + case (TimeTransferType::MONTH): // month + return 1 + cTime; + case (TimeTransferType::WEEK): // week + return 1 + cTime; + default: + return -1; + } +} + +int ReminderRequest::GetCTime(const TimeTransferType &type, int actualTime) +{ + switch (type) { + case (TimeTransferType::YEAR): // year + return actualTime - BASE_YEAR; + case (TimeTransferType::MONTH): // month + return actualTime - 1; + case (TimeTransferType::WEEK): // week + return actualTime - 1; + default: + return -1; + } +} +} +} diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f1334689b7764f1a85879601012eeeebdb22834f --- /dev/null +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -0,0 +1,305 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" + +#include "reminder_request_alarm.h" + +namespace OHOS { +namespace Notification { +const uint8_t ReminderRequestAlarm::DAYS_PER_WEEK = 7; +const uint8_t ReminderRequestAlarm::MONDAY = 1; +const uint8_t ReminderRequestAlarm::SUNDAY = 7; +const uint8_t ReminderRequestAlarm::HOURS_PER_DAY = 24; +const uint16_t ReminderRequestAlarm::SECONDS_PER_HOUR = 3600; +const uint8_t ReminderRequestAlarm::MINUTES_PER_HOUR = 60; +const int8_t ReminderRequestAlarm::INVALID_INT_VALUE = -1; +const int8_t ReminderRequestAlarm::DEFAULT_SNOOZE_TIMES = 3; + +ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) + : ReminderRequest(ReminderRequest::ReminderType::ALARM) +{ + SetSnoozeTimes(DEFAULT_SNOOZE_TIMES); + hour_ = hour; + minute_ = minute; + CheckParamValid(); + SetDaysOfWeek(true, daysOfWeek); + SetTriggerTimeInMilli(GetNextTriggerTime(true)); +} + +ReminderRequestAlarm::ReminderRequestAlarm(const ReminderRequestAlarm &other) : ReminderRequest(other) +{ + this->hour_ = other.hour_; + this->minute_ = other.minute_; + this->repeatDays_ = other.repeatDays_; + ANSR_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); +} + +void ReminderRequestAlarm::CheckParamValid() const +{ + if (hour_ >= HOURS_PER_DAY || hour_ < 0) { + ANSR_LOGE("setted hour is not between [0, 24)"); + throw std::invalid_argument("setted hour is not between [0, 24)"); + } + if (minute_ < 0 || minute_ >= MINUTES_PER_HOUR) { + ANSR_LOGE("setted minute is not between [0, 60)"); + throw std::invalid_argument("setted minute is not between [0, 60)"); + } +} + +bool ReminderRequestAlarm::IsRepeatReminder() const +{ + if ((repeatDays_ != 0) || ((GetTimeInterval() > 0) && (GetSnoozeTimes() > 0))) { + return true; + } else { + return false; + } +} + +void ReminderRequestAlarm::SetDaysOfWeek(bool set, std::vector daysOfWeek) +{ + if (daysOfWeek.size() == 0) { + return; + } + if (daysOfWeek.size() > DAYS_PER_WEEK) { + ANSR_LOGE("The length of daysOfWeek should not larger than 7"); + throw std::invalid_argument("The length of daysOfWeek should not larger than 7"); + } + for (std::vector::iterator it = daysOfWeek.begin(); it != daysOfWeek.end(); ++it) { + if (*it < MONDAY || *it > SUNDAY) { + continue; + } + if (set) { + repeatDays_ |= 1 << (*it - 1); + } else { + repeatDays_ &= ~(1 << (*it - 1)); + } + } +} + +uint64_t ReminderRequestAlarm::PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const +{ + if (ignoreRepeat || (repeatDays_)) { + return GetNextTriggerTime(forceToGetNext); + } else { + return INVALID_LONG_LONG_VALUE; + } +} + +uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const +{ + time_t now; + (void)time(&now); // unit is seconds. + struct tm *nowTime = localtime(&now); + if (nowTime == nullptr) { + ANSR_LOGW("Get local time fail."); + return 0; + } + + ANSR_LOGD("Now: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + "min=%{public}d, sec=%{public}d, week=%{public}d, \n Target: tar_hour=%{public}d, tar_min=%{public}d", + GetActualTime(TimeTransferType::YEAR, nowTime->tm_year), + GetActualTime(TimeTransferType::MONTH, nowTime->tm_mon), + nowTime->tm_mday, nowTime->tm_hour, nowTime->tm_min, nowTime->tm_sec, + GetActualTime(TimeTransferType::WEEK, nowTime->tm_wday), hour_, minute_); + + struct tm tar; + tar.tm_year = nowTime->tm_year; + tar.tm_mon = nowTime->tm_mon; + tar.tm_mday = nowTime->tm_mday; + tar.tm_hour = hour_; + tar.tm_min = minute_; + tar.tm_sec = 0; + + const time_t target = mktime(&tar); + int8_t nextDayInterval = GetNextAlarm(now, target); + time_t nextTriggerTime = 0; + if (nextDayInterval == INVALID_INT_VALUE) { + if (now >= target) { + if (forceToGetNext) { + nextTriggerTime = target + 1 * HOURS_PER_DAY * SECONDS_PER_HOUR; + } + } else { + nextTriggerTime = target; + } + } else { + nextTriggerTime = target + nextDayInterval * HOURS_PER_DAY * SECONDS_PER_HOUR; + } + struct tm *test = localtime(&nextTriggerTime); + if (test == nullptr) { + return 0; + } + ANSR_LOGI("NextTriggerTime: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld", + GetActualTime(TimeTransferType::YEAR, test->tm_year), + GetActualTime(TimeTransferType::MONTH, test->tm_mon), + test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, + GetActualTime(TimeTransferType::WEEK, test->tm_wday), (long long)nextTriggerTime); + + if (static_cast(nextTriggerTime) <= 0) { + return 0; + } + return static_cast(nextTriggerTime) * ReminderRequest::MILLI_SECONDS; +} + +int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target) const +{ + if (repeatDays_ == 0) { + return INVALID_INT_VALUE; + } + int today = gmtime(&now)->tm_wday; + int dayCount = now >= target ? 1 : 0; + for (; dayCount <= DAYS_PER_WEEK; dayCount++) { + int day = (today + dayCount) % DAYS_PER_WEEK; + day = (day == 0) ? SUNDAY : day; + if (IsRepeatDay(day)) { + break; + } + } + ANSR_LOGI("NextDayInterval is %{public}d", dayCount); + return dayCount; +} + +bool ReminderRequestAlarm::IsRepeatDay(int day) const +{ + return (repeatDays_ & (1 << (day - 1))) > 0; +} + +std::vector ReminderRequestAlarm::GetDaysOfWeek() const +{ + std::vector repeatDays; + int days[] = {1, 2, 3, 4, 5, 6, 7}; + int len = sizeof(days) / sizeof(int); + for (int i = 0; i < len; i++) { + if (IsRepeatDay(days[i])) { + repeatDays.push_back(days[i]); + } + } + return repeatDays; +} + +uint8_t ReminderRequestAlarm::GetHour() const +{ + return hour_; +} + +uint8_t ReminderRequestAlarm::GetMinute() const +{ + return minute_; +} + +uint8_t ReminderRequestAlarm::GetRepeatDay() const +{ + return repeatDays_; +} + +bool ReminderRequestAlarm::OnDateTimeChange() +{ + return ReminderRequest::OnDateTimeChange(); +} + +bool ReminderRequestAlarm::OnTimeZoneChange() +{ + return ReminderRequest::OnTimeZoneChange(); +} + +bool ReminderRequestAlarm::UpdateNextReminder() +{ + ANSR_LOGD("UpdateNextReminder alarm time"); + if (IsRepeatReminder()) { + uint8_t letfSnoozeTimes = GetSnoozeTimesDynamic(); + if ((letfSnoozeTimes > 0) && (GetTimeInterval() > 0)) { + ANSR_LOGI("Left times: %{public}d, update next triggerTime", GetSnoozeTimesDynamic()); + SetTriggerTimeInMilli(GetTriggerTimeInMilli() + GetTimeInterval() * MILLI_SECONDS); + SetSnoozeTimesDynamic(--letfSnoozeTimes); + } else { + SetSnoozeTimesDynamic(GetSnoozeTimes()); + if (repeatDays_ == 0) { + ANSR_LOGI("No need to update next triggerTime"); + SetExpired(true); + return false; + } + uint64_t nextTriggerTime = GetNextTriggerTime(true); + if (nextTriggerTime != INVALID_LONG_LONG_VALUE) { + ANSR_LOGI("Set next trigger time successful, reset dynamic snoozeTimes"); + SetTriggerTimeInMilli(nextTriggerTime); + } else { + ANSR_LOGW("Set reminder to expired"); + SetExpired(true); + return false; + } + } + return true; + } else { + ANSR_LOGD("Single time reminder, not need to update next trigger time"); + SetSnoozeTimesDynamic(GetSnoozeTimes()); + SetExpired(true); + return false; + } +} + +bool ReminderRequestAlarm::Marshalling(Parcel &parcel) const +{ + ReminderRequest::Marshalling(parcel); + + // write int + if (!parcel.WriteUint8(hour_)) { + ANSR_LOGE("Failed to write hour"); + return false; + } + if (!parcel.WriteUint8(minute_)) { + ANSR_LOGE("Failed to write minute"); + return false; + } + if (!parcel.WriteUint8(repeatDays_)) { + ANSR_LOGE("Failed to write daysOfWeek"); + return false; + } + return true; +} + +ReminderRequestAlarm *ReminderRequestAlarm::Unmarshalling(Parcel &parcel) +{ + ANSR_LOGD("New alarm"); + auto objptr = new ReminderRequestAlarm(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) +{ + ReminderRequest::ReadFromParcel(parcel); + + // read int + if (!parcel.ReadUint8(hour_)) { + ANSR_LOGE("Failed to read hour"); + return false; + } + if (!parcel.ReadUint8(minute_)) { + ANSR_LOGE("Failed to read minute"); + return false; + } + if (!parcel.ReadUint8(repeatDays_)) { + ANSR_LOGE("Failed to read repeatDays"); + return false; + } + ANSR_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp new file mode 100644 index 0000000000000000000000000000000000000000..115c6fa0d804e308d375bc6f978b7fef2141cfd3 --- /dev/null +++ b/frameworks/ans/native/src/reminder_request_calendar.cpp @@ -0,0 +1,495 @@ +/* + * 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 "ans_log_wrapper.h" + +#include "reminder_request_calendar.h" + +namespace OHOS { +namespace Notification { +const uint8_t ReminderRequestCalendar::MAX_MONTHS_OF_YEAR = 12; +const uint8_t ReminderRequestCalendar::MAX_DAYS_OF_MONTH = 31; +const uint8_t ReminderRequestCalendar::JANUARY = 1; +const uint8_t ReminderRequestCalendar::DECEMBER = 12; +const uint8_t ReminderRequestCalendar::DEFAULT_SNOOZE_TIMES = 3; + +ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, + const std::vector &repeatMonths, const std::vector &repeatDays) + : ReminderRequest(ReminderRequest::ReminderType::CALENDAR) +{ + // 1. record the infomation which designated by user at first time. + firstDesignateYear_ = GetActualTime(TimeTransferType::YEAR, dateTime.tm_year); + firstDesignateMonth_ = GetActualTime(TimeTransferType::MONTH, dateTime.tm_mon); + firstDesignateDay_ = dateTime.tm_mday; + SetRepeatMonths(repeatMonths); + SetRepeatDaysOfMonth(repeatDays); + SetSnoozeTimes(DEFAULT_SNOOZE_TIMES); + + // 2. get the latest valid trigger time. + InitDateTime(dateTime); + hour_ = dateTime_.tm_hour; + minute_ = dateTime_.tm_min; + uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE; + if ((nextTriggerTime = GetNextTriggerTime()) != INVALID_LONG_LONG_VALUE) { + time_t target = static_cast(nextTriggerTime / MILLI_SECONDS); + tm *tar = localtime(&target); + if (tar == nullptr) { + throw std::invalid_argument("Get localtime error"); + } + dateTime_ = *tar; + } else { + ANSR_LOGW("Not exist next trigger time, please check the param of ReminderRequestCalendar constructor."); + throw std::invalid_argument( + "Not exist next trigger time, please check the param of ReminderRequestCalendar constructor."); + } + + // 2. set the time infomation (used to transfer to proxy service) which is decided to trigger firstly. + year_ = GetActualTime(TimeTransferType::YEAR, dateTime_.tm_year); + month_ = GetActualTime(TimeTransferType::MONTH, dateTime_.tm_mon); + day_ = dateTime_.tm_mday; + second_ = 0; + SetTriggerTimeInMilli(nextTriggerTime); +} + +ReminderRequestCalendar::ReminderRequestCalendar(const ReminderRequestCalendar &other) : ReminderRequest(other) +{ + dateTime_ = other.dateTime_; + firstDesignateYear_ = other.firstDesignateYear_; + firstDesignateMonth_ = other.firstDesignateMonth_; + firstDesignateDay_ = other.firstDesignateDay_; + year_ = other.year_; + month_ = other.month_; + day_ = other.day_; + hour_ = other.hour_; + minute_ = other.minute_; + second_ = other.second_; + repeatMonth_ = other.repeatMonth_; + repeatDay_ = other.repeatDay_; +} + +uint8_t ReminderRequestCalendar::GetDaysOfMonth(const uint16_t &year, const uint8_t &month) const +{ + uint8_t days; + uint8_t daysArray[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; + uint8_t february = 2; + uint8_t leapMonth = 29; + uint8_t nonLeapMonth = 28; + uint16_t solarYear = 400; + uint8_t leapParam1 = 4; + uint8_t leapParam2 = 100; + if (month == february) { + days = ((((0 == year % leapParam1) && (0 != year % leapParam2)) || (0 == year % solarYear)) + ? leapMonth : nonLeapMonth); + } else { + days = daysArray[month - 1]; + } + return days; +} + +uint8_t ReminderRequestCalendar::GetNextDay( + const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const +{ + uint32_t repeatDayTmp = repeatDay_; + uint8_t daysOfSpecialMonth = GetDaysOfMonth(settedYear, settedMonth); + uint8_t setDayTmp = INVALID_U8_VALUE; + for (uint8_t i = 1; i <= daysOfSpecialMonth; i++) { + if ((repeatDayTmp & (1 << (i - 1))) > 0) { + struct tm setTime; + setTime.tm_year = GetCTime(TimeTransferType::YEAR, settedYear); + setTime.tm_mon = GetCTime(TimeTransferType::MONTH, settedMonth); + setTime.tm_mday = i; + setTime.tm_hour = target.tm_hour; + setTime.tm_min = target.tm_min; + setTime.tm_sec = target.tm_sec; + + struct tm nowTime; + nowTime.tm_year = now.tm_year; + nowTime.tm_mon = now.tm_mon; + nowTime.tm_mday = now.tm_mday; + nowTime.tm_hour = now.tm_hour; + nowTime.tm_min = now.tm_min; + nowTime.tm_sec = now.tm_sec; + if (mktime(&nowTime) >= mktime(&setTime)) { + continue; + } else { + setDayTmp = i; + return setDayTmp; + } + } + } + return setDayTmp; +} + +uint64_t ReminderRequestCalendar::GetNextTriggerTime() const +{ + uint64_t triggerTimeInMilli = INVALID_LONG_LONG_VALUE; + time_t now; + (void)time(&now); // unit is seconds. + tm *nowTmp = localtime(&now); + if (nowTmp == nullptr) { + ANSR_LOGW("Get local time fail."); + return triggerTimeInMilli; + } + struct tm nowTime = *nowTmp; + nowTime.tm_sec = 0; + struct tm tarTime; + tarTime.tm_year = GetCTime(TimeTransferType::YEAR, firstDesignateYear_); + tarTime.tm_mon = GetCTime(TimeTransferType::MONTH, firstDesignateMonth_); + tarTime.tm_mday = firstDesignateDay_; + tarTime.tm_hour = hour_; + tarTime.tm_min = minute_; + tarTime.tm_sec = 0; + + if (!(repeatMonth_ > 0 && repeatDay_ > 0)) { + const time_t target = mktime(&tarTime); + if (now <= target) { + triggerTimeInMilli = static_cast(target) * MILLI_SECONDS; + ANSR_LOGD("Now time is: %{public}s", GetDateTimeInfo(now).c_str()); + ANSR_LOGD("Tar time is: %{public}s", GetDateTimeInfo(target).c_str()); + } + return triggerTimeInMilli; + } + triggerTimeInMilli = GetNextTriggerTimeAsRepeatReminder(nowTime, tarTime); + return triggerTimeInMilli; +} + +uint64_t ReminderRequestCalendar::GetNextTriggerTimeAsRepeatReminder(const tm &nowTime, const tm &tarTime) const +{ + uint64_t triggerTimeInMilli = INVALID_LONG_LONG_VALUE; + uint16_t setYear = static_cast(GetActualTime(TimeTransferType::YEAR, nowTime.tm_year)); + uint8_t setMonth = INVALID_U8_VALUE; + uint8_t setDay = INVALID_U8_VALUE; + uint8_t beginMonth = static_cast(GetActualTime(TimeTransferType::MONTH, nowTime.tm_mon)); + uint8_t count = 1; + uint16_t repeatMonthTmp = repeatMonth_; + for (uint8_t i = beginMonth; i < (MAX_MONTHS_OF_YEAR + beginMonth + 1); i++) { + if ((repeatMonthTmp & (1 << ((i - 1) % MAX_MONTHS_OF_YEAR))) > 0) { + setMonth = (i % MAX_MONTHS_OF_YEAR); + setMonth = setMonth == 0 ? DECEMBER : setMonth; + if (count != 1) { + setYear = setMonth <= beginMonth ? setYear + 1 : setYear; + } + setDay = GetNextDay(setYear, setMonth, nowTime, tarTime); + } + if (setDay != INVALID_U8_VALUE) { + break; + } + count++; + } + if ((triggerTimeInMilli = GetTimeInstantMilli(setYear, setMonth, setDay, hour_, minute_, second_)) + != INVALID_LONG_LONG_VALUE) { + ANSR_LOGD("Next calendar time:%{public}u/%{public}u/%{public}u %{public}u:%{public}u:%{public}u", + setYear, setMonth, setDay, hour_, minute_, second_); + } + return triggerTimeInMilli; +} + +uint64_t ReminderRequestCalendar::GetTimeInstantMilli( + uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) const +{ + struct tm tar; + tar.tm_year = GetCTime(TimeTransferType::YEAR, year); + tar.tm_mon = GetCTime(TimeTransferType::MONTH, month); + tar.tm_mday = day; + tar.tm_hour = hour; + tar.tm_min = minute; + tar.tm_sec = second; + const time_t target = mktime(&tar); + if (target < 0) { + ANSR_LOGW("GetTImeInstantMilli less than 0."); + return INVALID_LONG_LONG_VALUE; + } + return static_cast(target) * MILLI_SECONDS; +} + +void ReminderRequestCalendar::InitDateTime() +{ + dateTime_.tm_year = GetCTime(TimeTransferType::YEAR, year_); + dateTime_.tm_mon = GetCTime(TimeTransferType::MONTH, month_); + dateTime_.tm_mday = day_; + dateTime_.tm_hour = hour_; + dateTime_.tm_min = minute_; + dateTime_.tm_sec = second_; +} + +void ReminderRequestCalendar::InitDateTime(const tm &dateTime) +{ + dateTime_.tm_year = dateTime.tm_year; + dateTime_.tm_mon = dateTime.tm_mon; + dateTime_.tm_mday = dateTime.tm_mday; + dateTime_.tm_hour = dateTime.tm_hour; + dateTime_.tm_min = dateTime.tm_min; + dateTime_.tm_sec = dateTime.tm_sec; +} + +bool ReminderRequestCalendar::IsRepeatReminder() const +{ + return (repeatMonth_ > 0 && repeatDay_ > 0) || (GetTimeInterval() > 0 && GetSnoozeTimes() > 0); +} + + +bool ReminderRequestCalendar::IsRepeatMonth(uint8_t month) const +{ + return (repeatMonth_ & (1 << (month - 1))) > 0; +} + +bool ReminderRequestCalendar::IsRepeatDay(uint8_t day) const +{ + return (repeatDay_ & (1 << (day - 1))) > 0; +} + +void ReminderRequestCalendar::SetDay(const uint8_t &day, const bool &isSet) +{ + if (day < 1 || day > MAX_DAYS_OF_MONTH) { + return; + } + if (isSet) { + repeatDay_ |= 1 << (day - 1); + } else { + repeatDay_ &= ~(1 << (day - 1)); + } +} + +void ReminderRequestCalendar::SetMonth(const uint8_t &month, const bool &isSet) +{ + if (month < JANUARY || month > DECEMBER) { + return; + } + if (isSet) { + repeatMonth_ |= 1 << (month - 1); + } else { + repeatMonth_ &= ~ (1 << (month - 1)); + } +} + +void ReminderRequestCalendar::SetRepeatMonths(const std::vector &repeatMonths) +{ + if (repeatMonths.size() > MAX_MONTHS_OF_YEAR) { + ANSR_LOGW("The length of repeat months array should not larger than %{public}u", MAX_MONTHS_OF_YEAR); + throw std::invalid_argument( + "The length of repeat months array should not larger than " + std::to_string(MAX_MONTHS_OF_YEAR)); + } + repeatMonth_ = 0; + for (auto it = repeatMonths.begin(); it != repeatMonths.end(); ++it) { + SetMonth((*it), true); + } +} + +void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &repeateDays) +{ + if (repeateDays.size() > MAX_DAYS_OF_MONTH) { + ANSR_LOGW("The length of repeat days array should not larger than %{public}u", MAX_DAYS_OF_MONTH); + throw std::invalid_argument( + "The length of repeat days array should not larger than " + std::to_string(MAX_DAYS_OF_MONTH)); + } + repeatDay_ = 0; + for (auto it = repeateDays.begin(); it != repeateDays.end(); ++it) { + SetDay((*it), true); + } +} + +std::vector ReminderRequestCalendar::GetRepeatMonths() const +{ + std::vector repeatMonths; + for (int i = 0; i < MAX_MONTHS_OF_YEAR; i++) { + if (IsRepeatMonth(i + 1)) { + repeatMonths.push_back(i + 1); + } + } + return repeatMonths; +} + +std::vector ReminderRequestCalendar::GetRepeatDays() const +{ + std::vector repeatDays; + for (int i = 0; i < MAX_DAYS_OF_MONTH; i++) { + if (IsRepeatDay(i + 1)) { + repeatDays.push_back(i + 1); + } + } + return repeatDays; +} + +bool ReminderRequestCalendar::OnDateTimeChange() +{ + return ReminderRequest::OnDateTimeChange(); +} + +bool ReminderRequestCalendar::OnTimeZoneChange() +{ + return ReminderRequest::OnTimeZoneChange(); +} + +bool ReminderRequestCalendar::UpdateNextReminder() +{ + ANSR_LOGD("UpdateNextReminder calendar time"); + if (!IsRepeatReminder()) { + ANSR_LOGI("No need to update next trigger time as it is an one-time reminder."); + SetSnoozeTimesDynamic(GetSnoozeTimes()); + SetExpired(true); + return false; + } + uint8_t leftSnoozeTimes = GetSnoozeTimesDynamic(); + if (leftSnoozeTimes > 0 && (GetTimeInterval() > 0)) { + ANSR_LOGI("Left snooze times: %{public}d, update next triggerTime", leftSnoozeTimes); + SetTriggerTimeInMilli(GetTriggerTimeInMilli() + GetTimeInterval() * MILLI_SECONDS); + SetSnoozeTimesDynamic(--leftSnoozeTimes); + } else { + SetSnoozeTimesDynamic(GetSnoozeTimes()); + if (repeatMonth_ == 0 || repeatDay_ == 0) { + ANSR_LOGI("Not a day repeat reminder, no need to update to next trigger time."); + SetExpired(true); + return false; + } else { + uint64_t nextTriggerTime = GetNextTriggerTime(); + if (nextTriggerTime != INVALID_LONG_LONG_VALUE) { + ANSR_LOGI("Set next trigger time successful, reset dynamic snoozeTimes"); + SetTriggerTimeInMilli(nextTriggerTime); + } else { + ANSR_LOGW("Set next trigger time invalidate"); + SetExpired(true); + return false; + } + } + } + return true; +} + +uint64_t ReminderRequestCalendar::PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const +{ + if (ignoreRepeat || (repeatMonth_ > 0 && repeatDay_ > 0)) { + return GetNextTriggerTime(); + } else { + return INVALID_LONG_LONG_VALUE; + } +} + +bool ReminderRequestCalendar::Marshalling(Parcel &parcel) const +{ + ReminderRequest::Marshalling(parcel); + + // write int + if (!parcel.WriteUint16(year_)) { + ANSR_LOGE("Failed to write year"); + return false; + } + if (!parcel.WriteUint8(month_)) { + ANSR_LOGE("Failed to write month"); + return false; + } + if (!parcel.WriteUint8(day_)) { + ANSR_LOGE("Failed to write day"); + return false; + } + if (!parcel.WriteUint8(hour_)) { + ANSR_LOGE("Failed to write hour"); + return false; + } + if (!parcel.WriteUint8(minute_)) { + ANSR_LOGE("Failed to write minute"); + return false; + } + if (!parcel.WriteUint8(second_)) { + ANSR_LOGE("Failed to write second"); + return false; + } + if (!parcel.WriteUint16(repeatMonth_)) { + ANSR_LOGE("Failed to write repeatMonth"); + return false; + } + if (!parcel.WriteUint32(repeatDay_)) { + ANSR_LOGE("Failed to write repeateDay"); + return false; + } + if (!parcel.WriteUint16(firstDesignateYear_)) { + ANSR_LOGE("Failed to write firstDesignateYear"); + return false; + } + if (!parcel.WriteUint8(firstDesignateMonth_)) { + ANSR_LOGE("Failed to write firstDesignateMonth"); + return false; + } + if (!parcel.WriteUint8(firstDesignateDay_)) { + ANSR_LOGE("Failed to write firstDesignateDay"); + return false; + } + return true; +} + +ReminderRequestCalendar *ReminderRequestCalendar::Unmarshalling(Parcel &parcel) +{ + ANSR_LOGD("New calendar"); + auto objptr = new ReminderRequestCalendar(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool ReminderRequestCalendar::ReadFromParcel(Parcel &parcel) +{ + ReminderRequest::ReadFromParcel(parcel); + + // read int + if (!parcel.ReadUint16(year_)) { + ANSR_LOGE("Failed to read year"); + return false; + } + if (!parcel.ReadUint8(month_)) { + ANSR_LOGE("Failed to read month"); + return false; + } + if (!parcel.ReadUint8(day_)) { + ANSR_LOGE("Failed to read day"); + return false; + } + if (!parcel.ReadUint8(hour_)) { + ANSR_LOGE("Failed to read hour"); + return false; + } + if (!parcel.ReadUint8(minute_)) { + ANSR_LOGE("Failed to read minute"); + return false; + } + if (!parcel.ReadUint8(second_)) { + ANSR_LOGE("Failed to read second"); + return false; + } + if (!parcel.ReadUint16(repeatMonth_)) { + ANSR_LOGE("Failed to read repeatMonth"); + return false; + } + if (!parcel.ReadUint32(repeatDay_)) { + ANSR_LOGE("Failed to read repeateDay"); + return false; + } + InitDateTime(); + if (!parcel.ReadUint16(firstDesignateYear_)) { + ANSR_LOGE("Failed to read firstDesignateYear"); + return false; + } + if (!parcel.ReadUint8(firstDesignateMonth_)) { + ANSR_LOGE("Failed to read firstDesignateMonth"); + return false; + } + if (!parcel.ReadUint8(firstDesignateDay_)) { + ANSR_LOGE("Failed to read firstDesignateDay"); + return false; + } + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/src/reminder_request_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp new file mode 100644 index 0000000000000000000000000000000000000000..773e18eba07ce3027e5ceb3d9bddeac6e0737ebc --- /dev/null +++ b/frameworks/ans/native/src/reminder_request_timer.cpp @@ -0,0 +1,140 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "ans_log_wrapper.h" +#include "time_service_client.h" + +#include "reminder_request_timer.h" + +namespace OHOS { +namespace Notification { +ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) + : ReminderRequest(ReminderRequest::ReminderType::TIMER) +{ + CheckParamsValid(countDownTimeInSeconds); + countDownTimeInSeconds_ = countDownTimeInSeconds; + time_t now; // unit is seconds. + (void)time(&now); + ReminderRequest::SetTriggerTimeInMilli( + (static_cast(now) + countDownTimeInSeconds_) * ReminderRequest::MILLI_SECONDS); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + firstRealTimeInMilliSeconds_ = timer->GetBootTimeMs(); +} + +ReminderRequestTimer::ReminderRequestTimer(const ReminderRequestTimer &other) : ReminderRequest(other) +{ + firstRealTimeInMilliSeconds_ = other.firstRealTimeInMilliSeconds_; + countDownTimeInSeconds_ = other.countDownTimeInSeconds_; +} + +uint64_t ReminderRequestTimer::GetInitInfo() const +{ + return countDownTimeInSeconds_; +} + +uint64_t ReminderRequestTimer::PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const +{ + ANSR_LOGD("countdonw time not support PreGetNextTriggerTimeIgnoreSnooze"); + return ReminderRequest::INVALID_LONG_LONG_VALUE; +} + +bool ReminderRequestTimer::OnDateTimeChange() +{ + UpdateTimeInfo("onDateTimeChange"); + return false; +} + +bool ReminderRequestTimer::OnTimeZoneChange() +{ + UpdateTimeInfo("onTimeZoneChange"); + return false; +} + +bool ReminderRequestTimer::UpdateNextReminder() +{ + ANSR_LOGD("countdonw time not support repeat reminder, no need to update next triggerTime"); + SetExpired(true); + return false; +} + +void ReminderRequestTimer::CheckParamsValid(const uint64_t countDownTimeInSeconds) const +{ + if (countDownTimeInSeconds == 0 || countDownTimeInSeconds >= (UINT64_MAX / ReminderRequest::MILLI_SECONDS)) { + ANSR_LOGE("Illegal count down time, please check the description of the constructor"); + throw std::invalid_argument("Illegal count down time, please check the description of the constructor"); + } +} + +void ReminderRequestTimer::UpdateTimeInfo(const std::string description) +{ + if (IsExpired()) { + return; + } + ANSR_LOGD("%{public}s, update countdown time trigger time", description.c_str()); + time_t now; + (void)time(&now); // unit is seconds. + whenToChangeSysTime_ = static_cast(now) * MILLI_SECONDS; + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + int64_t bootTime = timer->GetBootTimeMs(); + SetTriggerTimeInMilli(whenToChangeSysTime_ + (countDownTimeInSeconds_ * MILLI_SECONDS - + (bootTime - firstRealTimeInMilliSeconds_))); +} + +bool ReminderRequestTimer::Marshalling(Parcel &parcel) const +{ + ReminderRequest::Marshalling(parcel); + + // write int + if (!parcel.WriteUint64(firstRealTimeInMilliSeconds_)) { + ANSR_LOGE("Failed to write firstRealTimeInMilliSeconds"); + return false; + } + if (!parcel.WriteUint64(countDownTimeInSeconds_)) { + ANSR_LOGE("Failed to write countDownTimeInSeconds"); + return false; + } + return true; +} + +ReminderRequestTimer *ReminderRequestTimer::Unmarshalling(Parcel &parcel) +{ + auto objptr = new ReminderRequestTimer(); + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool ReminderRequestTimer::ReadFromParcel(Parcel &parcel) +{ + ReminderRequest::ReadFromParcel(parcel); + + // read int + if (!parcel.ReadUint64(firstRealTimeInMilliSeconds_)) { + ANSR_LOGE("Failed to read firstRealTimeInMilliSeconds"); + return false; + } + if (!parcel.ReadUint64(countDownTimeInSeconds_)) { + ANSR_LOGE("Failed to read countDownTimeInSeconds"); + return false; + } + return true; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/test/unittest/BUILD.gn b/frameworks/ans/native/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..dd864cd0bd69b05c60296eddad8a84b9aa33683b --- /dev/null +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -0,0 +1,75 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +module_output_path = "ans_reminder/unittest" + +ohos_unittest("ans_reminder_unit_test") { + module_out_path = module_output_path + + include_dirs = [ + ".", + "include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + "/${services_path}/ans/include", + "${services_path}/ans/test/unittest/mock/include", + ] + + sources = [ + "${native_path}/test/unittest/reminder_request_alarm_test.cpp", + "${native_path}/test/unittest/reminder_request_calendar_test.cpp", + "${native_path}/test/unittest/reminder_request_test.cpp", + "${native_path}/test/unittest/reminder_request_timer_test.cpp", + ] + + configs = [ "//utils/native/base:utils_config" ] + + deps = [ + "${core_path}:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "bytrace_standard:bytrace_core", + "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimedia_image_standard:image_native", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} + +group("unittest") { + testonly = true + deps = [] + + deps += [ ":ans_reminder_unit_test" ] +} diff --git a/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3e76090e706690195f1f7761f6000140930a34e9 --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp @@ -0,0 +1,210 @@ +/* + * 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 "ans_log_wrapper.h" +#include "reminder_request_alarm.h" +#include "reminder_helper.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class ReminderRequestAlarmTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() + { + ReminderHelper::CancelAllReminders(); + } +}; + +/** + * @tc.number : initHour_00100 + * @tc.name : + * @tc.desc : set hour < 0 should throw exception. + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00100, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + try { + auto rrc = std::make_shared(-1, 1, daysOfWeek); + EXPECT_TRUE(false) << "hour < 0 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("hour < 0 throw exception."); + } +} + +/** + * @tc.number : initHour_00200 + * @tc.name : + * @tc.desc : set hour > 23 should throw exception. + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00200, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + try { + auto rrc = std::make_shared(24, 1, daysOfWeek); + EXPECT_TRUE(false) << "hour > 23 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("hour > 23 throw exception."); + } +} + +/** + * @tc.number : initHour_00300 + * @tc.name : + * @tc.desc : test set edge value of hour (0 and 23). + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00300, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + auto rrc = std::make_shared(0, 1, daysOfWeek); + EXPECT_TRUE(rrc->GetHour() == 0) << "hour should be 0"; + + auto rrcB = std::make_shared(23, 1, daysOfWeek); + EXPECT_TRUE(rrcB->GetHour() == 23) << "hour should be 23"; + + auto rrcC = std::make_shared(1, 1, daysOfWeek); + EXPECT_TRUE(rrcC->GetHour() == 1) << "hour should be 1"; + + auto rrcD = std::make_shared(22, 1, daysOfWeek); + EXPECT_TRUE(rrcD->GetHour() == 22) << "hour should be 22"; + + auto rrcE = std::make_shared(12, 1, daysOfWeek); + EXPECT_TRUE(rrcE->GetHour() == 12) << "hour should be 12"; +} + +/** + * @tc.number : initHour_00400 + * @tc.name : + * @tc.desc : set minute < 0 should throw exception. + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00400, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + try { + auto rrc = std::make_shared(1, -1, daysOfWeek); + EXPECT_TRUE(false) << "minute < 0 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("minute < 0 throw exception."); + } +} + +/** + * @tc.number : initHour_00500 + * @tc.name : + * @tc.desc : set minute > 59 should throw exception. + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00500, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + try { + auto rrc = std::make_shared(1, 60, daysOfWeek); + EXPECT_TRUE(false) << "minute > 59 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("minute > 59 throw exception."); + } +} + +/** + * @tc.number : initHour_00600 + * @tc.name : + * @tc.desc : test set edge value of minute (0 and 59). + */ +HWTEST_F(ReminderRequestAlarmTest, initHour_00600, Function | SmallTest | Level1) +{ + std::vector daysOfWeek; + auto rrc = std::make_shared(0, 0, daysOfWeek); + EXPECT_TRUE(rrc->GetMinute() == 0) << "minute should be 0"; + + auto rrcB = std::make_shared(23, 59, daysOfWeek); + EXPECT_TRUE(rrcB->GetMinute() == 59) << "minute should be 59"; +} + +/** + * @tc.number : initDaysOfWeek_00100 + * @tc.name : + * @tc.desc : test set daysOfWeek with normal value. + */ +HWTEST_F(ReminderRequestAlarmTest, initDaysOfWeek_00100, Function | SmallTest | Level1) +{ + uint8_t arr[] = {1, 2, 3}; + std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); + auto rrc = std::make_shared(0, 0, daysOfWeek); + uint8_t expectedVal = 7; + EXPECT_TRUE(rrc->GetRepeatDay() == expectedVal) << "repeatDays (1, 2, 3) should be 7"; +} + +/** + * @tc.number : initDaysOfWeek_00200 + * @tc.name : + * @tc.desc : test set daysOfWeek with edge value. + */ +HWTEST_F(ReminderRequestAlarmTest, initDaysOfWeek_00200, Function | SmallTest | Level1) +{ + uint8_t arr[] = {1, 7}; + std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); + auto rrc = std::make_shared(0, 0, daysOfWeek); + EXPECT_TRUE(rrc->GetRepeatDay() == 65) << "repeatDays (1, 12) should be 65"; +} + +/** + * @tc.number : initDaysOfWeek_00300 + * @tc.name : + * @tc.desc : test set daysOfWeek with duplicate value. + */ +HWTEST_F(ReminderRequestAlarmTest, initDaysOfWeek_00300, Function | SmallTest | Level1) +{ + uint8_t arr[] = {1, 1, 5, 5, 7, 7, 7}; + std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); + auto rrc = std::make_shared(0, 0, daysOfWeek); + EXPECT_TRUE(rrc->GetRepeatDay() == 81) << "repeatDays (1, 1, 5 12) should be 81"; +} + +/** + * @tc.number : initDaysOfWeek_00400 + * @tc.name : + * @tc.desc : test set daysOfWeek exceeding maximum length. + */ +HWTEST_F(ReminderRequestAlarmTest, initDaysOfWeek_00400, Function | SmallTest | Level1) +{ + uint8_t arr[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; + std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); + try { + auto rrc = std::make_shared(0, 0, daysOfWeek); + EXPECT_TRUE(false) << "repeatDays exceeding maximum length should throw exception"; + } catch (const std::invalid_argument &e) { + EXPECT_TRUE(true); + } +} + +/** + * @tc.number : initDaysOfWeek_00500 + * @tc.name : + * @tc.desc : test set daysOfWeek with null value. + */ +HWTEST_F(ReminderRequestAlarmTest, initDaysOfWeek_00500, Function | SmallTest | Level1) +{ + uint8_t arr[] = {}; + std::vector daysOfWeek (arr, arr + sizeof(arr) / sizeof(uint8_t)); + auto rrc = std::make_shared(0, 0, daysOfWeek); + uint8_t expectedVal = 0; + EXPECT_TRUE(rrc->GetRepeatDay() == expectedVal) << "repeatDays () should be 0"; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..77c61bb7ba59033d1aa27656536fb02033418a4e --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp @@ -0,0 +1,324 @@ +/* + * 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 "ans_log_wrapper.h" +#include "reminder_request_calendar.h" +#include "reminder_helper.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class ReminderRequestCalendarTest : public testing::Test { +public: + static void SetUpTestCase() + { + ReminderHelper::CancelAllReminders(); + } + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() + { + ReminderHelper::CancelAllReminders(); + } + + std::shared_ptr CreateCalendar(tm &nowTime) + { + time_t now; + (void)time(&now); // unit is seconds. + tm *tmp = localtime(&now); + if (tmp == nullptr) { + return nullptr; + } + nowTime = *tmp; + nowTime.tm_year = 0; + nowTime.tm_mon = 0; + nowTime.tm_mday = 1; + nowTime.tm_hour = 1; + nowTime.tm_min = 1; + std::vector repeatMonths; + std::vector repeatDays; + repeatMonths.push_back(1); + repeatDays.push_back(1); + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + return calendar; + } + + bool IsVectorEqual(std::vector &vectorA, std::vector &vectorB) + { + if (vectorA.size() != vectorB.size()) { + return false; + } + if (vectorA.size() == 0) { + return true; + } + auto vitA = vectorA.begin(); + auto vitB = vectorB.begin(); + while (vitA != vectorA.end()) { + if (*vitA != *vitB) { + return false; + } + ++vitA; + ++vitB; + } + return true; + } +}; + +/** + * @tc.number : initDateTime_00100 + * @tc.name : + * @tc.desc : Check firstDesignateYear set successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00100, Function | SmallTest | Level1) +{ + struct tm nowTime; + auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); + if (calendar == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + int firstDesignateYear = calendar->GetActualTime(ReminderRequest::TimeTransferType::YEAR, nowTime.tm_year); + EXPECT_TRUE(firstDesignateYear == calendar->GetFirstDesignateYear()) << "Set first designate year error."; +} + +/** + * @tc.number : initDateTime_00200 + * @tc.name : + * @tc.desc : Check firstDesignateMonth set successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00200, Function | SmallTest | Level1) +{ + struct tm nowTime; + auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); + if (calendar == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + int firstDesignateMonth = calendar->GetActualTime(ReminderRequest::TimeTransferType::MONTH, nowTime.tm_mon); + EXPECT_TRUE(firstDesignateMonth == calendar->GetFirstDesignageMonth()) << "Set first designate month error."; +} + +/** + * @tc.number : initDateTime_00300 + * @tc.name : + * @tc.desc : Check firstDesignateDay set successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00300, Function | SmallTest | Level1) +{ + struct tm nowTime; + auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); + if (calendar == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + int firstDesignateDay = nowTime.tm_mday; + EXPECT_TRUE(firstDesignateDay == calendar->GetFirstDesignateDay()) << "Set first designate day error."; +} + +/** + * @tc.number : initDateTime_00400 + * @tc.name : + * @tc.desc : Check repeatMonth set with normal value successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00400, Function | SmallTest | Level1) +{ + time_t now; + (void)time(&now); // unit is seconds. + tm *tmp = localtime(&now); + if (tmp == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + struct tm nowTime = *tmp; + + std::vector repeatMonths; + std::vector repeatDays; + repeatMonths.push_back(1); + repeatDays.push_back(1); + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + std::vector actualRepeatMonths = calendar->GetRepeatMonths(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatMonths, actualRepeatMonths)) + << "Set repeat month with 1 error."; + + repeatMonths.clear(); + repeatMonths.push_back(12); + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatMonths = calendar->GetRepeatMonths(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatMonths, actualRepeatMonths)) + << "Set repeat month with 12 error."; + + repeatMonths.clear(); + for (uint8_t i = 1; i <= 12; i++) { + repeatMonths.push_back(i); + } + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatMonths = calendar->GetRepeatMonths(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatMonths, actualRepeatMonths)) + << "Set repeat month with 1~12 error."; +} + +/** + * @tc.number : initDateTime_00500 + * @tc.name : + * @tc.desc : Check repeatMonth set with exception value successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00500, Function | SmallTest | Level1) +{ + time_t now; + time(&now); // unit is seconds. + tm *tmp = localtime(&now); + if (tmp == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + tm nowTime = *tmp; + nowTime.tm_year += 1; + std::vector repeatMonths; + std::vector repeatDays; + repeatMonths.push_back(-1); + repeatDays.push_back(1); + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + std::vector actualRepeatMonths = calendar->GetRepeatMonths(); + EXPECT_TRUE(actualRepeatMonths.size() == 0) << "Set repeat month with -1 error."; + + repeatMonths.clear(); + repeatMonths.push_back(13); + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatMonths = calendar->GetRepeatMonths(); + EXPECT_TRUE(actualRepeatMonths.size() == 0) << "Set repeat month with 13 error."; + + for (uint8_t i = 1; i <= 12; i++) { + repeatMonths.push_back(i); + } + repeatMonths.push_back(1); + try { + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + EXPECT_TRUE(false) << "length of repeat month > 12 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("length of repeat month > 12 throw exception."); + } +} + +/** + * @tc.number : initDateTime_00600 + * @tc.name : + * @tc.desc : Check repeatDay set with nomal value successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00600, Function | SmallTest | Level1) +{ + time_t now; + (void)time(&now); // unit is seconds. + tm *tmp = localtime(&now); + if (tmp == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + tm nowTime = *tmp; + std::vector repeatMonths; + std::vector repeatDays; + repeatMonths.push_back(1); + repeatDays.push_back(1); + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + std::vector actualRepeatDays = calendar->GetRepeatDays(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatDays, actualRepeatDays)) + << "Set repeat day with 1 error."; + + repeatDays.clear(); + repeatDays.push_back(31); + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatDays = calendar->GetRepeatDays(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatDays, actualRepeatDays)) + << "Set repeat day with 31 error."; + + repeatDays.clear(); + for (uint8_t i = 1; i <= 31; i++) { + repeatDays.push_back(i); + } + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatDays = calendar->GetRepeatDays(); + EXPECT_TRUE(ReminderRequestCalendarTest::IsVectorEqual(repeatDays, actualRepeatDays)) + << "Set repeat day with 1~31 error."; +} + +/** + * @tc.number : initDateTime_00700 + * @tc.name : + * @tc.desc : Check repeatDay set with exception value successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00700, Function | SmallTest | Level1) +{ + time_t now; + (void)time(&now); // unit is seconds. + tm *tmp = localtime(&now); + if (tmp == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + tm nowTime = *tmp; + nowTime.tm_year += 1; + std::vector repeatMonths; + std::vector repeatDays; + repeatMonths.push_back(-1); + repeatDays.push_back(-1); + auto calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + std::vector actualRepeatDays = calendar->GetRepeatDays(); + EXPECT_TRUE(actualRepeatDays.size() == 0) << "Set repeat day with -1 error."; + + repeatDays.clear(); + repeatDays.push_back(32); + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + actualRepeatDays = calendar->GetRepeatDays(); + EXPECT_TRUE(actualRepeatDays.size() == 0) << "Set repeat day with 32 error."; + + repeatDays.clear(); + for (uint8_t i = 1; i <= 31; i++) { + repeatDays.push_back(i); + } + repeatDays.push_back(1); + try { + calendar = std::make_shared(nowTime, repeatMonths, repeatDays); + ANSR_LOGI("length of repeat month > 32 should throw exception."); + } catch (const std::invalid_argument &e) { + ANSR_LOGI("length of repeat month > 32 throw exception."); + } +} + +/** + * @tc.number : initDateTime_00800 + * @tc.name : + * @tc.desc : Check hour set successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00800, Function | SmallTest | Level1) +{ + struct tm nowTime; + auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); + if (calendar == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + EXPECT_TRUE(1 == calendar->GetHour()) << "Set hour error."; +} + +/** + * @tc.number : initDateTime_00900 + * @tc.name : + * @tc.desc : Check minut set successfully. + */ +HWTEST_F(ReminderRequestCalendarTest, initDateTime_00900, Function | SmallTest | Level1) +{ + struct tm nowTime; + auto calendar = ReminderRequestCalendarTest::CreateCalendar(nowTime); + if (calendar == nullptr) { + EXPECT_TRUE(false) << "calendar is null"; + } + EXPECT_TRUE(1 == calendar->GetMinute()) << "Set minute error."; + EXPECT_TRUE(0 == calendar->GetSecond()) << "Set seconds error."; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/test/unittest/reminder_request_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1f189e9f55060ad7f53a7217e90b21a0d43b694d --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_test.cpp @@ -0,0 +1,293 @@ +/* + * 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 "reminder_request.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class ReminderRequestChild : public ReminderRequest { +public: + ReminderRequestChild() : ReminderRequest() {}; +}; + +class ReminderRequestTest : public testing::Test { +public: + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} + + static const uint8_t REMINDER_STATUS_SHOWING; +}; + +const uint8_t ReminderRequestTest::REMINDER_STATUS_SHOWING = 4; + +/** + * @tc.number : CanRemove_00100 + * @tc.name : + * @tc.desc : When reminder init, CanRemove should return true. + */ +HWTEST_F(ReminderRequestTest, CanRemove_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + EXPECT_TRUE(rrc->CanRemove()) << "When init, canRemove should be false"; +} + +/** + * @tc.number : CanRemove_00200 + * @tc.name : + * @tc.desc : When reminder is shown, CanRemove should return false. + */ +HWTEST_F(ReminderRequestTest, CanRemove_00200, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnShow(false, false, true); + EXPECT_FALSE(rrc->CanRemove()) << "When shown, canRemove should be false"; +} + +/** + * @tc.number : CanRemove_00300 + * @tc.name : + * @tc.desc : When reminder close, CanRemove should return true. + */ +HWTEST_F(ReminderRequestTest, CanRemove_00300, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnShow(false, false, true); + rrc->OnClose(false); + EXPECT_TRUE(rrc->CanRemove()) << "When reminder is expired and closed, can remove should be false"; +} + +/** + * @tc.number : CanRemove_00400 + * @tc.name : + * @tc.desc : When reminder is covered as same notification id, CanRemove should return true. + */ +HWTEST_F(ReminderRequestTest, CanRemove_00400, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnShow(false, false, true); + rrc->OnSameNotificationIdCovered(); + EXPECT_TRUE(rrc->CanRemove()) << "When reminder is expired and covered by \ + sameNotification id, can remove should be true"; +} + +/** + * @tc.number : StateCheck_00100 + * @tc.name : + * @tc.desc : When reminder init, state should be 0. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + EXPECT_EQ(rrc->GetState(), 0) << "When init, state should be 0"; +} + +/** + * @tc.number : StateCheck_00200 + * @tc.name : + * @tc.desc : When reminder close with param true, state REMINDER_STATUS_SHOWING should be unset. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00200, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnClose(true); + EXPECT_TRUE((rrc->GetState() & ReminderRequestTest::REMINDER_STATUS_SHOWING) == 0); +} + +/** + * @tc.number : StateCheck_00300 + * @tc.name : + * @tc.desc : When reminder close with param false, state REMINDER_STATUS_SHOWING should be unset. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00300, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnClose(false); + EXPECT_TRUE((rrc->GetState() & ReminderRequestTest::REMINDER_STATUS_SHOWING) == 0); +} + +/** + * @tc.number : StateCheck_00400 + * @tc.name : + * @tc.desc : When reminder is covered as same notification id, state REMINDER_STATUS_SHOWING should be unset. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00400, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnSameNotificationIdCovered(); + EXPECT_TRUE((rrc->GetState() & ReminderRequestTest::REMINDER_STATUS_SHOWING) == 0); +} + +/** + * @tc.number : StateCheck_00500 + * @tc.name : + * @tc.desc : When reminder is shown with param true,true, state REMINDER_STATUS_SHOWING should be set. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00500, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnShow(false, true, true); + EXPECT_TRUE((rrc->GetState() & ReminderRequestTest::REMINDER_STATUS_SHOWING) != 0); +} + +/** + * @tc.number : StateCheck_00600 + * @tc.name : + * @tc.desc : When reminder is shown with param false,true, state REMINDER_STATUS_SHOWING should be set. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00600, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->OnShow(false, false, true); + EXPECT_TRUE((rrc->GetState() & ReminderRequestTest::REMINDER_STATUS_SHOWING) != 0); +} + +/** + * @tc.number : StateCheck_00700 + * @tc.name : + * @tc.desc : When reminder is shown with param true,false, state REMINDER_STATUS_SHOWING should not change. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00700, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + uint8_t stateBefore = rrc->GetState(); + rrc->OnShow(false, true, false); + EXPECT_EQ(rrc->GetState(), stateBefore); +} + +/** + * @tc.number : StateCheck_00800 + * @tc.name : + * @tc.desc : When reminder is shown with param false,false, state REMINDER_STATUS_SHOWING should be unset. + */ +HWTEST_F(ReminderRequestTest, StateCheck_00800, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + uint8_t stateBefore = rrc->GetState(); + rrc->OnShow(false, false, false); + EXPECT_EQ(rrc->GetState(), stateBefore); +} + +/** + * @tc.number : initReminderId_00100 + * @tc.name : + * @tc.desc : When reminder create successfully, system should assign unique id to reminder. + */ +HWTEST_F(ReminderRequestTest, initReminderId_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + rrc->InitReminderId(); + int32_t reminderIdBefore = rrc->GetReminderId(); + rrc->InitReminderId(); + int32_t reminderIdAfter = rrc->GetReminderId(); + EXPECT_EQ((reminderIdAfter - reminderIdBefore), 1); +} + +/** + * @tc.number : setContent_00100 + * @tc.name : + * @tc.desc : Test SetContent with normal parameters. + */ +HWTEST_F(ReminderRequestTest, setContent_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is normal content"; + rrc->SetContent(content); + EXPECT_EQ(rrc->GetContent(), content); +} + +/** + * @tc.number : setContent_00200 + * @tc.name : + * @tc.desc : Test SetContent parameters with special characters. + */ +HWTEST_F(ReminderRequestTest, setContent_00200, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is content with special characters: ~!@#$%^&*()-+"; + rrc->SetContent(content); + EXPECT_EQ(rrc->GetContent(), content); +} + +/** + * @tc.number : setExpiredContent_00100 + * @tc.name : + * @tc.desc : Test SetExpiredContent with normal parameters. + */ +HWTEST_F(ReminderRequestTest, setExpiredContent_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is normal content"; + rrc->SetExpiredContent(content); + EXPECT_EQ(rrc->GetExpiredContent(), content); +} + +/** + * @tc.number : setExpiredContent_00200 + * @tc.name : + * @tc.desc : Test SetExpiredContent with special characters. + */ +HWTEST_F(ReminderRequestTest, setExpiredContent_00200, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is content with special characters: ~!@#$%^&*()-+"; + rrc->SetExpiredContent(content); + EXPECT_EQ(rrc->GetExpiredContent(), content); +} + +/** + * @tc.number : setTitle_00100 + * @tc.name : + * @tc.desc : Test SetTitle with normal parameters. + */ +HWTEST_F(ReminderRequestTest, setTitle_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is normal content"; + rrc->SetTitle(content); + EXPECT_EQ(rrc->GetTitle(), content); +} + +/** + * @tc.number : setTitle_00200 + * @tc.name : + * @tc.desc : Test SetTitle with special characters. + */ +HWTEST_F(ReminderRequestTest, setTitle_00200, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + std::string content = "this is content with special characters: ~!@#$%^&*()-+"; + rrc->SetTitle(content); + EXPECT_EQ(rrc->GetTitle(), content); +} + +/** + * @tc.number : setNotificationId_00100 + * @tc.name : + * @tc.desc : Test SetNotificationId parameters. + */ +HWTEST_F(ReminderRequestTest, setNotificationId_00100, Function | SmallTest | Level1) +{ + auto rrc = std::make_shared(); + int32_t notificationId = 0; + rrc->SetNotificationId(notificationId); + EXPECT_EQ(rrc->GetNotificationId(), notificationId); +} +} +} \ No newline at end of file diff --git a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6b39c09bf034b89774c8e488712ecabe947a06e2 --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp @@ -0,0 +1,91 @@ +/* + * 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 "ans_log_wrapper.h" +#include "reminder_request_timer.h" +#include "reminder_helper.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class ReminderRequestTimerTest : public testing::Test { +public: + static void SetUpTestCase() + { + ReminderHelper::CancelAllReminders(); + } + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() + { + ReminderHelper::CancelAllReminders(); + } +}; + +/** + * @tc.number : initCountDownTime_00100 + * @tc.name : + * @tc.desc : set countDownTime = 0 should throw exception. + */ +HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00100, Function | SmallTest | Level1) +{ + try { + uint64_t countDownTimeInSeconds = 0; + auto rrc = std::make_shared(countDownTimeInSeconds); + EXPECT_TRUE(false) << "countDownTime < 0 should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("countDownTime < 0 throw exception."); + } +} + +/** + * @tc.number : initCountDownTime_00200 + * @tc.name : + * @tc.desc : set countDownTime > (UINT64_MAX / 1000) should throw exception. + */ +HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00200, Function | SmallTest | Level1) +{ + try { + auto rrc = std::make_shared(UINT64_MAX / 1000); + EXPECT_TRUE(false) << "countDownTime >= (UINT64_MAX / 1000) should throw exception."; + } catch (const std::invalid_argument &e) { + ANSR_LOGI("countDownTime > (UINT64_MAX / 1000) throw exception."); + } +} + + +/** + * @tc.number : initCountDownTime_00300 + * @tc.name : + * @tc.desc : set countDownTime with normal value. + */ +HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00300, Function | SmallTest | Level1) +{ + uint64_t countDownTimeInSeconds = 1; + auto rrc = std::make_shared(countDownTimeInSeconds); + EXPECT_TRUE(rrc->GetInitInfo() == 1) << "countDownTime is not 1"; + + countDownTimeInSeconds = 10; + auto rrc2 = std::make_shared(countDownTimeInSeconds); + EXPECT_TRUE(rrc2->GetInitInfo() == 10) << "countDownTime is not 10"; + + countDownTimeInSeconds = 100; + auto rrc3 = std::make_shared(countDownTimeInSeconds); + EXPECT_TRUE(rrc3->GetInitInfo() == 100) << "countDownTime is not 1"; +} +} +} \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn old mode 100755 new mode 100644 index 0912b06463a8454cbffbbc780d211e78e76b45f0..c8c3a48de71cd7facbd8e40994ef2f22b324c4c7 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -22,11 +22,7 @@ config("public_ans_config") { "${core_path}/common/include", "//utils/native/base/include", "${services_path}/ans/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", "${core_path}/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content/", ] } @@ -38,22 +34,12 @@ ohos_moduletest("ans_fw_module_test") { "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/libs/libeventhandler/src", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//utils/native/base/include", "//utils/system/safwk/native/include", "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", - "//foundation/communication/utils/include", - "//foundation/communication/ipc/ipc/native/src/core/include", - "//foundation/communication/ipc/utils/include", - "//foundation/communication/ipc/ipc/softbus_temp", "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", - "//foundation/distributedschedule/samgr/services/samgr/native/include", - "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", - "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", "${core_path}/common/include", @@ -63,23 +49,17 @@ ohos_moduletest("ans_fw_module_test") { "//utils/native/base/include", "//third_party/jsoncpp/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils/", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log/", ] sources = [ - "//base/notification/ans_standard/frameworks/ans/core/src/ans_manager_proxy.cpp", - "//base/notification/ans_standard/frameworks/ans/core/src/ans_manager_stub.cpp", - "//base/notification/ans_standard/frameworks/ans/core/src/ans_notification.cpp", - "//base/notification/ans_standard/frameworks/ans/core/src/ans_subscriber_proxy.cpp", - "//base/notification/ans_standard/frameworks/ans/core/src/ans_subscriber_stub.cpp", - "//base/notification/ans_standard/frameworks/ans/native/src/notification.cpp", "ans_fw_module_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_change_notification.cpp", + "mock/mock_common_event_data.cpp", + "mock/mock_common_event_manager.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", ] @@ -91,29 +71,30 @@ ohos_moduletest("ans_fw_module_test") { "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", "${services_path}/ans:libans", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", - "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -124,6 +105,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { module_out_path = module_output_path include_dirs = [ "include", + "${core_path}/include", "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", @@ -131,28 +113,17 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//utils/system/safwk/native/include", "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", - "//foundation/communication/utils/include", - "//foundation/communication/ipc/ipc/native/src/core/include", - "//foundation/communication/ipc/utils/include", - "//foundation/communication/ipc/ipc/softbus_temp", - "//foundation/distributedschedule/samgr/services/samgr/native/include", - "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", - "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", "${core_path}/common/include", "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", + "//third_party/jsoncpp/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", - "//foundation/multimedia/image_standard/interfaces/innerkits/include", - "//developtools/bytrace_standard/interfaces/innerkits/native/include", ] sources = [ @@ -161,40 +132,47 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_change_notification.cpp", + "mock/mock_common_event_data.cpp", + "mock/mock_common_event_manager.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", ] configs = [ "//utils/native/base:utils_config" ] + ldflags = [ "-Wl,-rpath=/system/lib/module/multimedia/" ] + deps = [ "${frameworks_path}/ans/core:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", "${services_path}/ans:libans", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -205,6 +183,7 @@ ohos_moduletest("ans_innerkits_module_slot_test") { module_out_path = module_output_path include_dirs = [ "include", + "${core_path}/include", "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", @@ -212,27 +191,17 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "//utils/system/safwk/native/include", "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", - "//foundation/communication/utils/include", - "//foundation/communication/ipc/ipc/native/src/core/include", - "//foundation/communication/ipc/utils/include", - "//foundation/communication/ipc/ipc/softbus_temp", - "//foundation/distributedschedule/samgr/services/samgr/native/include", - "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", - "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", "${core_path}/common/include", "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", + "//third_party/jsoncpp/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", - "//developtools/bytrace_standard/interfaces/innerkits/native/include", ] sources = [ @@ -241,6 +210,9 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_change_notification.cpp", + "mock/mock_common_event_data.cpp", + "mock/mock_common_event_manager.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", ] @@ -252,27 +224,30 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", "${services_path}/ans:libans", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -283,6 +258,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { module_out_path = module_output_path include_dirs = [ "include", + "${core_path}/include", "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", @@ -290,27 +266,17 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "//utils/system/safwk/native/include", "//base/notification/ans_standard/services/ans/include", "//third_party/json/include", - "//foundation/communication/utils/include", - "//foundation/communication/ipc/ipc/native/src/core/include", - "//foundation/communication/ipc/utils/include", - "//foundation/communication/ipc/ipc/softbus_temp", - "//foundation/distributedschedule/samgr/services/samgr/native/include", - "//foundation/communication/ipc/interfaces/innerkits/libdbinder/include", - "//base/notification/ces_standard/cesfwk/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/test/moduletest/mock/include", + "//base/notification/ces_standard/interfaces/innerkits/native/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", + "//base/notification/ans_standard/interfaces/innerkits/wantagent/include", "${core_path}/common/include", "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", "//utils/native/base/include", + "//third_party/jsoncpp/include", "//base/notification/ans_standard/frameworks/ans/test/moduletest/mock/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", - "//developtools/bytrace_standard/interfaces/innerkits/native/include", ] sources = [ @@ -319,6 +285,9 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager.cpp", "mock/mock_bundle_mgr_proxy.cpp", + "mock/mock_change_notification.cpp", + "mock/mock_common_event_data.cpp", + "mock/mock_common_event_manager.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", ] @@ -330,38 +299,49 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", "${services_path}/ans:libans", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" part_name = "ans_standard" } +ohos_js_unittest("ReminderAgentJsTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + group("moduletest") { testonly = true deps = [] deps += [ + ":ReminderAgentJsTest", ":ans_fw_module_test", ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", diff --git a/frameworks/ans/test/moduletest/ReminderHelperTest.js b/frameworks/ans/test/moduletest/ReminderHelperTest.js new file mode 100644 index 0000000000000000000000000000000000000000..c61a047ec7d76b6643b13bf07e59379476698fd2 --- /dev/null +++ b/frameworks/ans/test/moduletest/ReminderHelperTest.js @@ -0,0 +1,889 @@ +/* + * 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 reminderAgent from '@ohos.reminderAgent'; + + +import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from 'deccjsunit/index' + +describe("ReminderHelperTest", function () { + beforeAll(function() { + /* + * @tc.setup: setup invoked before all testcases + */ + console.info('beforeAll caled') + }) + + afterAll(function() { + /* + * @tc.teardown: teardown invoked after all testcases + */ + console.info('afterAll caled') + }) + + beforeEach(function() { + /* + * @tc.setup: setup invoked before each testcases + */ + console.info('beforeEach caled') + }) + + afterEach(function() { + /* + * @tc.teardown: teardown invoked after each testcases + */ + console.info('afterEach caled') + reminderAgent.cancelAllReminders(); + }) + + /* + * @tc.name: testReminderHelper001 + * @tc.desc: test publishReminder can return correct reminder id. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper001", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + let expectId = -1; + reminderAgent.publishReminder(timer).then((reminderId) => { + expectId = reminderId + 1; + reminderAgent.publishReminder(timer).then((reminderId) => { + if (reminderId === expectId){ + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + } + }, (error) => { + expect(false).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }); + }); + }) + + /* + * @tc.name: testReminderHelper002 + * @tc.desc: test publishReminder can return correct reminder id. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper002", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + let expectId = -1; + function reminderCallback(err, reminderId) { + expect(reminderId).assertEqual(expectId); + } + reminderAgent.publishReminder(timer, (err, reminderId) => { + expectId = reminderId + 1; + reminderAgent.publishReminder(timer, reminderCallback); + }) + done(); + }) + + /* + * @tc.name: testReminderHelper003 + * @tc.desc: test addNotificationSlot instance with null + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper003", 0, async function (done) { + function reminderCallback(err, data) { + let i = 0; + expect(0).assertEqual(i); + } + reminderAgent.addNotificationSlot(0, reminderCallback); + done(); + }) + + /* + * @tc.name: testReminderHelper004 + * @tc.desc: test addNotificationSlot instance with null + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper004", 0, async function (done) { + let mySlot = null; + let promise = new Promise((resolve, reject) => { + reminderAgent.addNotificationSlot(mySlot).then(() => { + resolve(); + }) + reject(); + }); + promise.then(() => { + }, err => { + let i = 0; + expect(0).assertEqual(i); + }).catch(res => {}); + done(); + }) + + /* + * @tc.name: testReminderHelper005 + * @tc.desc: test addNotificationSlot with normal value + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper005", 0, async function (done) { + let mySlot = { + type: 2 + } + reminderAgent.addNotificationSlot(mySlot).then(() => { + let i = 0; + expect(i).assertEqual(0); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper006 + * @tc.desc: test addNotificationSlot with normal value + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper006", 0, async function (done) { + reminderAgent.addNotificationSlot(3, (err, data) => { + let i = 0; + expect(i).assertEqual(0); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper007 + * @tc.desc: test cancelAllReminders can cancel all exist reminders + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper007", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + } + } + reminderAgent.publishReminder(timer).then((reminderId) => {}); + reminderAgent.publishReminder(calendar).then((reminderId) => {}); + setTimeout(() => { + reminderAgent.cancelAllReminders().then(() => { + reminderAgent.getValidReminders().then((reminders) => { + expect(reminders.length === 0).assertEqual(true); + }); + }); + }, 5000); + done(); + }) + + /* + * @tc.name: testReminderHelper008 + * @tc.desc: test cancelAllReminders can cancel all exist reminders + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper008", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + } + } + reminderAgent.publishReminder(timer).then((reminderId) => {}); + reminderAgent.publishReminder(calendar).then((reminderId) => {}); + setTimeout(() => { + reminderAgent.cancelAllReminders((err, data) => { + reminderAgent.getValidReminders().then((reminders) => { + expect(reminders.length === 0).assertEqual(true); + }); + }); + }, 5000); + done(); + }) + + /* + * @tc.name: testReminderHelper009 + * @tc.desc: test cancelReminder with not exit reminder. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper009", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + let id = 1; + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(timer).then(() => { + reminderAgent.getValidReminders().then((reminders) => { + publishlength=reminders.length + reminderAgent.cancelReminder(id).then(() => { + reminderAgent.getValidReminders().then((reminders) => { + cancellength = reminders.length + firstdiff = publishlength - cancellength; + expect(0).assertEqual(firstdiff); + }); + }); + }); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper010 + * @tc.desc: test cancelReminder with not exit reminder. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper010", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(timer).then(() => { + reminderAgent.getValidReminders((err, reminders) => { + publishlength = reminders.length; + reminderAgent.cancelReminder(0, (err, data)=>{ + reminderAgent.getValidReminders((err, reminders) => { + cancellength = reminders.length; + firstdiff = publishlength - cancellength; + expect(0).assertEqual(firstdiff); + }); + }); + }); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper011 + * @tc.desc: test cancelReminder with exist reminder. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper011", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(alarm, (err, reminderId) => { + reminderAgent.getValidReminders((err, reminders) => { + publishlength = reminders.length; + }); + setTimeout(() => { + reminderAgent.cancelReminder(reminderId, (err, data) => { + reminderAgent.getValidReminders((err, reminders) => { + cancellength = reminders.length; + firstdiff = publishlength - cancellength; + if (firstdiff === 0) { + expect(0).assertEqual(firstdiff); + } else if (firstdiff === 1) { + expect(1).assertEqual(firstdiff); + } + }); + }); + }, 1000); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper012 + * @tc.desc: test cancelReminder with exist reminder. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper012", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(alarm, (err, reminderId) => { + reminderAgent.getValidReminders((err, reminders) => { + publishlength = reminders.length; + }); + setTimeout(() => { + reminderAgent.cancelReminder(reminderId).then(() => { + reminderAgent.getValidReminders((err, reminders) => { + cancellength = reminders.length; + firstdiff = publishlength - cancellength; + if (firstdiff === 0) { + expect(0).assertEqual(firstdiff); + } else if (firstdiff === 1) { + expect(1).assertEqual(firstdiff); + } + }); + }); + }, 1000); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper013 + * @tc.desc: test getValidReminders, verify all the information is correct. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper013", 0, async function (done) { + var alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + var timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + reminderAgent.cancelAllReminders((err, data) => { + reminderAgent.publishReminder(timer, (error, reminderId) => {}); + reminderAgent.publishReminder(alarm, (error, reminderId) => {}); + setTimeout(() => { + reminderAgent.getValidReminders().then((reminders) => { + expect(reminders.length).assertEqual(2); + }); + }, 1000); + }) + done(); + }) + + /* + * @tc.name: testReminderHelper014 + * @tc.desc: test getValidReminders, verify all the information is correct. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper014", 0, async function (done) { + var alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + var timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + reminderAgent.cancelAllReminders((err, data) => { + reminderAgent.publishReminder(timer, (error, reminderId) => {}); + reminderAgent.publishReminder(alarm, (error, reminderId) => {}); + setTimeout(() => { + reminderAgent.getValidReminders((err, reminders) => { + expect(reminders.length).assertEqual(2); + }); + }, 1000); + }) + done(); + }) + + /* + * @tc.name: testReminderHelper015 + * @tc.desc: test removeNotificationSlot with not exist slot. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper015", 0, function (done) { + function reminderCallback(err, data){ + let i = 0; + expect(0).assertEqual(i); + } + reminderAgent.removeNotificationSlot(0, reminderCallback); + done(); + }) + + /* + * @tc.name: testReminderHelper016 + * @tc.desc: test removeNotificationSlot with not exist slot. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper016", 0, function (done) { + let promise = new Promise((resolve, reject) => { + reminderAgent.removeNotificationSlot(1).then(() => { + resolve(); + }); + reject(); + }); + promise.then(() => { + }, err => { + let i = 0; + expect(0).assertEqual(i); + }).catch(res => {}); + done(); + }) + + /* + * @tc.name: testReminderHelper017 + * @tc.desc: test removeNotificationSlot with exist slot. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper017", 0, async function (done) { + var tarRemoveSlot = { + type: 1 + } + reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { + reminderAgent.removeNotificationSlot(tarRemoveSlot.type, (err, data) => { + expect(0).assertEqual(err.code); + }); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper018 + * @tc.desc: test removeNotificationSlot with exist slot. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper018", 0, async function (done) { + var tarRemoveSlot = { + type: 1 + } + reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { + reminderAgent.removeNotificationSlot(tarRemoveSlot.type).then(() => { + let i = 0; + expect(0).assertEqual(i); + }); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper019 + * @tc.desc: test getValidReminders. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper019", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + reminderAgent.publishReminder(timer).then((reminderId) => { }); + setTimeout(() => { + reminderAgent.getValidReminders().then((reminders) => { + expect(reminders.length === 0).assertEqual(true); + }); + }, 5000); + done(); + }) + + /* + * @tc.name:testReminderHelper020 + * @tc.desc: test getValidReminders. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper020", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 3 + } + reminderAgent.publishReminder(timer, (err, data) => { }); + setTimeout(() => { + reminderAgent.getValidReminders((err, reminders) => { + expect(reminders.length === 0).assertEqual(true); + }); + }, 5000); + done(); + }) + + /* + * @tc.name: testReminderHelper021 + * @tc.desc: test publishReminder a normal alarm. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper021", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + reminderAgent.publishReminder(alarm).then((reminderId) => { + let i = 0; + expect(i).assertEqual(0); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper022 + * @tc.desc: test publishReminder a normal alarm. + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper022", 0, async function (done) { + let alarm = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, + hour: 21, + minute: 14, + title: "this is title", + content: "this is content" + } + function reminderCallback (err, reminderId) { + let i = 0; + expect(i).assertEqual(0); + } + reminderAgent.publishReminder(alarm, reminderCallback); + done(); + }) + + /* + * @tc.name: testReminderHelper023 + * @tc.desc: test publishReminder + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper023", 0, function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + }, + repeatMonths:[2], + repeatDays:[2], + actionButton:[ + { + title:"close", + type:0 + }, + { + title:"snooze", + type:1 + } + ], + wantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + maxScreenWantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + ringDuration:5, + snoozeTimes:2, + timeInterval:5, + title:"this is title", + content:"this is content", + expiredContent:"this reminder has expired", + snoozeContent:"remind later", + notificationId:100, + slotType:3 + } + reminderAgent.publishReminder(calendar).then((reminderId) => { + reminderAgent.getValidReminders().then((reminders) => { + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + JSON.stringify(reminders[i])); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + expect(reminders[i].ringDuration).assertEqual(5); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + expect(reminders[i].snoozeTimes).assertEqual(2); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + expect(reminders[i].title).assertEqual("this is title"); + console.log("getValidReminders, title = " + reminders[i].title); + expect(reminders[i].content).assertEqual("this is content"); + console.log("getValidReminders, content = " + reminders[i].content); + expect(reminders[i].expiredContent).assertEqual("this reminder has expired"); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + expect(reminders[i].snoozeContent).assertEqual("remind later"); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + expect(reminders[i].notificationId).assertEqual(100); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } + }) + }); + done(); + }) + + /* + * @tc.name: testReminderHelper024 + * @tc.desc: test publishReminder + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper024", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + }, + repeatMonths:[2], + repeatDays:[2], + actionButton:[ + { + title:"close", + type:0 + }, + { + title:"snooze", + type:1 + } + ], + wantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + maxScreenWantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + ringDuration:5, + snoozeTimes:2, + timeInterval:5, + title:"this is title", + content:"this is content", + expiredContent:"this reminder has expired", + snoozeContent:"remind later", + notificationId:100, + slotType:3 + } + reminderAgent.publishReminder(calendar, (err,reminderId) => { + reminderAgent.getValidReminders().then((reminders) => { + for (let i = 0; i < reminders.length; i++) { + console.log("getValidReminders = " + JSON.stringify(reminders[i])); + console.log("getValidReminders, reminderType = " + reminders[i].reminderType); + for (let j = 0; j < reminders[i].actionButton.length; j++) { + console.log("getValidReminders, actionButton.title = " + reminders[i].actionButton[j].title); + console.log("getValidReminders, actionButton.type = " + reminders[i].actionButton[j].type); + } + console.log("getValidReminders, wantAgent.pkgName = " + reminders[i].wantAgent.pkgName); + console.log("getValidReminders, wantAgent.abilityName = " + reminders[i].wantAgent.abilityName); + console.log("getValidReminders, maxScreenWantAgent.pkgName = " + reminders[i].maxScreenWantAgent.pkgName); + console.log("getValidReminders, maxScreenWantAgent.abilityName = " + reminders[i].maxScreenWantAgent.abilityName); + expect(reminders[i].ringDuration).assertEqual(5); + console.log("getValidReminders, ringDuration = " + reminders[i].ringDuration); + expect(reminders[i].snoozeTimes).assertEqual(2); + console.log("getValidReminders, snoozeTimes = " + reminders[i].snoozeTimes); + console.log("getValidReminders, timeInterval = " + reminders[i].timeInterval); + expect(reminders[i].title).assertEqual("this is title"); + console.log("getValidReminders, title = " + reminders[i].title); + expect(reminders[i].content).assertEqual("this is content"); + console.log("getValidReminders, content = " + reminders[i].content); + expect(reminders[i].expiredContent).assertEqual("this reminder has expired"); + console.log("getValidReminders, expiredContent = " + reminders[i].expiredContent); + expect(reminders[i].snoozeContent).assertEqual("remind later"); + console.log("getValidReminders, snoozeContent = " + reminders[i].snoozeContent); + expect(reminders[i].notificationId).assertEqual(100); + console.log("getValidReminders, notificationId = " + reminders[i].notificationId); + console.log("getValidReminders, slotType = " + reminders[i].slotType); + } + }) + }); + done(); + }) + + /* + * @tc.name: testReminderHelper025 + * @tc.desc: test publishReminder + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper025", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + }, + repeatMonths:[2], + repeatDays:[2], + actionButton:[ + { + title:"close", + type:0 + }, + { + title:"snooze", + type:1 + } + ], + wantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + maxScreenWantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + ringDuration:5, + snoozeTimes:2, + timeInterval:5, + title:"this is title", + content:"this is content", + expiredContent:"this reminder has expired", + snoozeContent:"remind later", + notificationId:100, + slotType:3 + } + reminderAgent.publishReminder(calendar, (err, reminderId) => { + expect(typeof(reminderId) === 'number').assertEqual(true); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper026 + * @tc.desc: test publishReminder + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper026", 0, async function (done) { + let calendar = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_CALENDAR, + dateTime : { + year: 2025, + month: 10, + day: 10, + hour: 23, + minute: 30 + }, + repeatMonths:[2], + repeatDays:[2], + actionButton:[ + { + title:"close", + type:0 + }, + { + title:"snooze", + type:1 + } + ], + wantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + maxScreenWantAgent:{ + pkgName:"com.huawei.phone", + abilityName:"com.huawei.phone.MainAbility" + }, + ringDuration:5, + snoozeTimes:2, + timeInterval:5, + title:"this is title", + content:"this is content", + expiredContent:"this reminder has expired", + snoozeContent:"remind later", + notificationId:100, + slotType:3 + } + reminderAgent.publishReminder(calendar).then((reminderId) => { + expect(typeof(reminderId)).assertEqual('number'); + }); + done(); + }) + + /* + * @tc.name: testReminderHelper027 + * @tc.desc: test publishReminder (max number limit of each application) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper027", 0, async function (done) { + let timer = { + reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, + triggerTimeInSeconds: 100 + } + let maxLimitNumsOfApp = 30; + let firstId = 0; + let secondId = 0; + let diffId = 0; + for (let i = 0; i < maxLimitNumsOfApp; i++) { + (function (i) { + var i = i; + setTimeout(function () { + reminderAgent.publishReminder(timer).then((reminderId) => { + if (i === 0) { + firstId = reminderId + } + if (i === 29) { + secondId = reminderId + diffId = secondId - firstId + expect(29).assertEqual(diffId); + i = null + } + }); + }, 500 * i); + })(i); + } + done(); + }) +}) \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index d851d969aabf4732c097031d3ff293afdb00b0c2..ec094df775522b4b11f5a78ad63d2f3815e10e52 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -26,27 +26,54 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.h" -#include "ans_mt_constant.h" +#include "common_event_manager.h" +#include "common_event_support.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "mock_ipc_skeleton.h" +#include "mock_single_kv_store.h" #include "notification_content.h" #include "notification_helper.h" #include "notification_long_text_content.h" #include "notification_subscriber.h" #include "system_ability_definition.h" +namespace OHOS { +namespace AppExecFwk { +void MockSetDistributedNotificationEnabled(bool enable); +} // AppExecFwk +} // namespace OHOS + using namespace testing::ext; using namespace OHOS::Media; namespace OHOS { namespace Notification { +namespace { +const std::string APP_NAME = "bundleName"; +const std::string NOTIFICATION_LABEL_0 = "Label0"; +const std::string NOTIFICATION_LABEL_1 = "Label1"; +const std::string NOTIFICATION_LABEL_2 = "Label2"; +const std::string AN_NOT_EXIST_KEY = "AN_NOT_EXIST_KEY"; +const std::string KEY_SPLITER = "_"; + +const std::string KVSTORE_APP_ID = "advanced_notification_service"; +const std::string KVSTORE_NOTIFICATION_STORE_ID = "distributed_notification"; +const std::string KVSTORE_PREFERENCES_STORE_ID = "distributed_preferences"; +const std::string KVSTORE_SCREEN_STATUS_STORE_ID = "distributed_screen_status"; + +constexpr int UID = 1; +constexpr int CANCEL_REASON_DELETE = 2; +constexpr int APP_CANCEL_REASON_DELETE = 8; +constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; +} // namespace enum class SubscriberEventType { ON_SUBSCRIBERESULT, ON_UNSUBSCRIBERESULT, ON_DIED, ON_UPDATE, - ON_DISTURBMODECHANGED, + ON_DND_CHANGED, ON_CANCELED, ON_CANCELED_WITH_SORTINGMAP_AND_DELETEREASON, ON_CONSUMED, @@ -74,34 +101,18 @@ class OnSubscribeResultEvent : public SubscriberEvent { public: ~OnSubscribeResultEvent() override {} - OnSubscribeResultEvent(NotificationConstant::SubscribeResult result) - : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT), subscribeResult_(result) - {} - NotificationConstant::SubscribeResult GetSubscribeResult() - { - return subscribeResult_; - } -private: - NotificationConstant::SubscribeResult subscribeResult_; + OnSubscribeResultEvent() : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT) + {} }; class OnUnSubscribeResultEvent : public SubscriberEvent { public: - OnUnSubscribeResultEvent(NotificationConstant::SubscribeResult result) - : SubscriberEvent(SubscriberEventType::ON_UNSUBSCRIBERESULT), unSubscribeResult_(result) + OnUnSubscribeResultEvent() : SubscriberEvent(SubscriberEventType::ON_UNSUBSCRIBERESULT) {} ~OnUnSubscribeResultEvent() override {} - - NotificationConstant::SubscribeResult GetUnSubscribeResult() - { - return unSubscribeResult_; - } - -private: - NotificationConstant::SubscribeResult unSubscribeResult_; }; class OnDiedEvent : public SubscriberEvent { @@ -131,22 +142,22 @@ private: std::shared_ptr sortingMap_; }; -class OnDisturbModeChangedEvent : public SubscriberEvent { +class OnDoNotDisturbDateChangedEvent : public SubscriberEvent { public: - OnDisturbModeChangedEvent(int disturbMode) - : SubscriberEvent(SubscriberEventType::ON_DISTURBMODECHANGED), disturbMode_(disturbMode) + explicit OnDoNotDisturbDateChangedEvent(const std::shared_ptr &date) + : SubscriberEvent(SubscriberEventType::ON_DND_CHANGED), date_(date) {} - ~OnDisturbModeChangedEvent() override + ~OnDoNotDisturbDateChangedEvent() override {} - int GetDisturbModeChanged() + const std::shared_ptr &GetDoNotDisturbDate() const { - return disturbMode_; + return date_; } private: - int disturbMode_; + std::shared_ptr date_; }; class OnOnCanceledEvent : public SubscriberEvent { @@ -246,15 +257,15 @@ private: class TestAnsSubscriber : public NotificationSubscriber { public: - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + void OnConnected() override { - std::shared_ptr event = std::make_shared(result); + std::shared_ptr event = std::make_shared(); std::unique_lock lck(mtx_); events_.push_back(event); } - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + void OnDisconnected() override { - std::shared_ptr event = std::make_shared(result); + std::shared_ptr event = std::make_shared(); std::unique_lock lck(mtx_); events_.push_back(event); } @@ -266,9 +277,9 @@ public: std::unique_lock lck(mtx_); events_.push_back(event); } - void OnDisturbModeChanged(int disturbMode) override + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override { - std::shared_ptr event = std::make_shared(disturbMode); + std::shared_ptr event = std::make_shared(date); std::unique_lock lck(mtx_); events_.push_back(event); } @@ -329,6 +340,85 @@ public: { std::this_thread::sleep_for(std::chrono::seconds(1)); } + + const std::string DELIMITER = "|"; + const std::string LOCAL_DEVICE_ID = ""; + const std::string REMOTE_DEVICE_ID = ""; + inline std::string GenerateDistributedKey(const NotificationRequest &req, const std::string &deviceId) + { + return std::string() + .append(deviceId) + .append(DELIMITER) + .append(APP_NAME) + .append(DELIMITER) + .append(req.GetLabel()) + .append(DELIMITER) + .append(ToString(req.GetNotificationId())); + } + + bool GetRequestInDistributedEntryList( + NotificationRequest &req, std::vector &entries, DistributedKv::Entry &outEntry) + { + std::string localDistributedKey = GenerateDistributedKey(req, LOCAL_DEVICE_ID); + for (auto entry : entries) { + if (entry.key.ToString() == localDistributedKey) { + outEntry = entry; + return true; + } + } + return false; + } + + bool GetRequestInNotificationList(NotificationRequest &req, + std::vector> ¬ificationList, std::shared_ptr &outNotification) + { + for (auto notification : notificationList) { + if (notification->GetNotificationRequest().GetNotificationId() == req.GetNotificationId() && + notification->GetNotificationRequest().GetLabel() == req.GetLabel()) { + outNotification = notification; + return true; + } + } + return false; + } + + NotificationRequest CreateDistributedRequest(std::string label) + { + int32_t notificationId = 1; + auto normalContent = std::make_shared(); + auto content = std::make_shared(normalContent); + NotificationRequest request(notificationId); + request.SetLabel(label); + request.SetContent(content); + request.SetDistributed(true); + std::vector devices = {""}; + request.SetDevicesSupportDisplay(devices); + return request; + } + + void PublishCommonEventScreenStatus(bool isScreenOn) + { + EventFwk::Want want; + EventFwk::CommonEventData data; + if (isScreenOn) { + data.SetWant(want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON)); + } else { + data.SetWant(want.SetAction(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF)); + } + + EventFwk::CommonEventManager::PublishCommonEvent(data); + } + + void SetDistributedScreenStatus(bool isScreenOn) + { + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + DistributedKv::Key key("" + DELIMITER + "screen_status"); + DistributedKv::Value value(isScreenOn ? "on" : "off"); + pointer->Put(key, value); + } }; class EventParser { @@ -353,12 +443,11 @@ public: ~EventParser() {} - void parse(std::list> events) + void Parse(std::list> events) { for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnSubscriber_ = ev->GetSubscribeResult(); + waitOnSubscriber_ = true; } else if (event->GetType() == SubscriberEventType::ON_CONSUMED) { std::shared_ptr ev = std::static_pointer_cast(event); waitOnConsumed_ = true; @@ -381,101 +470,99 @@ public: onCanceledWithSortingMapSor_.push_back(ev->GetSortingMap()); onCanceledWithSortingMapDelRea_.push_back(ev->GetDeleteReason()); } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { - std::shared_ptr ev = - std::static_pointer_cast(event); - waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + waitOnUnSubscriber_ = true; } } } - void setWaitOnConsumed(bool bl) + void SetWaitOnConsumed(bool bl) { waitOnConsumed_ = bl; } - void setWaitOnCanceled(bool bl) + void SetWaitOnCanceled(bool bl) { waitOnCanceled_ = bl; } - void setWaitOnCanceledWithSortingMapAndDeleteReason(bool bl) + void SetWaitOnCanceledWithSortingMapAndDeleteReason(bool bl) { waitOnCanceledWithSortingMapAndDeleteReason_ = bl; } - void setWaitOnUnSubscriber() + void SetWaitOnUnSubscriber() { waitOnUnSubscriber_ = NotificationConstant::SubscribeResult::RESOURCES_FAIL; } - uint32_t getWaitOnSubscriber() + bool GetWaitOnSubscriber() const { return waitOnSubscriber_; } - uint32_t getWaitOnUnSubscriber() + bool GetWaitOnUnSubscriber() const { return waitOnUnSubscriber_; } - bool getwaitOnConsumed() + bool GetWaitOnConsumed() const { return waitOnConsumed_; } - std::vector> getOnConsumedReq() + std::vector> GetOnConsumedReq() const { return onConsumedReq_; } - std::vector> getOnConsumedWithSortingMapReq() + std::vector> GetOnConsumedWithSortingMapReq() const { return onConsumedWithSortingMapReq_; } - std::vector> getOnConsumedWithSortingMapSor() + std::vector> GetOnConsumedWithSortingMapSor() const { return onConsumedWithSortingMapSor_; } - bool getWaitOnConsumedWithSortingMap() + bool GetWaitOnConsumedWithSortingMap() const { return waitOnConsumedWithSortingMap_; } - bool getWaitOnCanceled() + bool GetWaitOnCanceled() const { return waitOnCanceled_; } - bool getWaitOnCanceledWithSortingMapAndDeleteReason() + bool GetWaitOnCanceledWithSortingMapAndDeleteReason() const { return waitOnCanceledWithSortingMapAndDeleteReason_; } - std::vector> getOnCanceledReq() + std::vector> GetOnCanceledReq() const { return onCanceledReq_; } - std::vector> getOnCanceledWithSortingMapReq() + std::vector> GetOnCanceledWithSortingMapReq() const { return onCanceledWithSortingMapReq_; } - std::vector> getOnCanceledWithSortingMapSor() + std::vector> GetOnCanceledWithSortingMapSor() const { return onCanceledWithSortingMapSor_; } - std::vector getOnCanceledWithSortingMapDelRea() + std::vector GetOnCanceledWithSortingMapDelRea() const { return onCanceledWithSortingMapDelRea_; } private: - uint32_t waitOnSubscriber_; - uint32_t waitOnUnSubscriber_; + bool waitOnSubscriber_ = false; + bool waitOnUnSubscriber_ = false; bool waitOnConsumed_ = false; std::vector> onConsumedReq_; std::vector> onConsumedWithSortingMapReq_; @@ -549,31 +636,31 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L SleepForFC(); std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); + eventParser.Parse(events); for (uint32_t i = 0; i <= MAX_ACTIVE_NUM_PERSECOND; i++) { std::string notificationLabel = std::to_string(i); std::string notificationIdStr = std::to_string(i); int32_t notificationIdInt = i; if (i < MAX_ACTIVE_NUM_PERSECOND) { std::stringstream stream; - stream << UID << KEY_SPLITER << notificationLabel << KEY_SPLITER << notificationIdInt; + stream << KEY_SPLITER << UID << KEY_SPLITER << notificationLabel << KEY_SPLITER << notificationIdInt; std::string notificationKey = stream.str(); NotificationSorting sorting; - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetLabel().c_str(), notificationLabel); - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetId(), notificationIdInt); - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetKey(), notificationKey); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetLabel().c_str(), notificationLabel); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetId(), notificationIdInt); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.GetOnConsumedReq()[i]->GetLabel().c_str(), notificationLabel); + EXPECT_EQ(eventParser.GetOnConsumedReq()[i]->GetId(), notificationIdInt); + EXPECT_EQ(eventParser.GetOnConsumedReq()[i]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.GetOnConsumedWithSortingMapReq()[i]->GetLabel().c_str(), notificationLabel); + EXPECT_EQ(eventParser.GetOnConsumedWithSortingMapReq()[i]->GetId(), notificationIdInt); + EXPECT_EQ(eventParser.GetOnConsumedWithSortingMapReq()[i]->GetKey(), notificationKey); EXPECT_TRUE( - eventParser.getOnConsumedWithSortingMapSor()[i]->GetNotificationSorting(notificationKey, sorting)); + eventParser.GetOnConsumedWithSortingMapSor()[i]->GetNotificationSorting(notificationKey, sorting)); EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); } } - EXPECT_EQ((uint32_t)eventParser.getOnConsumedReq().size(), MAX_ACTIVE_NUM_PERSECOND); - EXPECT_EQ((uint32_t)eventParser.getOnConsumedWithSortingMapReq().size(), MAX_ACTIVE_NUM_PERSECOND); - EXPECT_EQ(eventParser.getWaitOnSubscriber(), NotificationConstant::SubscribeResult::SUCCESS); - EXPECT_EQ(eventParser.getWaitOnUnSubscriber(), NotificationConstant::SubscribeResult::SUCCESS); + EXPECT_EQ((uint32_t)eventParser.GetOnConsumedReq().size(), MAX_ACTIVE_NUM_PERSECOND); + EXPECT_EQ((uint32_t)eventParser.GetOnConsumedWithSortingMapReq().size(), MAX_ACTIVE_NUM_PERSECOND); + EXPECT_TRUE(eventParser.GetWaitOnSubscriber()); + EXPECT_TRUE(eventParser.GetWaitOnUnSubscriber()); subscriber.ClearEvents(); SleepForFC(); } @@ -605,21 +692,21 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | M SleepForFC(); std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 0); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); std::stringstream stream; - stream << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + stream << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; std::string notificationKey = stream.str(); NotificationSorting sorting; - EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); - EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); + EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); + EXPECT_TRUE(eventParser.GetOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], CANCEL_REASON_DELETE); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapDelRea()[0], CANCEL_REASON_DELETE); subscriber.ClearEvents(); SleepForFC(); } @@ -650,19 +737,19 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00200, Function | M SleepForFC(); std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - eventParser.setWaitOnCanceled(false); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + eventParser.SetWaitOnCanceled(false); EXPECT_EQ(NotificationHelper::RemoveNotification(key), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); SleepForFC(); EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); subscriber.ClearEvents(); SleepForFC(); } @@ -689,9 +776,9 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | Medium SleepForFC(); EventParser eventParser; std::list> events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - eventParser.setWaitOnConsumed(false); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); NotificationRequest req1(1); req1.SetLabel(NOTIFICATION_LABEL_0); @@ -699,8 +786,8 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | Medium events = subscriber.GetEvents(); EXPECT_EQ(NotificationHelper::PublishNotification(req1), ERR_OK); SleepForFC(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); SleepForFC(); EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); std::vector> notifications; @@ -710,9 +797,9 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00100, Function | Medium SleepForFC(); EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); subscriber.ClearEvents(); SleepForFC(); } @@ -734,11 +821,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitons_00200, Function | Medium SleepForFC(); EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); std::list> events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_FALSE(eventParser.getwaitOnConsumed()); - EXPECT_FALSE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_FALSE(eventParser.getWaitOnCanceled()); - EXPECT_FALSE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + eventParser.Parse(events); + EXPECT_FALSE(eventParser.GetWaitOnConsumed()); + EXPECT_FALSE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_FALSE(eventParser.GetWaitOnCanceled()); + EXPECT_FALSE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); subscriber.ClearEvents(); SleepForFC(); } @@ -759,19 +846,17 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_UnSubscriber_00100, Function | MediumTest | EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); std::list> events = subscriber.GetEvents(); - uint32_t waitOnSubscriber_; - uint32_t waitOnUnSubscriber_; + bool waitOnSubscriber = false; + bool waitOnUnSubscriber = false; for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnSubscriber_ = ev->GetSubscribeResult(); + waitOnSubscriber = true; } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + waitOnUnSubscriber = true; } } - EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + EXPECT_TRUE(waitOnSubscriber); subscriber.ClearEvents(); SleepForFC(); @@ -794,28 +879,29 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_UnSubscriber_00200, Function | MediumTest | EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), (int)ERR_OK); SleepForFC(); std::list> events = subscriber.GetEvents(); - uint32_t waitOnSubscriber_; - uint32_t waitOnUnSubscriber_; + bool waitOnSubscriber = false; + bool waitOnUnSubscriber = false; for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnSubscriber_ = ev->GetSubscribeResult(); + waitOnSubscriber = true; } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + waitOnUnSubscriber = true; } } - EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); - waitOnSubscriber_ = NotificationConstant::SubscribeResult::PREMISSION_FAIL; - EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), (int)ERR_OK); + EXPECT_TRUE(waitOnSubscriber); + EXPECT_TRUE(waitOnUnSubscriber); + + waitOnSubscriber = false; + waitOnUnSubscriber = false; + subscriber.ClearEvents(); + EXPECT_NE(NotificationHelper::UnSubscribeNotification(subscriber, info), (int)ERR_OK); events = subscriber.GetEvents(); for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + waitOnUnSubscriber = true; } } - EXPECT_EQ(waitOnUnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + EXPECT_FALSE(waitOnUnSubscriber); subscriber.ClearEvents(); SleepForFC(); } @@ -833,19 +919,18 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_Subscriber_00100, Function | MediumTest | Le EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); std::list> events = subscriber.GetEvents(); - uint32_t waitOnSubscriber_; - uint32_t waitOnUnSubscriber_; + bool waitOnSubscriber = false; + bool waitOnUnSubscriber = false; for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnSubscriber_ = ev->GetSubscribeResult(); + waitOnSubscriber = true; } else if (event->GetType() == SubscriberEventType::ON_UNSUBSCRIBERESULT) { - std::shared_ptr ev = std::static_pointer_cast(event); - waitOnUnSubscriber_ = ev->GetUnSubscribeResult(); + waitOnUnSubscriber = true; } } - EXPECT_EQ(waitOnSubscriber_, NotificationConstant::SubscribeResult::SUCCESS); + EXPECT_TRUE(waitOnSubscriber); subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); } @@ -880,21 +965,21 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00100, Function | Med SleepForFC(); std::list> events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 1); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 1); std::stringstream stream; - stream << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 1; + stream << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 1; std::string notificationKey = stream.str(); NotificationSorting sorting; - EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); - EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); + EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey); + EXPECT_TRUE(eventParser.GetOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey, sorting)); EXPECT_EQ(sorting.GetKey().c_str(), notificationKey); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_REASON_DELETE); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_REASON_DELETE); subscriber.ClearEvents(); SleepForFC(); } @@ -925,19 +1010,19 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00200, Function | Med int32_t id = 0; SleepForFC(); - eventParser.setWaitOnCanceled(false); - eventParser.setWaitOnCanceledWithSortingMapAndDeleteReason(false); + eventParser.SetWaitOnCanceled(false); + eventParser.SetWaitOnCanceledWithSortingMapAndDeleteReason(false); EXPECT_EQ(NotificationHelper::CancelNotification(NOTIFICATION_LABEL_0, id), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); SleepForFC(); EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); std::list> events = subscriber.GetEvents(); - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_FALSE(eventParser.getWaitOnCanceled()); - EXPECT_FALSE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_FALSE(eventParser.GetWaitOnCanceled()); + EXPECT_FALSE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); subscriber.ClearEvents(); SleepForFC(); } @@ -975,33 +1060,33 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | Med std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); - EXPECT_EQ(eventParser.getOnConsumedReq()[0]->GetId(), 0); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); std::stringstream stream0; - stream0 << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; + stream0 << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_0 << KEY_SPLITER << 0; std::string notificationKey0 = stream0.str(); NotificationSorting sorting0; - EXPECT_EQ(eventParser.getOnCanceledReq()[0]->GetKey(), notificationKey0); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey0); - EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey0, sorting0)); + EXPECT_EQ(eventParser.GetOnCanceledReq()[0]->GetKey(), notificationKey0); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapReq()[0]->GetKey(), notificationKey0); + EXPECT_TRUE(eventParser.GetOnConsumedWithSortingMapSor()[0]->GetNotificationSorting(notificationKey0, sorting0)); EXPECT_EQ(sorting0.GetKey().c_str(), notificationKey0); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_ALL_REASON_DELETE); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapDelRea()[0], APP_CANCEL_ALL_REASON_DELETE); - EXPECT_EQ(eventParser.getOnConsumedReq()[1]->GetLabel().c_str(), NOTIFICATION_LABEL_1); - EXPECT_EQ(eventParser.getOnConsumedReq()[1]->GetId(), 1); + EXPECT_EQ(eventParser.GetOnConsumedReq()[1]->GetLabel().c_str(), NOTIFICATION_LABEL_1); + EXPECT_EQ(eventParser.GetOnConsumedReq()[1]->GetId(), 1); std::stringstream stream1; - stream1 << UID << KEY_SPLITER << NOTIFICATION_LABEL_1 << KEY_SPLITER << 1; + stream1 << KEY_SPLITER << UID << KEY_SPLITER << NOTIFICATION_LABEL_1 << KEY_SPLITER << 1; std::string notificationKey1 = stream1.str(); NotificationSorting sorting1; - EXPECT_EQ(eventParser.getOnCanceledReq()[1]->GetKey(), notificationKey1); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapReq()[1]->GetKey(), notificationKey1); - EXPECT_TRUE(eventParser.getOnConsumedWithSortingMapSor()[1]->GetNotificationSorting(notificationKey1, sorting1)); + EXPECT_EQ(eventParser.GetOnCanceledReq()[1]->GetKey(), notificationKey1); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapReq()[1]->GetKey(), notificationKey1); + EXPECT_TRUE(eventParser.GetOnConsumedWithSortingMapSor()[1]->GetNotificationSorting(notificationKey1, sorting1)); EXPECT_EQ(sorting1.GetKey().c_str(), notificationKey1); - EXPECT_EQ(eventParser.getOnCanceledWithSortingMapDelRea()[1], APP_CANCEL_ALL_REASON_DELETE); + EXPECT_EQ(eventParser.GetOnCanceledWithSortingMapDelRea()[1], APP_CANCEL_ALL_REASON_DELETE); subscriber.ClearEvents(); SleepForFC(); @@ -1042,11 +1127,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishSoundNotification_00100, Function | M std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); subscriber.ClearEvents(); SleepForFC(); } @@ -1085,11 +1170,11 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishVibrationNotification_00100, Function SleepForFC(); std::list> events = subscriber.GetEvents(); EventParser eventParser; - eventParser.parse(events); - EXPECT_TRUE(eventParser.getwaitOnConsumed()); - EXPECT_TRUE(eventParser.getWaitOnConsumedWithSortingMap()); - EXPECT_TRUE(eventParser.getWaitOnCanceled()); - EXPECT_TRUE(eventParser.getWaitOnCanceledWithSortingMapAndDeleteReason()); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); subscriber.ClearEvents(); SleepForFC(); } @@ -1213,5 +1298,1242 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishNotificationWithPixelMap_00300, Funct EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_ICON_OVER_SIZE); } -} // namespace Notification -} // namespace OHOS +/** + * + * @tc.number : ANS_FW_MT_OnDoNotDisturbDateChange_00100 + * @tc.name : + * @tc.desc : OnDoNotDisturbDateChange callback. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_OnDoNotDisturbDateChange_00100, Function | MediumTest | Level1) +{ + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + NotificationDoNotDisturbDate date(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(date), ERR_OK); + + std::this_thread::sleep_for(std::chrono::seconds(1)); + + std::list> events = subscriber.GetEvents(); + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_DND_CHANGED) { + std::shared_ptr ev = + std::static_pointer_cast(event); + auto date = ev->GetDoNotDisturbDate(); + ASSERT_NE(date, nullptr); + EXPECT_EQ(date->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::NONE); + } + } + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); +} + +/** + * + * @tc.number : ANS_FW_MT_OnDoNotDisturbDateChange_00200 + * @tc.name : + * @tc.desc : OnDoNotDisturbDateChange callback. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_OnDoNotDisturbDateChange_00200, Function | MediumTest | Level1) +{ + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), 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(); + NotificationDoNotDisturbDate date(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(date), ERR_OK); + + std::this_thread::sleep_for(std::chrono::seconds(1)); + + std::list> events = subscriber.GetEvents(); + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_DND_CHANGED) { + std::shared_ptr ev = + std::static_pointer_cast(event); + auto date = ev->GetDoNotDisturbDate(); + ASSERT_NE(date, nullptr); + EXPECT_EQ(date->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::ONCE); + } + } + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); +} + +/** + * + * @tc.number : ANS_FW_MT_OnDoNotDisturbDateChange_00300 + * @tc.name : + * @tc.desc : OnDoNotDisturbDateChange callback. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_OnDoNotDisturbDateChange_00300, Function | MediumTest | Level1) +{ + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), 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(); + NotificationDoNotDisturbDate date(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(date), ERR_OK); + + std::this_thread::sleep_for(std::chrono::seconds(1)); + + std::list> events = subscriber.GetEvents(); + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_DND_CHANGED) { + std::shared_ptr ev = + std::static_pointer_cast(event); + auto date = ev->GetDoNotDisturbDate(); + ASSERT_NE(date, nullptr); + EXPECT_EQ(date->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + } + } + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); +} + +/** + * + * @tc.number : ANS_FW_MT_OnDoNotDisturbDateChange_00400 + * @tc.name : + * @tc.desc : OnDoNotDisturbDateChange callback. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_OnDoNotDisturbDateChange_00400, Function | MediumTest | Level1) +{ + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), 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(); + NotificationDoNotDisturbDate date(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(date), ERR_OK); + + std::this_thread::sleep_for(std::chrono::seconds(1)); + + std::list> events = subscriber.GetEvents(); + for (auto event : events) { + if (event->GetType() == SubscriberEventType::ON_DND_CHANGED) { + std::shared_ptr ev = + std::static_pointer_cast(event); + auto date = ev->GetDoNotDisturbDate(); + ASSERT_NE(date, nullptr); + EXPECT_EQ(date->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::CLEARLY); + } + } + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); +} + +static NotificationDoNotDisturbDate GetDoNotDisturbDateInstance( + NotificationConstant::DoNotDisturbType type, int64_t intervalHours) +{ + std::chrono::time_point beginTp = std::chrono::system_clock::now(); + + auto beginDur = std::chrono::duration_cast(beginTp.time_since_epoch()); + auto beginMs = beginDur.count(); + + auto endDur = beginDur + std::chrono::hours(intervalHours); + auto endMs = endDur.count(); + + return {type, beginMs, endMs}; +} + +/** + * + * @tc.number : ANS_FW_MT_GetDoNotDisturbDate_00100 + * @tc.name : + * @tc.desc : GetDoNotDisturbDate. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_GetDoNotDisturbDate_00100, Function | MediumTest | Level1) +{ + NotificationDoNotDisturbDate setDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(setDate), ERR_OK); + + NotificationDoNotDisturbDate getDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(getDate), ERR_OK); + EXPECT_EQ(getDate.GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::NONE); + EXPECT_EQ(getDate.GetBeginDate(), 0); + EXPECT_EQ(getDate.GetEndDate(), 0); +} + +/** + * + * @tc.number : ANS_FW_MT_DoesSupportDoNotDisturbMode_00100 + * @tc.name : + * @tc.desc : DoesSupportDoNotDisturbMode. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_DoesSupportDoNotDisturbMode_00100, Function | MediumTest | Level1) +{ + bool isSupport = false; + EXPECT_EQ(NotificationHelper::DoesSupportDoNotDisturbMode(isSupport), ERR_OK); + EXPECT_EQ(isSupport, SUPPORT_DO_NOT_DISTRUB); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_01000 + * @tc.name : DoNotDisturb_01000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 01:40 ~ 02:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_FW_MT_DoNotDisturb_01000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::ONCE, 1); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_01000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_01000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_01000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_01000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_02000 + * @tc.name : DoNotDisturb_02000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 1970-01-01 01:40 ~ 1970-01-02 01:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_02000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::ONCE, 24); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_02000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_02000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_02000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_02000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); + + EXPECT_NE(disDate.GetBeginDate(), disDate.GetEndDate()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_03000 + * @tc.name : DoNotDisturb_03000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 1970-01-01 01:40 ~ 1970-01-02 02:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_03000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::ONCE, 25); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_03000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_03000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_03000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_03000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_04000 + * @tc.name : DoNotDisturb_04000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 01:40 ~ 07:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_04000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::DAILY, 6); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_04000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_04000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_04000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_04000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_05000 + * @tc.name : DoNotDisturb_05000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 1970-01-01 01:40 ~ 1970-01-02 01:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_05000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::DAILY, 24); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_05000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_05000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_05000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_05000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); + + EXPECT_NE(disDate.GetBeginDate(), disDate.GetEndDate()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_06000 + * @tc.name : DoNotDisturb_06000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 1970-01-01 01:40 ~ 1970-01-02 02:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_06000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::DAILY, 25); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_06000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_06000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_06000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_06000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); +} + +/** + * @tc.number : ANS_Interface_MT_DoNotDisturb_07000 + * @tc.name : DoNotDisturb_07000 + * @tc.desc : Set and get DoNotDisturbDate. E.g. 1970-01-01 01:40 ~ 1970-01-03 01:40 + * @tc.expected : Set and get DoNotDisturbDate successfully. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_07000, Function | MediumTest | Level1) +{ + auto srcDate = GetDoNotDisturbDateInstance(NotificationConstant::DoNotDisturbType::CLEARLY, 48); + EXPECT_EQ(NotificationHelper::SetDoNotDisturbDate(srcDate), ERR_OK); + + NotificationDoNotDisturbDate disDate; + EXPECT_EQ(NotificationHelper::GetDoNotDisturbDate(disDate), ERR_OK); + + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_07000:: srcDate : beginMs : " << srcDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_07000:: srcDate : endMs : " << srcDate.GetEndDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_07000:: disDate : beginMs : " << disDate.GetBeginDate(); + GTEST_LOG_(INFO) << "ANS_Interface_MT_DoNotDisturb_07000:: disDate : endMs : " << disDate.GetEndDate(); + + EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_SetEnable_00100 + * @tc.name : DistributedNotification_SetEnable_00100 + * @tc.desc : Set distributed notification enable. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_SetEnable_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + bool enable; + + ASSERT_EQ(NotificationHelper::EnableDistributed(false), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnabled(enable), ERR_OK); + ASSERT_EQ(enable, false); + + ASSERT_EQ(NotificationHelper::EnableDistributed(true), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnabled(enable), ERR_OK); + ASSERT_EQ(enable, true); +} + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_SetEnableByBundle_00100 + * @tc.name : DistributedNotification_SetEnableByBundle_00100 + * @tc.desc : Set distributed notification enable by bundle. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_SetEnableByBundle_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + bool enable; + NotificationBundleOption bundleOption(APP_NAME, UID); + + ASSERT_EQ(NotificationHelper::EnableDistributedByBundle(bundleOption, false), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); + ASSERT_EQ(enable, false); + + ASSERT_EQ(NotificationHelper::EnableDistributedByBundle(bundleOption, true), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); + ASSERT_EQ(enable, true); + + ASSERT_EQ(NotificationHelper::EnableDistributedSelf(false), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); + ASSERT_EQ(enable, false); + + ASSERT_EQ(NotificationHelper::EnableDistributedSelf(true), ERR_OK); + ASSERT_EQ(NotificationHelper::IsDistributedEnableByBundle(bundleOption, enable), ERR_OK); + ASSERT_EQ(enable, true); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Publish_00100 + * @tc.name : DistributedNotification_Publish_00100 + * @tc.desc : publish a notification to distributed kvstore. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Publish_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Publish_00200 + * @tc.name : DistributedNotification_Publish_00200 + * @tc.desc : publish a local notification not use distributed kvstore. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Publish_00200, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + request.SetDistributed(false); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), false); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Publish_00300 + * @tc.name : DistributedNotification_Publish_00300 MockSetDistributedNotificationEnabled + * @tc.desc : publish a distributed notification when DistributedNotificationEnabled is false in application info. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Publish_00300, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + request.SetDistributed(true); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + AppExecFwk::MockSetDistributedNotificationEnabled(false); + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), false); + AppExecFwk::MockSetDistributedNotificationEnabled(true); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Cancel_00100 + * @tc.name : DistributedNotification_Cancel_00100 + * @tc.desc : cancel a notification to distributed kvstore ,use CancelNotification(label, id). + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Cancel_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + ASSERT_EQ(NotificationHelper::CancelNotification(request.GetLabel(), request.GetNotificationId()), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), false); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Cancel_00200 + * @tc.name : DistributedNotification_Cancel_00200 + * @tc.desc : cancel a notification to distributed kvstore ,use CancelAllNotifications(). + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Cancel_00200, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + request.SetNotificationId(request.GetNotificationId() + 1); + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + ASSERT_EQ(NotificationHelper::CancelAllNotifications(), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(entries.size(), std::size_t(0)); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Remove_00100 + * @tc.name : DistributedNotification_Remove_00100 + * @tc.desc : remove a notification to distributed kvstore ,use RemoveNotification(bundleOption, id, label). + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Remove_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + NotificationBundleOption bundleOption(APP_NAME, UID); + ASSERT_EQ( + NotificationHelper::RemoveNotification(bundleOption, request.GetNotificationId(), request.GetLabel()), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), false); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Remove_00200 + * @tc.name : DistributedNotification_Remove_00200 + * @tc.desc : remove a notification to distributed kvstore ,use RemoveNotifications(). + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Remove_00200, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + request.SetNotificationId(request.GetNotificationId() + 1); + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + ASSERT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(entries.size(), std::size_t(0)); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Remove_00300 + * @tc.name : DistributedNotification_Remove_00300 + * @tc.desc : remove a notification to distributed kvstore ,use RemoveNotificationsByBundle(bundleOption). + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Remove_00300, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + DistributedKv::Entry outEntry; + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + request.SetNotificationId(request.GetNotificationId() + 1); + ASSERT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(GetRequestInDistributedEntryList(request, entries, outEntry), true); + + NotificationBundleOption bundleOption(APP_NAME, UID); + ASSERT_EQ(NotificationHelper::RemoveNotificationsByBundle(bundleOption), ERR_OK); + ASSERT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + ASSERT_EQ(entries.size(), std::size_t(0)); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Subscribe_00100 + * @tc.name : DistributedNotification_Subscribe_00100 + * @tc.desc : distributed kvstore callback data insert/update/delete. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + std::string jsonString; + NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + TestAnsSubscriber subscriber; + ASSERT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); + DistributedKv::Value value(jsonString); + pointer->InsertDataToDoCallback(key, value); + SleepForFC(); + + EventParser parser1; + parser1.Parse(subscriber.GetEvents()); + auto notificationList = parser1.GetOnConsumedReq(); + EXPECT_NE(notificationList.size(), std::size_t(0)); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + subscriber.ClearEvents(); + + pointer->UpdateDataToDoCallback(key, value); + SleepForFC(); + + EventParser parser2; + parser2.Parse(subscriber.GetEvents()); + notificationList = parser2.GetOnConsumedReq(); + EXPECT_NE(notificationList.size(), std::size_t(0)); + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + subscriber.ClearEvents(); + + pointer->DeleteDataToDoCallback(key); + SleepForFC(); + + EventParser parser3; + parser3.Parse(subscriber.GetEvents()); + notificationList = parser3.GetOnCanceledReq(); + EXPECT_NE(notificationList.size(), std::size_t(0)); + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + subscriber.ClearEvents(); + ASSERT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_Subscribe_00200 + * @tc.name : DistributedNotification_Subscribe_00200 + * @tc.desc : distributed kvstore callback data, delete notification after OnConsumed. + */ +HWTEST_F(AnsFWModuleTest, DistributedNotification_Subscribe_00200, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + request.SetOwnerBundleName(APP_NAME); + request.SetCreatorBundleName(APP_NAME); + std::string jsonString; + NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + std::vector entries; + + TestAnsSubscriber subscriber; + ASSERT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); + DistributedKv::Value value(jsonString); + pointer->InsertDataToDoCallback(key, value); + SleepForFC(); + + EventParser parser1; + parser1.Parse(subscriber.GetEvents()); + auto notificationList = parser1.GetOnConsumedReq(); + EXPECT_NE(notificationList.size(), std::size_t(0)); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + + EXPECT_EQ(NotificationHelper::RemoveNotifications(), ERR_OK); + + EXPECT_EQ(pointer->GetEntries(DistributedKv::Key(""), entries), DistributedKv::Status::SUCCESS); + EXPECT_EQ(entries.size(), std::size_t(0)); + subscriber.ClearEvents(); + ASSERT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_Interface_MT_GetDeviceRemindType_00100 + * @tc.name : GetDeviceRemindType_00100 + * @tc.desc : Get device remind type. + */ +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_GetDeviceRemindType_00100, Function | MediumTest | Level1) +{ + auto rType = NotificationConstant::RemindType::NONE; + EXPECT_EQ(NotificationHelper::GetDeviceRemindType(rType), ERR_OK); + ANS_LOGI("ANS_Interface_MT_GetDeviceRemindType_00100:: rType : %{public}d", static_cast(rType)); + + EXPECT_NE(rType, NotificationConstant::RemindType::NONE); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_ScreenStatusChange_00100 + * @tc.name : ScreenStatusChange_00100 + * @tc.desc : Receive local screen status from common event to kvstore. + */ +HWTEST_F(AnsFWModuleTest, ScreenStatusChange_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + DistributedKv::Key key(""); + std::vector entries; + + PublishCommonEventScreenStatus(false); + EXPECT_EQ(pointer->GetEntries(key, entries), DistributedKv::Status::SUCCESS); + EXPECT_EQ(entries.size(), std::size_t(1)); + EXPECT_EQ(entries[0].value.ToString(), "off"); + entries.clear(); + + PublishCommonEventScreenStatus(true); + EXPECT_EQ(pointer->GetEntries(key, entries), DistributedKv::Status::SUCCESS); + EXPECT_EQ(entries.size(), std::size_t(1)); + EXPECT_EQ(entries[0].value.ToString(), "on"); + entries.clear(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00100 + * @tc.name : DefaultRemindPolicy_00100 + * @tc.desc : Publish a notification when local screen on and remote screen off. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00100, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + PublishCommonEventScreenStatus(true); + SetDistributedScreenStatus(false); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00200 + * @tc.name : DefaultRemindPolicy_00200 + * @tc.desc : Publish a notification when local screen on and remote screen on. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00200, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + PublishCommonEventScreenStatus(true); + SetDistributedScreenStatus(true); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00300 + * @tc.name : DefaultRemindPolicy_00300 + * @tc.desc : Publish a notification when local screen off and remote screen off. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00300, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + PublishCommonEventScreenStatus(false); + SetDistributedScreenStatus(false); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00400 + * @tc.name : DefaultRemindPolicy_00400 + * @tc.desc : Publish a notification when local screen off and remote screen on. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00400, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + + PublishCommonEventScreenStatus(false); + SetDistributedScreenStatus(true); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + EXPECT_EQ(NotificationHelper::PublishNotification(request), ERR_OK); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00500 + * @tc.name : DefaultRemindPolicy_00500 + * @tc.desc : Receive distributed notification when screen is on. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00500, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + std::vector devices = {""}; + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + request.SetOwnerBundleName(APP_NAME); + request.SetCreatorBundleName(APP_NAME); + request.SetDevicesSupportDisplay(devices); + std::string jsonString; + NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + + PublishCommonEventScreenStatus(true); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); + DistributedKv::Value value(jsonString); + pointer->InsertDataToDoCallback(key, value); + SleepForFC(); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} + +/** + * + * @tc.number : ANS_FW_MT_DistributedNotification_DefaultRemindPolicy_00600 + * @tc.name : DefaultRemindPolicy_00600 + * @tc.desc : Receive distributed notification when screen is off. + */ +HWTEST_F(AnsFWModuleTest, DefaultRemindPolicy_00600, Function | MediumTest | Level1) +{ + ANS_LOGI("%{public}s", test_info_->name()); + std::vector devices = {""}; + NotificationRequest request = CreateDistributedRequest(test_info_->name()); + request.SetOwnerBundleName(APP_NAME); + request.SetCreatorBundleName(APP_NAME); + request.SetDevicesSupportDisplay(devices); + std::string jsonString; + NotificationJsonConverter::ConvertToJosnString(&request, jsonString); + + PublishCommonEventScreenStatus(false); + + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + DistributedKv::AppId appId = {.appId = KVSTORE_APP_ID}; + DistributedKv::StoreId storeId = {.storeId = KVSTORE_SCREEN_STATUS_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer(appId, storeId); + + DistributedKv::Key key(GenerateDistributedKey(request, REMOTE_DEVICE_ID)); + DistributedKv::Value value(jsonString); + pointer->InsertDataToDoCallback(key, value); + SleepForFC(); + + EventParser parser; + parser.Parse(subscriber.GetEvents()); + auto notificationList = parser.GetOnConsumedReq(); + std::shared_ptr outNotification; + EXPECT_EQ(GetRequestInNotificationList(request, notificationList, outNotification), true); + EXPECT_EQ(outNotification->GetRemindType(), NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND); + + subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); +} +#endif + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07100, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); + + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + int32_t id = notifications[0]->GetId(); + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + EXPECT_EQ(NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + SleepForFC(); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); + IPCSkeleton::SetCallingUid(1); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07200, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); + + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + std::string key = notifications[0]->GetKey().c_str(); + EXPECT_EQ(NotificationHelper::RemoveNotification(key), (int)ERR_OK); + int32_t id = notifications[0]->GetId(); + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + EXPECT_EQ(NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + SleepForFC(); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); + IPCSkeleton::SetCallingUid(1); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07300, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); + + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + int32_t id = notifications[0]->GetId(); + EXPECT_EQ(NotificationHelper::CancelNotification(id), (int)ERR_ANS_NOTIFICATION_NOT_EXISTS); + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + EXPECT_EQ(NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + SleepForFC(); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); + IPCSkeleton::SetCallingUid(1); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07400, Function | MediumTest | Level1) +{ + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), (int)ERR_ANS_NOT_SYSTEM_SERVICE); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07500, Function | MediumTest | Level1) +{ + TestAnsSubscriber subscriber; + NotificationSubscribeInfo info; + info.AddAppName("bundleName"); + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber, info), ERR_OK); + + std::shared_ptr implContent = std::make_shared(); + std::shared_ptr content = std::make_shared(implContent); + NotificationRequest req0(0); + req0.SetLabel(NOTIFICATION_LABEL_0); + req0.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req0), ERR_OK); + + NotificationRequest req1(1); + req1.SetLabel(NOTIFICATION_LABEL_1); + req1.SetContent(content); + EXPECT_EQ(NotificationHelper::PublishNotification(req1), ERR_OK); + EXPECT_EQ( + NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_1, 1), (int)ERR_ANS_NOT_SYSTEM_SERVICE); + EXPECT_EQ(NotificationHelper::CancelAllNotifications(), ERR_OK); + SleepForFC(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); + SleepForFC(); + std::list> events = subscriber.GetEvents(); + + EventParser eventParser; + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + EXPECT_TRUE(eventParser.GetWaitOnConsumedWithSortingMap()); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07600, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->IsUnremovable(), true); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetSourceType(), NotificationConstant::SourceType::TYPE_CONTINUOUS); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); + subscriber.ClearEvents(); + IPCSkeleton::SetCallingUid(1); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07700, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); + + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + int32_t id = notifications[0]->GetId(); + EXPECT_EQ(NotificationHelper::CancelAllNotifications(), (int)ERR_OK); + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + EXPECT_EQ(NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + SleepForFC(); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); + IPCSkeleton::SetCallingUid(1); +} + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07800, Function | MediumTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + TestAnsSubscriber subscriber; + EXPECT_EQ(NotificationHelper::SubscribeNotification(subscriber), ERR_OK); + NotificationRequest req(0); + req.SetLabel(NOTIFICATION_LABEL_0); + EXPECT_EQ(NotificationHelper::PublishContinuousTaskNotification(req), ERR_OK); + SleepForFC(); + EventParser eventParser; + std::list> events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnConsumed()); + eventParser.SetWaitOnConsumed(false); + + std::vector> notifications; + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + int32_t id = notifications[0]->GetId(); + EXPECT_EQ(NotificationHelper::RemoveNotifications(), (int)ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_NE((int)notifications.size(), (int)0); + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + EXPECT_EQ(NotificationHelper::CancelContinuousTaskNotification(NOTIFICATION_LABEL_0, id), ERR_OK); + EXPECT_EQ(NotificationHelper::GetAllActiveNotifications(notifications), ERR_OK); + EXPECT_EQ((int)notifications.size(), (int)0); + SleepForFC(); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + events = subscriber.GetEvents(); + eventParser.Parse(events); + EXPECT_TRUE(eventParser.GetWaitOnCanceled()); + EXPECT_TRUE(eventParser.GetWaitOnCanceledWithSortingMapAndDeleteReason()); + subscriber.ClearEvents(); + SleepForFC(); + IPCSkeleton::SetCallingUid(1); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp index a1ba734cdf57aff72cc350ba28e1de89c3c47787..a8ac9f30751ead3851743819d44022d910b2073a 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -18,21 +18,22 @@ #include "ans_inner_errors.h" #include "ans_manager_proxy.h" #include "advanced_notification_service.h" -#include "context.h" #include "datetime_ex.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "notification_helper.h" +#include "notification_json_convert.h" #include "mock_bundle_manager.h" #include "mock_ipc_skeleton.h" #include "system_ability_definition.h" #include "want_agent_info.h" #include "want_agent_helper.h" +#include "want_params.h" +#include "ohos/aafwk/base/int_wrapper.h" using namespace testing::ext; namespace OHOS { namespace Notification { - static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); bool OnConsumedReceived = false; @@ -55,12 +56,13 @@ const int32_t CASE_TWELVE = 12; const int32_t CASE_THIRTEEN = 13; const int32_t CASE_FOURTEEN = 14; const int32_t CASE_FIFTEEN = 15; -const int32_t CASE_SIXTEEN = 16; const int32_t CALLING_UID = 9999; const int32_t PIXEL_MAP_TEST_WIDTH = 32; const int32_t PIXEL_MAP_TEST_HEIGHT = 32; +const int32_t CANCELGROUP_NID = 10101; + std::mutex g_subscribe_mtx; std::mutex g_consumed_mtx; std::mutex g_unsubscribe_mtx; @@ -68,16 +70,16 @@ std::mutex g_send_finished_mtx; AAFwk::Want g_want; const time_t TIME_OUT_SECONDS_LIMIT = 5; -const std::string CLASSIFICATION_ALARM{"alarm"}; +const std::string CLASSIFICATION_ALARM {"alarm"}; class TestAnsSubscriber : public NotificationSubscriber { public: - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + virtual void OnConnected() override { g_subscribe_mtx.unlock(); } - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + virtual void OnDisconnected() override { g_unsubscribe_mtx.unlock(); } @@ -88,11 +90,12 @@ public: virtual void OnUpdate(const std::shared_ptr &sortingMap) override {} - virtual void OnDisturbModeChanged(int disturbMode) override + virtual void OnDoNotDisturbDateChange(const std::shared_ptr &date) override {} virtual void OnCanceled(const std::shared_ptr &request) override { + GTEST_LOG_(INFO) << "ANS_Interface_MT::OnCanceled request : " << request->GetNotificationRequest().Dump(); OnCanceledReceived = true; } @@ -105,7 +108,6 @@ public: OnConsumedReceived = true; g_consumed_mtx.unlock(); NotificationRequest notificationRequest = request->GetNotificationRequest(); - NotificationConstant::DisturbMode disturbMode; if (CASE_ONE == notificationRequest.GetNotificationId()) { CheckCaseOneResult(notificationRequest); } else if (CASE_TWO == notificationRequest.GetNotificationId()) { @@ -131,17 +133,12 @@ public: } else if (CASE_TWELVE == notificationRequest.GetNotificationId()) { EXPECT_EQ(NotificationConstant::CUSTOM, notificationRequest.GetSlotType()); } else if (CASE_THIRTEEN == notificationRequest.GetNotificationId()) { - EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); - EXPECT_EQ(NotificationConstant::ALLOW_ALARMS, disturbMode); - } else if (CASE_FOURTEEN == notificationRequest.GetNotificationId()) { - EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); - EXPECT_EQ(NotificationConstant::ALLOW_ALL, disturbMode); - } else if (CASE_FIFTEEN == notificationRequest.GetNotificationId()) { - EXPECT_EQ(0, NotificationHelper::GetDisturbMode(disturbMode)); - EXPECT_EQ(NotificationConstant::ALLOW_NONE, disturbMode); - } else if (CASE_SIXTEEN == notificationRequest.GetNotificationId()) { EXPECT_EQ(NotificationRequest::GroupAlertType::ALL, notificationRequest.GetGroupAlertType()); EXPECT_EQ(true, notificationRequest.IsGroupOverview()); + } else if (CASE_FOURTEEN == notificationRequest.GetNotificationId()) { + CheckCaseFourteenResult(notificationRequest); + } else if (CASE_FIFTEEN == notificationRequest.GetNotificationId()) { + CheckCaseFifteenResult(notificationRequest); } else { GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish::OnConsumed do nothing!!!!!"; } @@ -347,7 +344,7 @@ private: EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); EXPECT_EQ(false, notificationRequest.IsColorEnabled()); EXPECT_EQ(false, notificationRequest.IsCountdownTimer()); - EXPECT_EQ("groupvalue", notificationRequest.GetGroupValue()); + EXPECT_EQ("groupvalue", notificationRequest.GetGroupName()); EXPECT_EQ(true, notificationRequest.IsOnlyLocal()); EXPECT_EQ("setting text", notificationRequest.GetSettingsText()); EXPECT_EQ(false, notificationRequest.IsShowStopwatch()); @@ -363,6 +360,27 @@ private: EXPECT_EQ(0, notificationRequest.GetProgressValue()); EXPECT_EQ(false, notificationRequest.IsProgressIndeterminate()); } + + void CheckCaseFourteenResult(const NotificationRequest& notificationRequest) const + { + std::shared_ptr notiTemplate = notificationRequest.GetTemplate(); + if (notiTemplate != nullptr) { + EXPECT_EQ("process", notiTemplate->GetTemplateName()); + std::shared_ptr param = notiTemplate->GetTemplateData(); + int value = AAFwk::Integer::Unbox(AAFwk::IInteger::Query(param->GetParam("process"))); + EXPECT_EQ(20, value); // 20 test input + } + EXPECT_EQ(NotificationConstant::OTHER, notificationRequest.GetSlotType()); + } + + void CheckCaseFifteenResult(NotificationRequest notificationRequest) + { + std::shared_ptr notiFlags = notificationRequest.GetFlags(); + if (notiFlags != nullptr) { + EXPECT_EQ(false, notiFlags->IsSoundEnabled()); + EXPECT_EQ(true, notiFlags->IsVibrationEnabled()); + } + } }; class CompletedCallbackTest : public WantAgent::CompletedCallback { @@ -388,6 +406,7 @@ public: void WaitOnSubscribeResult(); void WaitOnConsumed(); void WaitOnUnsubscribeResult(); + void CheckJsonConverter(const NotificationRequest *request); }; void AnsInterfaceModulePublishTest::SetUpTestCase() @@ -464,6 +483,42 @@ void AnsInterfaceModulePublishTest::WaitOnUnsubscribeResult() } } +void AnsInterfaceModulePublishTest::CheckJsonConverter(const NotificationRequest *request) +{ + nlohmann::json jsonObject; + auto ret0 = NotificationJsonConverter::ConvertToJosn(request, jsonObject); + EXPECT_EQ(ret0, true); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosn object dump ==========>" << jsonObject.dump(); + + std::string jsonString; + auto ret1 = NotificationJsonConverter::ConvertToJosnString(request, jsonString); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosnString ret1 ==========>" + << (ret1 ? "true" : "false"); + EXPECT_EQ(ret1, true); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosnString string ==========>" << jsonString; + + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::convert Json sleep start ==========>"; + sleep(SLEEP_TIME); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::convert Json sleep end ==========>"; + + auto pRequest1 = NotificationJsonConverter::ConvertFromJosn(jsonObject); + EXPECT_NE(pRequest1, nullptr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJosn jsonObject dump request ==========>" + << pRequest1->Dump(); + + auto pRequest2 = NotificationJsonConverter::ConvertFromJosnString(jsonString); + EXPECT_NE(pRequest2, nullptr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertFromJosnString jsonString dump request ==========>" + << pRequest2->Dump(); + + nlohmann::json jsonObject2; + auto ret2 = NotificationJsonConverter::ConvertToJosn(pRequest1, jsonObject2); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::ConvertToJosn ret2 ==========>" << (ret2 ? "true" : "false"); + EXPECT_EQ(ret2, true); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::FromJson -> ToJson object dump ==========>" + << jsonObject2.dump(); +} + /** * @tc.number : ANS_Interface_MT_Publish_00100 * @tc.name : Publish_00100 @@ -572,17 +627,17 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00200, Function NotificationActionButton::Create(nullptr, "title", wantAgent); std::shared_ptr userInput = NotificationUserInput::Create("inputKey"); std::vector> userInputs; - AppExecFwk::PacMap pacMap; + AAFwk::WantParams additional; std::map> results; std::vector options; std::set permitMimeTypes; - std::shared_ptr pacMapPtr; + std::shared_ptr additionalPtr; userInput->SetInputsSource(g_want, NotificationConstant::FREE_FORM_INPUT); - userInput->AddInputsToWant(userInputs, g_want, pacMap); + userInput->AddInputsToWant(userInputs, g_want, additional); std::shared_ptr userInputMine = NotificationUserInput::Create( - "Key", "tag", options, false, permitMimeTypes, pacMapPtr, NotificationConstant::EDIT_AUTO); + "Key", "tag", options, false, permitMimeTypes, additionalPtr, NotificationConstant::EDIT_AUTO); userInput->AddMimeInputToWant(*userInputMine, g_want, results); - userInput->AddAdditionalData(pacMap); + userInput->AddAdditionalData(additional); userInput->SetEditType(NotificationConstant::EDIT_DISABLED); userInput->SetOptions(options); userInput->SetPermitMimeTypes("mimeType", false); @@ -633,8 +688,8 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00300, Function std::shared_ptr actionButton = NotificationActionButton::Create(nullptr, "title", wantAgent); std::shared_ptr onlyUserInput = NotificationUserInput::Create("onlyUserInputKey"); - AppExecFwk::PacMap pacMap; - actionButton->AddAdditionalData(pacMap); + AAFwk::WantParams additional; + actionButton->AddAdditionalData(additional); actionButton->SetSemanticActionButton(NotificationConstant::NONE_ACTION_BUTTON); actionButton->SetAutoCreatedReplies(true); actionButton->AddMimeTypeOnlyUserInput(onlyUserInput); @@ -885,7 +940,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_00900, Function req.SetNotificationId(CASE_NINE); req.SetColorEnabled(false); req.SetCountdownTimer(false); - req.SetGroupValue("groupvalue"); + req.SetGroupName("groupvalue"); req.SetOnlyLocal(true); req.SetSettingsText("setting text"); req.SetShowStopwatch(false); @@ -1005,22 +1060,21 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_03000, Function } /** - * @tc.number : ANS_Interface_MT_Publish_04000 - * @tc.name : Publish_04000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification in - * disturbed mode (mode is ALLOW_ALARMS) - * @tc.expected : Add notification slot success, make a subscriber and a publish notification in undisturbed mode - * success. + * @tc.number : ANS_Interface_MT_Publish_07000 + * @tc.name : Publish_07000 + * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a local group + * notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a local group notification success. */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function | MediumTest | Level1) +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_07000, Function | MediumTest | Level1) { NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + slot.EnableBypassDnd(true); EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); auto subscriber = TestAnsSubscriber(); g_subscribe_mtx.lock(); EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALARMS)); MessageUser messageUser; std::shared_ptr normalContent = std::make_shared(); EXPECT_NE(normalContent, nullptr); @@ -1029,8 +1083,10 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function NotificationRequest req; req.SetContent(content); req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); - req.SetClassification(CLASSIFICATION_ALARM); + req.SetGroupName("groupnotifcation"); + req.SetGroupOverview(true); req.SetNotificationId(CASE_THIRTEEN); + req.SetGroupAlertType(NotificationRequest::GroupAlertType::ALL); g_consumed_mtx.lock(); EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); WaitOnConsumed(); @@ -1040,168 +1096,287 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function } /** - * @tc.number : ANS_Interface_MT_Publish_05000 - * @tc.name : Publish_05000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification - * in disturbed mode (mode is ALLOW_ALL) - * @tc.expected : Add notification slot success, make a subscriber and pulish a notification in undisturbed mode - * success. + * @tc.number : ANS_FW_MT_GetActiveNotifications_00100 + * @tc.name : GetActiveNotifications_00100 + * @tc.desc : Get the active notifications and the number of active notifications of the current application. + * @tc.expected : Get the active notifications success and the number of active notifications of the current + * application is right. */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_05000, Function | MediumTest | Level1) +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_00100, Function | MediumTest | Level1) { - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALL)); - MessageUser messageUser; - std::shared_ptr normalContent = std::make_shared(); - EXPECT_NE(normalContent, nullptr); - std::shared_ptr content = std::make_shared(normalContent); + std::shared_ptr implContent = std::make_shared(); + EXPECT_NE(implContent, nullptr); + std::shared_ptr content = std::make_shared(implContent); EXPECT_NE(content, nullptr); - NotificationRequest req; - req.SetContent(content); - req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); - req.SetNotificationId(CASE_FOURTEEN); + EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::CancelAllNotifications()); + sleep(SLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, true); + int countBefor = 0; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); + EXPECT_EQ(0, countBefor); + std::string label1 = "Label1"; + NotificationRequest req1(0); + req1.SetLabel(label1); + req1.SetContent(content); g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); WaitOnConsumed(); - // Wait OnUnsubscribeResult + OnConsumedReceived = false; + g_consumed_mtx.unlock(); + std::string label2 = "Label2"; + NotificationRequest req2(0); + req2.SetLabel(label2); + req2.SetContent(content); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); + WaitOnConsumed(); + int countAfter = 0; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); + EXPECT_EQ(ACTIVE_NUMS, countAfter); + std::vector> requests; + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(requests)); + EXPECT_EQ("Label1", requests[0]->GetLabel()); + EXPECT_EQ("Label2", requests[1]->GetLabel()); + EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); + sleep(SLEEP_TIME); + EXPECT_EQ(OnCanceledReceived, true); + EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); + EXPECT_EQ(0, countAfter); g_unsubscribe_mtx.lock(); EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); WaitOnUnsubscribeResult(); + OnCanceledReceived = false; } /** - * @tc.number : ANS_Interface_MT_Publish_06000 - * @tc.name : Publish_06000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification - * in disturbed mode (mode is ALLOW_NONE) - * @tc.expected : Add notification slot success, make a subscriber and pulush a notification in undisturbed mode - * success. + * @tc.number : ANS_FW_MT_CancelGroup_10100 + * @tc.name : CancelGroup_10100 + * @tc.desc : Cancel the notifications of the same group. + * @tc.expected : All notifications of the same group have been cancelled. */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_06000, Function | MediumTest | Level1) +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_CancelGroup_10100, Function | MediumTest | Level1) { - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - slot.EnableBypassDnd(true); - EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + auto subscriber = TestAnsSubscriber(); g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_NONE)); - MessageUser messageUser; + std::shared_ptr normalContent = std::make_shared(); EXPECT_NE(normalContent, nullptr); + GTEST_LOG_(INFO) << "ANS_Interface_MT_CancelGroup_10100::normalContentis::" << normalContent->Dump(); std::shared_ptr content = std::make_shared(normalContent); EXPECT_NE(content, nullptr); + NotificationRequest req; req.SetContent(content); - req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); - req.SetNotificationId(CASE_FIFTEEN); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CANCELGROUP_NID); + req.SetLabel("CancelGroup_10100"); + req.SetGroupName("group10100"); + g_consumed_mtx.lock(); EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); WaitOnConsumed(); + OnConsumedReceived = false; + + GTEST_LOG_(INFO) << "ANS_Interface_MT_CancelGroup_10100:: call CancelGroup : effective parameters"; + EXPECT_EQ(0, NotificationHelper::CancelGroup("group10100")); + + sleep(SLEEP_TIME); + OnCanceledReceived = false; + + GTEST_LOG_(INFO) << "ANS_Interface_MT_CancelGroup_10100:: call CancelGroup : invalid parameters"; + EXPECT_EQ(0, NotificationHelper::CancelGroup("ngroup")); + + sleep(SLEEP_TIME); + OnCanceledReceived = false; + + req.SetOwnerBundleName("mybundlename"); + req.SetCreatorBundleName("mybundlename"); + g_consumed_mtx.unlock(); + g_consumed_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); + WaitOnConsumed(); + OnConsumedReceived = false; + + NotificationBundleOption bo("bundlename", 0); + GTEST_LOG_(INFO) << "ANS_Interface_MT_CancelGroup_10100:: call RemoveGroupByBundle : effective parameters"; + EXPECT_NE(0, NotificationHelper::RemoveGroupByBundle(bo, "group10100")); + + sleep(SLEEP_TIME); + OnCanceledReceived = false; + + GTEST_LOG_(INFO) << "ANS_Interface_MT_CancelGroup_10100:: call RemoveGroupByBundle : invalid parameters"; + EXPECT_NE(0, NotificationHelper::RemoveGroupByBundle(bo, "ngroup")); + + sleep(SLEEP_TIME); + OnCanceledReceived = false; + g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); } /** - * @tc.number : ANS_Interface_MT_Publish_07000 - * @tc.name : Publish_07000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a local group - * notification. - * @tc.expected : Add notification slot success, make a subscriber and publish a local group notification success. + * @tc.number : ANS_Interface_MT_Publish_04000 + * @tc.name : Publish_04000 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a template notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a ltemplate notification success. */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_07000, Function | MediumTest | Level1) +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function | MediumTest | Level1) { - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - slot.EnableBypassDnd(true); + NotificationSlot slot(NotificationConstant::OTHER); EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); auto subscriber = TestAnsSubscriber(); + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); WaitOnSubscribeResult(); - MessageUser messageUser; + + std::shared_ptr notiTemplate = std::make_shared(); + EXPECT_NE(notiTemplate, nullptr); + notiTemplate->SetTemplateName("process"); + // [{'process':20}] + AAFwk::WantParams wantParams; + std::string key("process"); + int resultValue = 20; + wantParams.SetParam(key, AAFwk::Integer::Box(resultValue)); + notiTemplate->SetTemplateData(std::make_shared(wantParams)); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_04000::notiTemplate::" << notiTemplate->Dump(); std::shared_ptr normalContent = std::make_shared(); EXPECT_NE(normalContent, nullptr); std::shared_ptr content = std::make_shared(normalContent); EXPECT_NE(content, nullptr); NotificationRequest req; req.SetContent(content); - req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); - req.SetGroupValue("groupnotifcation"); - req.SetGroupOverview(true); - req.SetNotificationId(CASE_SIXTEEN); - req.SetGroupAlertType(NotificationRequest::GroupAlertType::ALL); + req.SetTemplate(notiTemplate); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_FOURTEEN); g_consumed_mtx.lock(); EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); WaitOnConsumed(); g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); } /** - * @tc.number : ANS_FW_MT_GetActiveNotifications_00100 - * @tc.name : GetActiveNotifications_00100 - * @tc.desc : Get the active notifications and the number of active notifications of the current application. - * @tc.expected : Get the active notifications success and the number of active notifications of the current - * application is right. + * @tc.number : ANS_Interface_MT_Publish_08000 + * @tc.name : Publish_08000 + * @tc.desc : . + * @tc.expected : . */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_00100, Function | MediumTest | Level1) +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_08000, Function | MediumTest | Level1) { + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_08000::convert Json start ############==========>"; + + NotificationRequest req; + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + normalContent->SetTitle("normal_title"); + normalContent->SetText("normal_text"); + normalContent->SetAdditionalText("normal_additional_text"); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_00800::normalContent::" << normalContent->Dump(); + + std::shared_ptr content = std::make_shared(normalContent); + EXPECT_NE(content, nullptr); + + req.SetNotificationId(8000); + req.SetContent(content); + req.SetSlotType(NotificationConstant::CONTENT_INFORMATION); + req.SetClassification(NotificationRequest::CLASSIFICATION_ALARM); + req.SetLabel("label"); + req.SetOwnerBundleName("owner"); + + auto wAgent1 = std::make_shared(); + req.SetWantAgent(wAgent1); + + auto wAgent2 = std::make_shared(); + std::shared_ptr dummyIcon; + auto ab1 = NotificationActionButton::Create(dummyIcon, "ab1_title", wAgent2); + + auto spUserInput3 = NotificationUserInput::Create("uikey3"); + auto spUserInput2 = NotificationUserInput::Create("uikey2"); + ab1->AddNotificationUserInput(spUserInput3); + ab1->AddNotificationUserInput(spUserInput2); + auto spOnlyUserInput1 = NotificationUserInput::Create("uionlykey1"); + spOnlyUserInput1->SetPermitFreeFormInput(false); + spOnlyUserInput1->SetPermitMimeTypes("uionly", true); + auto spOnlyUserInput4 = NotificationUserInput::Create("uionlykey4"); + spOnlyUserInput4->SetPermitFreeFormInput(false); + spOnlyUserInput4->SetPermitMimeTypes("uionly", true); + + ab1->AddMimeTypeOnlyUserInput(spOnlyUserInput1); + ab1->AddMimeTypeOnlyUserInput(spOnlyUserInput4); + + std::shared_ptr dummyWantAgent; + auto ab2 = NotificationActionButton::Create(dummyIcon, "ab2_title", dummyWantAgent); + + req.AddActionButton(ab1); + req.AddActionButton(ab2); + + std::vector history {"uihistory3", "uihistory2", "uihistory1"}; + req.SetNotificationUserInputHistory(history); + + auto msgUser1 = std::make_shared(); + msgUser1->SetKey("msgUser1_key"); + msgUser1->SetName("msgUser1_name"); + auto msgUser2 = std::make_shared(); + msgUser2->SetKey("msgUser2_key"); + msgUser2->SetName("msgUser2_name"); + req.AddMessageUser(msgUser2); + req.AddMessageUser(msgUser1); + + CheckJsonConverter(&req); +} + +/** + * @tc.number : ANS_Interface_MT_Publish_05000 + * @tc.name : Publish_05000 + * @tc.desc : Add notification slot(type is OTHER), make a subscriber and publish a flags notification. + * @tc.expected : Add notification slot success, make a subscriber and publish a flags notification success. + */ +HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_05000, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); auto subscriber = TestAnsSubscriber(); NotificationSubscribeInfo info = NotificationSubscribeInfo(); info.AddAppName("bundleName"); g_subscribe_mtx.lock(); EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); WaitOnSubscribeResult(); - std::shared_ptr implContent = std::make_shared(); - EXPECT_NE(implContent, nullptr); - std::shared_ptr content = std::make_shared(implContent); + + std::shared_ptr notiFlags = std::make_shared(); + EXPECT_NE(notiFlags, nullptr); + notiFlags->SetSoundEnabled(false); + notiFlags->SetVibrationEnabled(true); + GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish_04000::flags::" << notiFlags->Dump(); + std::shared_ptr normalContent = std::make_shared(); + EXPECT_NE(normalContent, nullptr); + std::shared_ptr content = std::make_shared(normalContent); EXPECT_NE(content, nullptr); - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::CancelAllNotifications()); - sleep(SLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - int countBefor = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countBefor)); - EXPECT_EQ(0, countBefor); - std::string label1 = "Label1"; - NotificationRequest req1(0); - req1.SetLabel(label1); - req1.SetContent(content); - g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req1)); - WaitOnConsumed(); - OnConsumedReceived = false; - g_consumed_mtx.unlock(); - std::string label2 = "Label2"; - NotificationRequest req2(0); - req2.SetLabel(label2); - req2.SetContent(content); + NotificationRequest req; + req.SetContent(content); + req.SetFlags(notiFlags); + req.SetSlotType(NotificationConstant::OTHER); + req.SetNotificationId(CASE_FIFTEEN); g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req2)); + EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); WaitOnConsumed(); - int countAfter = 0; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); - EXPECT_EQ(ACTIVE_NUMS, countAfter); - std::vector> requests; - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotifications(requests)); - EXPECT_EQ("Label1", requests[0]->GetLabel()); - EXPECT_EQ("Label2", requests[1]->GetLabel()); - EXPECT_EQ((int)ERR_OK, (int)NotificationHelper::RemoveNotifications()); - sleep(SLEEP_TIME); - EXPECT_EQ(OnCanceledReceived, true); - EXPECT_EQ((int)ERR_OK, NotificationHelper::GetActiveNotificationNums(countAfter)); - EXPECT_EQ(0, countAfter); g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); - OnCanceledReceived = false; } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp index 98a38c06f1a527c1853775734f460935c608b9c6..a34cdb20e850acab50001e0717857aba44b584dd 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp @@ -28,7 +28,6 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); const int32_t CALLING_UID = 9998; @@ -73,7 +72,7 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_001 EXPECT_EQ(0, NotificationHelper::SetShowBadgeEnabledForBundle(bundleOption, true)); bool enabled = false; EXPECT_EQ(0, NotificationHelper::GetShowBadgeEnabledForBundle(bundleOption, enabled)); - EXPECT_EQ(true,enabled); + EXPECT_EQ(true, enabled); EXPECT_EQ("bundlename", bundleOption.GetBundleName()); EXPECT_EQ(CALLING_UID, bundleOption.GetUid()); } @@ -91,7 +90,7 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_002 EXPECT_EQ(0, NotificationHelper::SetShowBadgeEnabledForBundle(bundleOption, false)); bool enabled = false; EXPECT_EQ(0, NotificationHelper::GetShowBadgeEnabledForBundle(bundleOption, enabled)); - EXPECT_EQ(false,enabled); + EXPECT_EQ(false, enabled); EXPECT_EQ("bundlename", bundleOption.GetBundleName()); EXPECT_EQ(CALLING_UID, bundleOption.GetUid()); } @@ -111,7 +110,7 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_003 EXPECT_EQ(0, NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(bundleOption, deviceId, true)); bool enabled = false; EXPECT_EQ(0, NotificationHelper::IsAllowedNotify(bundleOption, enabled)); - EXPECT_EQ(true,enabled); + EXPECT_EQ(true, enabled); EXPECT_EQ("bundlename", bundleOption.GetBundleName()); EXPECT_EQ(CALLING_UID, bundleOption.GetUid()); } @@ -119,8 +118,8 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_003 /** * @tc.number : ANS_Interface_MT_NotificationSetting_00400 * @tc.name : NotificationSetting_00400 - * @tc.desc : Set a specified application do not publish notification, get the specified application can not publish - * notification. + * @tc.desc : Set a specified application do not publish notification, get the specified application can not + * publish notification. * @tc.expected : Set a specified application do not publish notification success, get the specified application can * not publish notification. */ @@ -131,9 +130,52 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_004 EXPECT_EQ(0, NotificationHelper::SetNotificationsEnabledForSpecifiedBundle(bundleOption, deviceId, false)); bool enabled = false; EXPECT_EQ(0, NotificationHelper::IsAllowedNotify(bundleOption, enabled)); - EXPECT_EQ(false,enabled); + EXPECT_EQ(false, enabled); EXPECT_EQ("bundlename", bundleOption.GetBundleName()); EXPECT_EQ(CALLING_UID, bundleOption.GetUid()); } + +/** + * @tc.number : ANS_Interface_MT_NotificationSetting_00500 + * @tc.name : NotificationSetting_00500 + * @tc.desc : If the template configuration file does not exist, query whether the template exists. + * @tc.expected : Query return failed. + */ +HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_00500, Function | MediumTest | Level1) +{ + std::string templateName("process"); + bool support = false; + EXPECT_EQ((int)ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED, + NotificationHelper::IsSupportTemplate(templateName, support)); + EXPECT_EQ(false, support); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSetting_00600 + * @tc.name : NotificationSetting_00600 + * @tc.desc : The template exists in the system, query whether the template exists. + * @tc.expected : Query return success. + */ +HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_00600, Function | MediumTest | Level1) +{ + std::string templateName("process"); + bool support = false; + EXPECT_EQ(0, NotificationHelper::IsSupportTemplate(templateName, support)); + EXPECT_EQ(true, support); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSetting_00700 + * @tc.name : NotificationSetting_00700 + * @tc.desc : The template does not exist in the system, query whether the template exists. + * @tc.expected : Query return failed. + */ +HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_00700, Function | MediumTest | Level1) +{ + std::string templateName("template123"); + bool support = false; + EXPECT_EQ(0, NotificationHelper::IsSupportTemplate(templateName, support)); + EXPECT_EQ(false, support); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp index e7ced933603477f836afef13d7cccccf66b00ee6..31675f210c0dd47e995022d567ba435ab176a3da 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -15,20 +15,20 @@ #include #include +#include "advanced_notification_service.h" +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.h" -#include "advanced_notification_service.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" -#include "notification_helper.h" #include "mock_bundle_manager.h" #include "mock_ipc_skeleton.h" +#include "notification_helper.h" #include "system_ability_definition.h" using namespace testing::ext; namespace OHOS { namespace Notification { - static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); const int32_t CALLING_UID = 9998; @@ -315,6 +315,74 @@ HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00500, Fu NotificationHelper::GetNotificationSlot(NotificationConstant::OTHER, spSlot)); } +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00600 + * @tc.name : NotificationSlot_00600 + * @tc.desc : Create notification slot(type is SOCIAL_COMMUNICATION), get sound and vibration. + * @tc.expected : Create notification slot success, get sound and vibration success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00600, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); + EXPECT_EQ("SOCIAL_COMMUNICATION", slot.GetName()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, slot.GetLockScreenVisibleness()); + EXPECT_EQ(DEFAULT_NOTIFICATION_SOUND.ToString(), slot.GetSound().ToString()); + EXPECT_TRUE(slot.CanVibrate()); + EXPECT_EQ(DEFAULT_NOTIFICATION_VIBRATION, slot.GetVibrationStyle()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_HIGH, slot.GetLevel()); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00700 + * @tc.name : NotificationSlot_00700 + * @tc.desc : Create notification slot(type is SERVICE_REMINDER), get sound and vibration. + * @tc.expected : Create notification slot success, get sound and vibration success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00700, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::SERVICE_REMINDER); + EXPECT_EQ("SERVICE_REMINDER", slot.GetName()); + EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, slot.GetLockScreenVisibleness()); + EXPECT_EQ(DEFAULT_NOTIFICATION_SOUND.ToString(), slot.GetSound().ToString()); + EXPECT_TRUE(slot.CanVibrate()); + EXPECT_EQ(DEFAULT_NOTIFICATION_VIBRATION, slot.GetVibrationStyle()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_DEFAULT, slot.GetLevel()); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00800 + * @tc.name : NotificationSlot_00800 + * @tc.desc : Create notification slot(type is CONTENT_INFORMATION), get sound and vibration. + * @tc.expected : Create notification slot success, get sound and vibration success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00800, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::CONTENT_INFORMATION); + EXPECT_EQ("CONTENT_INFORMATION", slot.GetName()); + EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, slot.GetLockScreenVisibleness()); + EXPECT_EQ("", slot.GetSound().ToString()); + EXPECT_FALSE(slot.CanVibrate()); + EXPECT_EQ(0U, slot.GetVibrationStyle().size()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, slot.GetLevel()); +} + +/** + * @tc.number : ANS_Interface_MT_NotificationSlot_00900 + * @tc.name : NotificationSlot_00900 + * @tc.desc : Create notification slot(type is OTHER), get sound and vibration. + * @tc.expected : Create notification slot success, get sound and vibration success. + */ +HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00900, Function | MediumTest | Level1) +{ + NotificationSlot slot(NotificationConstant::OTHER); + EXPECT_EQ("OTHER", slot.GetName()); + EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, slot.GetLockScreenVisibleness()); + EXPECT_EQ("", slot.GetSound().ToString()); + EXPECT_FALSE(slot.CanVibrate()); + EXPECT_EQ(0U, slot.GetVibrationStyle().size()); + EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_MIN, slot.GetLevel()); +} + /** * @tc.number : ANS_Interface_MT_NotificationSlotGroup_00100 * @tc.name : NotificationSlotGroup_00100 diff --git a/frameworks/ans/test/moduletest/config.json b/frameworks/ans/test/moduletest/config.json new file mode 100644 index 0000000000000000000000000000000000000000..7d3bb1663873510fc00c1203273ad743dfbb2f43 --- /dev/null +++ b/frameworks/ans/test/moduletest/config.json @@ -0,0 +1,61 @@ +{ + "app": { + "bundleName": "com.example.myapplication", + "vendor": "example", + "version": { + "code": 1, + "name": "1.0" + }, + "apiVersion": { + "compatible": 4, + "target": 8 + } + }, + "deviceConfig": {}, + "module": { + "package": "com.example.myapplication", + "name": ".MyApplication", + "deviceType": [ + "phone" + ], + "distro": { + "deliveryWithInstall": true, + "moduleName": "entry", + "moduleType": "entry" + }, + "abilities": [ + { + "visible": true, + "skills": [ + { + "entities": [ + "entity.system.home" + ], + "actions": [ + "action.system.home" + ] + } + ], + "name": "com.example.myapplication.MainAbility", + "icon": "$media:icon", + "description": "$string:mainability_description", + "label": "MyApplication", + "type": "page", + "launchType": "standard" + } + ], + "js": [ + { + "pages": [ + "pages/index/index" + ], + "name": "default", + "window": { + "designWidth": 720, + "autoDesignWidth": false + } + } + ] + } + } + \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/blob.cpp b/frameworks/ans/test/moduletest/mock/blob.cpp index 93d2c34700f2b1d15a38ad135a6299d3450168bb..540888d0f6f0bddd56e2f06b1af89b6658802a38 100644 --- a/frameworks/ans/test/moduletest/mock/blob.cpp +++ b/frameworks/ans/test/moduletest/mock/blob.cpp @@ -17,7 +17,6 @@ #include "blob.h" #include -#include "log_print.h" namespace OHOS { namespace DistributedKv { @@ -111,7 +110,6 @@ bool Blob::Empty() const uint8_t Blob::operator[](size_t n) const { if (n >= Size()) { - ZLOGE("Trying to get a out-of-range Blob member."); return 0; } return blob_[n]; diff --git a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp index d755b0151ac19b60f4e18e540bc2c2488c1895fc..cc1b371db9efe4c6bad055466e3dd5bff445f840 100644 --- a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -16,7 +16,6 @@ #define LOG_TAG "DistributedKvDataManager" #include "distributed_kv_data_manager.h" -#include "constant.h" #include "mock_single_kv_store.h" #include "types.h" @@ -28,28 +27,49 @@ DistributedKvDataManager::DistributedKvDataManager() DistributedKvDataManager::~DistributedKvDataManager() {} -void DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, - std::function)> callback) +Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, + std::shared_ptr &kvStore) { - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - Status status = Status::SUCCESS; - std::unique_ptr proxyTmp = std::make_unique(); - callback(status, std::move(proxyTmp)); + std::string storeIdTmp = storeId.storeId; + kvStore = std::make_shared(); + AnsTestSingleKvStore::InsertMockKvStore(appId, storeId, kvStore); + return Status::SUCCESS; } -Status DistributedKvDataManager::CloseKvStore( - const AppId &appId, const StoreId &storeId, std::unique_ptr kvStorePtr) +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId) { return Status::SUCCESS; } -Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::unique_ptr kvStorePtr) +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr &kvStorePtr) { return Status::SUCCESS; } Status DistributedKvDataManager::DeleteKvStore(const AppId &appId, const StoreId &storeId) { + AnsTestSingleKvStore::RemoveMockKvStore(appId, storeId); + return Status::SUCCESS; +} + +Status DistributedKvDataManager::GetLocalDevice(DeviceInfo &localDevice) +{ + localDevice.deviceId = ""; + localDevice.deviceName = ""; + localDevice.deviceType = ""; + return Status::SUCCESS; +} + +Status DistributedKvDataManager::GetDeviceList(std::vector &deviceInfoList, DeviceFilterStrategy strategy) +{ + DeviceInfo remoteDevice = { + .deviceId = "", + .deviceName = "", + .deviceType = "", + }; + deviceInfoList.clear(); + deviceInfoList.push_back(remoteDevice); + return Status::SUCCESS; } diff --git a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h index fd4ac0f63f83da320a137fb47b9b3d22ca4d9d22..da5c0719644c357dea6541ce9cdee06fd4138da6 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -69,9 +69,11 @@ public: * @param bundleName Indicates the application bundle name to be queried. * @param flag Indicates the information contained in the BundleInfo object to be returned. * @param bundleInfo Indicates the obtained BundleInfo object. + * @param userId Indicates the user ID. * @return Returns true if the BundleInfo is successfully obtained; returns false otherwise. */ - virtual bool GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) override + virtual bool GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) override { return true; } @@ -79,9 +81,11 @@ public: * @brief Obtains BundleInfo of all bundles available in the system. * @param flag Indicates the flag used to specify information contained in the BundleInfo that will be returned. * @param bundleInfos Indicates all of the obtained BundleInfo objects. + * @param userId Indicates the user ID. * @return Returns true if the BundleInfos is successfully obtained; returns false otherwise. */ - virtual bool GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) override + virtual bool GetBundleInfos( + const BundleFlag flag, std::vector &bundleInfos, int32_t userId) override { return true; }; @@ -425,7 +429,7 @@ public: * @param bundleName Indicates the bundle name of the application whose data is to be cleared. * @return Returns true if the data cleared successfully; returns false otherwise. */ - virtual bool CleanBundleDataFiles(const std::string &bundleName) override + virtual bool CleanBundleDataFiles(const std::string &bundleName, const int userId) override { return true; } @@ -459,10 +463,12 @@ public: * @brief Dump the bundle informations with specifc flags. * @param flag Indicates the information contained in the dump result. * @param bundleName Indicates the bundle name if needed. + * @param userId Indicates the user ID. * @param result Indicates the dump infomation result. * @return Returns true if the dump result is successfully obtained; returns false otherwise. */ - virtual bool DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) override + virtual bool DumpInfos( + const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) override { return true; } @@ -524,6 +530,14 @@ public: { return nullptr; } + /** + * @brief Obtains the interface used to create or delete user. + * @return Returns a pointer to IBundleUserMgr class if exist; returns nullptr otherwise. + */ + virtual sptr GetBundleUserMgr() override + { + return nullptr; + } void MockSetIsSystemApp(bool isSystemApp); diff --git a/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h b/frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h old mode 100755 new mode 100644 diff --git a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h index 59a5d5c0498ff53c455d313e343c31a284accd9a..e71772fb8e2cb3de0a86c3d2b20e7c58ed5744e6 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h @@ -17,6 +17,7 @@ #define ANS_MOCK_SINGLE_KV_STORE_H #include +#include #include #include "kvstore.h" @@ -29,7 +30,6 @@ namespace OHOS { namespace DistributedKv { - class AnsTestSingleKvStore : public SingleKvStore { public: virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; @@ -38,23 +38,22 @@ public: virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; - virtual void GetResultSet( - const Key &prefixKey, std::function)> callback) const override; + virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; - virtual void GetResultSetWithQuery(const std::string &query, - std::function)> callback) const override; + virtual Status GetResultSetWithQuery(const std::string &query, + std::shared_ptr &resultSet) const override; - virtual void GetResultSetWithQuery( - const DataQuery &query, std::function)> callback) const override; + virtual Status GetResultSetWithQuery(const DataQuery &query, + std::shared_ptr &resultSet) const override; - virtual Status CloseResultSet(std::unique_ptr resultSet) override; + virtual Status CloseResultSet(std::shared_ptr &resultSet) override; virtual Status GetCountWithQuery(const std::string &query, int &result) const override; virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; virtual Status Sync( - const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs = 0) override; + const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; virtual Status RemoveDeviceData(const std::string &device) override; @@ -95,8 +94,43 @@ public: virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, + const DataQuery &query) override; + + virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + virtual Status UnSubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + Status GetKvStoreSnapshot(std::shared_ptr observer, + std::shared_ptr &snapshot) const override; + + Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; + + Status Clear() override; + +public: + static void InsertMockKvStore(AppId appId, StoreId storeId, std::shared_ptr store); + static void RemoveMockKvStore(AppId appId, StoreId storeId); + static std::shared_ptr GetMockKvStorePointer(AppId appId, StoreId storeId); + struct Compare { + bool operator()(const Key &a, const Key &b) const + { + return a.Compare(b) == -1; + } + }; + + void InsertDataToDoCallback(const Key &key, const Value &value); + void UpdateDataToDoCallback(const Key &key, const Value &value); + void DeleteDataToDoCallback(const Key &key); + protected: - KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) override; + KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) override; + +private: + static std::mutex mutex_; + static std::map, std::shared_ptr> kvStoreMap_; + std::shared_ptr observer_; + std::map kvstore_; }; } // namespace DistributedKv } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp index 98fd912f35d5f6d390c92d69b070cc63c7eb10f8..4ee0032efcbee222a80e78a9c7d6bbe8734abaac 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - constexpr int SYSTEM_APP_UUID = 1000; void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index cd58a48388c28f596e09b1eb2933dfb6492ffd46..77116bd9ab40d3c96e336a84361c588167802c7e 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -24,18 +24,24 @@ namespace OHOS { namespace AppExecFwk { - -BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) +namespace { +bool distributedNotificationEnabled = true; +} +void MockSetDistributedNotificationEnabled(bool enable) { + distributedNotificationEnabled = enable; } +BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) +{} + BundleMgrProxy::~BundleMgrProxy() -{ -} +{} bool BundleMgrProxy::GetApplicationInfo( const std::string &appName, const ApplicationFlag flag, const int userId, ApplicationInfo &appInfo) { + appInfo.distributedNotificationEnabled = distributedNotificationEnabled; return true; } @@ -45,12 +51,14 @@ bool BundleMgrProxy::GetApplicationInfos( return true; } -bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) +bool BundleMgrProxy::GetBundleInfo( + const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo, int32_t userId) { + bundleInfo.uid = 1; return true; } -bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos) +bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos, int32_t userId) { return true; } @@ -183,7 +191,7 @@ bool BundleMgrProxy::CleanBundleCacheFiles( return true; } -bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName) +bool BundleMgrProxy::CleanBundleDataFiles(const std::string &bundleName, const int userId) { return true; } @@ -203,7 +211,7 @@ bool BundleMgrProxy::UnregisterBundleStatusCallback() return true; } -bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, std::string &result) +bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) { return true; } @@ -261,13 +269,13 @@ bool BundleMgrProxy::UnregisterPermissionsChanged(const sptr +template bool BundleMgrProxy::GetParcelableInfo(IBundleMgr::Message code, MessageParcel &data, T &parcelableInfo) { return true; } -template +template bool BundleMgrProxy::GetParcelableInfos(IBundleMgr::Message code, MessageParcel &data, std::vector &parcelableInfos) { return true; @@ -277,6 +285,5 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da { return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_change_notification.cpp b/frameworks/ans/test/moduletest/mock/mock_change_notification.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c255d13cb3e20870fa5235f574b302c93d0db4ce --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_change_notification.cpp @@ -0,0 +1,62 @@ +/* + * 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 "change_notification.h" + +namespace OHOS { +namespace DistributedKv { +ChangeNotification::ChangeNotification(std::vector &&insertEntries, std::vector &&updateEntries, + std::vector &&deleteEntries, const std::string &deviceId, const bool isClear) + : insertEntries_(insertEntries), + updateEntries_(updateEntries), + deleteEntries_(deleteEntries), + deviceId_(deviceId), + isClear_(isClear) +{} + +ChangeNotification::~ChangeNotification() +{} + +const std::vector &ChangeNotification::GetInsertEntries() const +{ + return this->insertEntries_; +} + +const std::vector &ChangeNotification::GetUpdateEntries() const +{ + return this->updateEntries_; +} + +const std::vector &ChangeNotification::GetDeleteEntries() const +{ + return this->deleteEntries_; +} + +const std::string &ChangeNotification::GetDeviceId() const +{ + return this->deviceId_; +} + +bool ChangeNotification::IsClear() const +{ + return this->isClear_; +} + +bool ChangeNotification::Marshalling(Parcel &parcel) const +{ + return true; +} +} // namespace DistributedKv +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/mock_common_event_data.cpp b/frameworks/ans/test/moduletest/mock/mock_common_event_data.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c03942bed7a21621bf1439552cf38c1299224839 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_common_event_data.cpp @@ -0,0 +1,36 @@ +/* + * 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 "common_event_data.h" + +namespace OHOS { +namespace EventFwk { +CommonEventData::CommonEventData() +{} + +CommonEventData::~CommonEventData() +{} + +void CommonEventData::SetWant(const Want &want) +{ + want_ = want; +} + +bool CommonEventData::Marshalling(Parcel &parcel) const +{ + return true; +} +} // namespace EventFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/mock_common_event_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_common_event_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..852a174701b3097ab9bd30184aef77cef82abe86 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_common_event_manager.cpp @@ -0,0 +1,61 @@ +/* + * 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 "common_event_manager.h" + +#include + +namespace OHOS { +namespace EventFwk { +namespace { +std::list> subscriberList; +} +bool CommonEventManager::PublishCommonEvent(const CommonEventData &data) +{ + for (auto subscriber : subscriberList) { + subscriber->OnReceiveEvent(data); + } + return true; +} + +bool CommonEventManager::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo) +{ + return true; +} + +bool CommonEventManager::PublishCommonEvent(const CommonEventData &data, const CommonEventPublishInfo &publishInfo, + const std::shared_ptr &subscriber) +{ + return true; +} + +bool CommonEventManager::SubscribeCommonEvent(const std::shared_ptr &subscriber) +{ + subscriberList.push_back(subscriber); + return true; +} + +bool CommonEventManager::UnSubscribeCommonEvent(const std::shared_ptr &subscriber) +{ + subscriberList.remove(subscriber); + return true; +} + +bool CommonEventManager::GetStickyCommonEvent(const std::string &event, CommonEventData &commonEventData) +{ + return true; +} +} // namespace EventFwk +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp index 12a7f65b9d4e00f3c9c65a4a8668e162960cb723..1bdf27e03013d421d5f9d2c1309a586a39401286 100644 --- a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp @@ -14,12 +14,9 @@ */ #include "event_handler.h" -#include "event_handler_utils.h" -#include namespace OHOS { namespace AppExecFwk { - std::shared_ptr EventHandler::Current() { const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); diff --git a/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp index 26b6304c7930522d66ea3a2c6e8fefefb1826ce4..49c18fba8d3d77799f4682f06ff36e906e0998a9 100644 --- a/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp @@ -13,9 +13,9 @@ * limitations under the License. */ -#include "message_parcel.h" #include #include +#include "message_parcel.h" #include "ipc_debug.h" #include "iremote_object.h" diff --git a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp index 85aed3fef5427378195420cc7428132c0a21d60d..d09801b062d04c4df2ad1133ba00de60b41c2197 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -14,13 +14,103 @@ */ #include "mock_single_kv_store.h" + #include "types.h" namespace OHOS { namespace DistributedKv { +std::mutex AnsTestSingleKvStore::mutex_; +std::map, std::shared_ptr> AnsTestSingleKvStore::kvStoreMap_; + +void AnsTestSingleKvStore::InsertMockKvStore(AppId appId, StoreId storeId, std::shared_ptr store) +{ + std::lock_guard lock(mutex_); + + kvStoreMap_[std::pair(appId.appId, storeId.storeId)] = store; +} + +void AnsTestSingleKvStore::RemoveMockKvStore(AppId appId, StoreId storeId) +{ + kvStoreMap_.erase(std::pair(appId.appId, storeId.storeId)); +} + +std::shared_ptr AnsTestSingleKvStore::GetMockKvStorePointer(AppId appId, StoreId storeId) +{ + for (auto kvstore : kvStoreMap_) { + if (kvstore.first == std::pair(appId.appId, storeId.storeId)) { + return std::static_pointer_cast(kvstore.second); + } + } + + return nullptr; +} + +void AnsTestSingleKvStore::InsertDataToDoCallback(const Key &key, const Value &value) +{ + Put(key, value); + if (observer_ != nullptr) { + Entry entry; + entry.key = key; + entry.value = value; + std::vector insertEntries; + std::vector updateEntries; + std::vector deleteEntries; + insertEntries.push_back(entry); + ChangeNotification change( + std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), "", false); + observer_->OnChange(change); + } +} + +void AnsTestSingleKvStore::UpdateDataToDoCallback(const Key &key, const Value &value) +{ + Put(key, value); + if (observer_ != nullptr) { + Entry entry; + entry.key = key; + entry.value = value; + std::vector insertEntries; + std::vector updateEntries; + std::vector deleteEntries; + updateEntries.push_back(entry); + ChangeNotification change( + std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), "", false); + observer_->OnChange(change); + } +} + +void AnsTestSingleKvStore::DeleteDataToDoCallback(const Key &key) +{ + Value value; + Get(key, value); + Delete(key); + if (observer_ != nullptr) { + Entry entry; + entry.key = key; + entry.value = value; + std::vector insertEntries; + std::vector updateEntries; + std::vector deleteEntries; + deleteEntries.push_back(entry); + ChangeNotification change( + std::move(insertEntries), std::move(updateEntries), std::move(deleteEntries), "", false); + observer_->OnChange(change); + } +} Status AnsTestSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const { + entries.clear(); + + for (auto iter : kvstore_) { + if (iter.first.StartsWith(prefixKey)) { + Entry entry; + entry.key = iter.first; + entry.value = iter.second; + entries.push_back(entry); + } + } + return Status::SUCCESS; } @@ -34,19 +124,24 @@ Status AnsTestSingleKvStore::GetEntriesWithQuery(const DataQuery &query, std::ve return Status::SUCCESS; } -void AnsTestSingleKvStore::GetResultSet( - const Key &prefixKey, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -void AnsTestSingleKvStore::GetResultSetWithQuery( - const std::string &query, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSetWithQuery( + const std::string &query, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -void AnsTestSingleKvStore::GetResultSetWithQuery( - const DataQuery &query, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSetWithQuery( + const DataQuery &query, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -Status AnsTestSingleKvStore::CloseResultSet(std::unique_ptr resultSet) +Status AnsTestSingleKvStore::CloseResultSet(std::shared_ptr &resultSet) { return Status::SUCCESS; } @@ -62,13 +157,15 @@ Status AnsTestSingleKvStore::GetCountWithQuery(const DataQuery &query, int &resu } Status AnsTestSingleKvStore::Sync( - const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) + const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs) { return Status::SUCCESS; } Status AnsTestSingleKvStore::RemoveDeviceData(const std::string &device) { + kvstore_.clear(); + return Status::SUCCESS; } @@ -81,26 +178,41 @@ StoreId AnsTestSingleKvStore::GetStoreId() const Status AnsTestSingleKvStore::Delete(const Key &key) { - return Status::SUCCESS; + if (kvstore_.erase(key) != 0) { + return Status::SUCCESS; + } + + return Status::KEY_NOT_FOUND; } Status AnsTestSingleKvStore::Put(const Key &key, const Value &value) { + kvstore_[key] = value; + return Status::SUCCESS; } Status AnsTestSingleKvStore::Get(const Key &key, Value &value) { - return Status::SUCCESS; + for (auto iter : kvstore_) { + if (iter.first == key) { + value = iter.second; + return Status::SUCCESS; + } + } + + return Status::KEY_NOT_FOUND; } Status AnsTestSingleKvStore::SubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) { + observer_ = observer; return Status::SUCCESS; } Status AnsTestSingleKvStore::UnSubscribeKvStore(SubscribeType subscribeType, std::shared_ptr observer) { + observer_ = nullptr; return Status::SUCCESS; } @@ -165,10 +277,41 @@ Status AnsTestSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) cons return Status::SUCCESS; } -Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) +Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SyncWithCondition(const std::vector &deviceIds, SyncMode mode, + const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) { return Status::SUCCESS; } +Status AnsTestSingleKvStore::UnSubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::GetKvStoreSnapshot( + std::shared_ptr observer, std::shared_ptr &snapshot) const +{ + return Status::NOT_SUPPORT; +} + +Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) +{ + return Status::NOT_SUPPORT; +} + +Status AnsTestSingleKvStore::Clear() +{ + return Status::NOT_SUPPORT; +} } // namespace DistributedKv -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/frameworks/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn index 29d0b471d53384dd9460e9f2e7973f037123b747..4c3a05b2a193f853b87ea053ac9c7ac4d0eb5c4f 100644 --- a/frameworks/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -26,13 +26,12 @@ config("wantagent_innerkits_public_config") { "//base/global/resmgr_standard/interfaces/innerkits/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/appmgr", + "//foundation/aafwk/standard/interfaces/innerkits/app_manager/include/appmgr", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include/bundlemgr", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/app/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "//third_party/icu/icu4c/source/common", ] } @@ -59,22 +58,24 @@ ohos_shared_library("wantagent_innerkits") { public_configs = [ ":wantagent_innerkits_public_config" ] deps = [ - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] if (is_double_framework) { diff --git a/frameworks/wantagent/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp index 926dbfc2d994fd94b0d7a287994321a1dfd31628..62fddd422e62541b3c80358b9c9b97fc60d0b25c 100644 --- a/frameworks/wantagent/src/pending_want.cpp +++ b/frameworks/wantagent/src/pending_want.cpp @@ -40,12 +40,14 @@ WantAgentConstant::OperationType PendingWant::GetType(const sptr PendingWant::GetAbility( - const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) { return GetAbility(context, requestCode, want, flags, nullptr); } -std::shared_ptr PendingWant::GetAbility(const std::shared_ptr &context, int requestCode, +std::shared_ptr PendingWant::GetAbility( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags, const std::shared_ptr &options) { WANT_AGENT_LOGI("PendingWant::GetAbility begin."); @@ -74,20 +76,21 @@ std::shared_ptr PendingWant::GetAbility(const std::shared_ptr(target); } -std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, int requestCode, - std::vector> &wants, unsigned int flags) +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, unsigned int flags) { return GetAbilities(context, requestCode, wants, flags, nullptr); } -std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, int requestCode, - std::vector> &wants, unsigned int flags, const std::shared_ptr &options) +std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr &context, + int requestCode, std::vector> &wants, + unsigned int flags, const std::shared_ptr &options) { if (context == nullptr) { WANT_AGENT_LOGE("PendingWant::GetAbilities invalid input param."); return nullptr; } - + WantSenderInfo wantSenderInfo; wantSenderInfo.type = (int32_t)WantAgentConstant::OperationType::START_ABILITIES; wantSenderInfo.bundleName = context->GetBundleName(); @@ -111,13 +114,15 @@ std::shared_ptr PendingWant::GetAbilities(const std::shared_ptr PendingWant::GetCommonEvent( - const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) { return GetCommonEventAsUser(context, requestCode, want, flags, 0); } -std::shared_ptr PendingWant::GetCommonEventAsUser(const std::shared_ptr &context, int requestCode, - const std::shared_ptr &want, unsigned int flags, int uid) +std::shared_ptr PendingWant::GetCommonEventAsUser( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags, int uid) { if (context == nullptr) { WANT_AGENT_LOGE("PendingWant::GetCommonEventAsUser invalid input param."); @@ -143,21 +148,25 @@ std::shared_ptr PendingWant::GetCommonEventAsUser(const std::shared } std::shared_ptr PendingWant::GetService( - const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags) { - return BuildServicePendingWant(context, requestCode, want, flags, WantAgentConstant::OperationType::START_SERVICE); + return BuildServicePendingWant(context, requestCode, want, flags, + WantAgentConstant::OperationType::START_SERVICE); } std::shared_ptr PendingWant::GetForegroundService( - const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags) + const std::shared_ptr &context, int requestCode, + const std::shared_ptr &want, unsigned int flags) { return BuildServicePendingWant( context, requestCode, want, flags, WantAgentConstant::OperationType::START_FOREGROUND_SERVICE); } -std::shared_ptr PendingWant::BuildServicePendingWant(const std::shared_ptr &context, - int requestCode, const std::shared_ptr &want, unsigned int flags, - WantAgentConstant::OperationType serviceKind) +std::shared_ptr PendingWant::BuildServicePendingWant( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, + unsigned int flags, WantAgentConstant::OperationType serviceKind) { if (context == nullptr) { WANT_AGENT_LOGE("PendingWant::BuildServicePendingWant invalid input param."); @@ -189,59 +198,54 @@ void PendingWant::Cancel(const sptr &target) void PendingWant::Send(const sptr &target) { - Send(nullptr, 0, nullptr, nullptr, "", nullptr, target); + Send(0, nullptr, nullptr, "", nullptr, target); } void PendingWant::Send(int resultCode, const sptr &target) { - Send(nullptr, resultCode, nullptr, nullptr, "", nullptr, target); + Send(resultCode, nullptr, nullptr, "", nullptr, target); } -void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, +void PendingWant::Send(int resultCode, const std::shared_ptr &want, const sptr &target) { - Send(context, resultCode, want, nullptr, "", nullptr, target); + Send(resultCode, want, nullptr, "", nullptr, target); } void PendingWant::Send( int resultCode, const sptr &onCompleted, const sptr &target) { - Send(nullptr, resultCode, nullptr, onCompleted, "", nullptr, target); + Send(resultCode, nullptr, onCompleted, "", nullptr, target); } -void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, +void PendingWant::Send(int resultCode, const std::shared_ptr &want, const sptr &onCompleted, const sptr &target) { - Send(context, resultCode, want, onCompleted, "", nullptr, target); + Send(resultCode, want, onCompleted, "", nullptr, target); } -void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, +void PendingWant::Send(int resultCode, const std::shared_ptr &want, const sptr &onCompleted, const std::string &requiredPermission, const sptr &target) { - Send(context, resultCode, want, onCompleted, requiredPermission, nullptr, target); + Send(resultCode, want, onCompleted, requiredPermission, nullptr, target); } -void PendingWant::Send(const std::shared_ptr &context, int resultCode, const std::shared_ptr &want, +void PendingWant::Send(int resultCode, const std::shared_ptr &want, const sptr &onCompleted, const std::string &requiredPermission, const std::shared_ptr &options, const sptr &target) { HILOG_INFO("%{public}s:begin.", __func__); - if (SendAndReturnResult(context, resultCode, want, onCompleted, requiredPermission, options, target) != 0) { + if (SendAndReturnResult(resultCode, want, onCompleted, requiredPermission, options, target) != 0) { WANT_AGENT_LOGE("PendingWant::SendAndReturnResult failed."); } } -int PendingWant::SendAndReturnResult(const std::shared_ptr &context, int resultCode, - const std::shared_ptr &want, const sptr &onCompleted, - const std::string &requiredPermission, const std::shared_ptr &options, - const sptr &target) +int PendingWant::SendAndReturnResult(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target) { HILOG_INFO("%{public}s:begin.", __func__); - if (context == nullptr) { - WANT_AGENT_LOGE("PendingWant::SendAndReturnResult invalid input param."); - return 1; - } SenderInfo senderInfo; senderInfo.resolvedType = want != nullptr ? want->GetType() : ""; @@ -409,4 +413,10 @@ PendingWant *PendingWant::Unmarshalling(Parcel &parcel) return pendingWant; } +std::shared_ptr PendingWant::GetWantSenderInfo(const sptr &target) +{ + std::shared_ptr info = std::make_shared(); + int ret = AbilityManagerClient::GetInstance()->GetWantSenderInfo(target, info); + return ret ? nullptr : info; +} } // namespace OHOS::Notification::WantAgent diff --git a/frameworks/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index 5b3c49c1ba755a35394003c0e1e74be14e4ce8b3..58f13b14279588886a168ce0f95c26096d925734 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -14,12 +14,14 @@ */ #include "want_agent_helper.h" + #include "ability_manager_client.h" #include "hilog_wrapper.h" +#include "ohos/aafwk/content/want_params_wrapper.h" #include "pending_want.h" #include "want_agent_log_wrapper.h" -#include "want_sender_interface.h" #include "want_sender_info.h" +#include "want_sender_interface.h" using namespace OHOS::AAFwk; using namespace OHOS::AppExecFwk; @@ -62,7 +64,7 @@ unsigned int WantAgentHelper::FlagsTransformer(const std::vector WantAgentHelper::GetWantAgent( - const std::shared_ptr &context, const WantAgentInfo ¶msInfo) + const std::shared_ptr &context, const WantAgentInfo ¶msInfo) { WANT_AGENT_LOGI("WantAgentHelper::GetWantAgent begin."); if (context == nullptr) { @@ -152,6 +154,7 @@ std::shared_ptr WantAgentHelper::GetWantAgent(const WantAgentInfo &pa wantSenderInfo.allWants.push_back(wantsInfo); wantSenderInfo.bundleName = want->GetOperation().GetBundleName(); wantSenderInfo.flags = FlagsTransformer(paramsInfo.GetFlags()); + wantSenderInfo.type = (int32_t)paramsInfo.GetOperationType(); sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); if (target == nullptr) { @@ -172,11 +175,11 @@ WantAgentConstant::OperationType WantAgentHelper::GetType(const std::shared_ptr< return agent->GetPendingWant()->GetType(agent->GetPendingWant()->GetTarget()); } -void WantAgentHelper::TriggerWantAgent(const std::shared_ptr &context, const std::shared_ptr &agent, +void WantAgentHelper::TriggerWantAgent(const std::shared_ptr &agent, const std::shared_ptr &callback, const TriggerInfo ¶msInfo) { HILOG_INFO("%{public}s:begin.", __func__); - if ((context == nullptr) || (agent == nullptr)) { + if (agent == nullptr) { WANT_AGENT_LOGE("WantAgentHelper::TriggerWantAgent invalid input param."); return; } @@ -188,20 +191,19 @@ void WantAgentHelper::TriggerWantAgent(const std::shared_ptr &context, dispatcher = new (std::nothrow) CompletedDispatcher(pendingWant, callback, nullptr); } - Send(context, pendingWant, type, dispatcher, paramsInfo); + Send(pendingWant, type, dispatcher, paramsInfo); } -void WantAgentHelper::Send(const std::shared_ptr &context, const std::shared_ptr &pendingWant, +void WantAgentHelper::Send(const std::shared_ptr &pendingWant, WantAgentConstant::OperationType type, const sptr &callBack, const TriggerInfo ¶msInfo) { HILOG_INFO("%{public}s:begin.", __func__); - if ((context == nullptr) || (pendingWant == nullptr)) { + if (pendingWant == nullptr) { WANT_AGENT_LOGE("WantAgentHelper::Send invalid input param."); return; } - pendingWant->Send(context, - paramsInfo.GetResultCode(), + pendingWant->Send(paramsInfo.GetResultCode(), paramsInfo.GetWant(), callBack, paramsInfo.GetPermission(), @@ -307,13 +309,13 @@ void WantAgentHelper::RegisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent) { if (agent == nullptr) { - WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + WANT_AGENT_LOGE("WantAgentHelper::RegisterCancelListener WantAgent invalid input param."); return; } std::shared_ptr pendingWant = agent->GetPendingWant(); if (pendingWant == nullptr) { - WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + WANT_AGENT_LOGE("WantAgentHelper::RegisterCancelListener PendingWant invalid input param."); return; } @@ -324,16 +326,113 @@ void WantAgentHelper::UnregisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent) { if (agent == nullptr) { - WANT_AGENT_LOGE("WantAgentHelper::GetWant WantAgent invalid input param."); + WANT_AGENT_LOGE("WantAgentHelper::UnregisterCancelListener WantAgent invalid input param."); return; } std::shared_ptr pendingWant = agent->GetPendingWant(); if (pendingWant == nullptr) { - WANT_AGENT_LOGE("WantAgentHelper::GetWant PendingWant invalid input param."); + WANT_AGENT_LOGE("WantAgentHelper::UnregisterCancelListener PendingWant invalid input param."); return; } pendingWant->UnregisterCancelListener(cancelListener, pendingWant->GetTarget()); } + +std::string WantAgentHelper::ToString(const std::shared_ptr &agent) +{ + if (agent == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString WantAgent invalid input param."); + return ""; + } + + std::shared_ptr pendingWant = agent->GetPendingWant(); + if (pendingWant == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString PendingWant invalid input param."); + return ""; + } + + std::shared_ptr info = pendingWant->GetWantSenderInfo(pendingWant->GetTarget()); + if (info == nullptr) { + WANT_AGENT_LOGE("WantAgentHelper::ToString WantSenderInfo invalid input param."); + return ""; + } + nlohmann::json jsonObject; + jsonObject["requestCode"] = (*info.get()).requestCode; + jsonObject["operationType"] = (*info.get()).type; + jsonObject["flags"] = (*info.get()).flags; + + nlohmann::json wants = nlohmann::json::array(); + for (auto &wantInfo : (*info.get()).allWants) { + wants.emplace_back(wantInfo.want.ToString()); + } + jsonObject["wants"] = wants; + + if ((*info.get()).allWants.size() > 0) { + nlohmann::json paramsObj; + AAFwk::WantParamWrapper wWrapper((*info.get()).allWants[0].want.GetParams()); + paramsObj["extraInfoValue"] = wWrapper.ToString(); + jsonObject["extraInfo"] = paramsObj; + } + + return jsonObject.dump(); +} + +std::shared_ptr WantAgentHelper::FromString(const std::string &jsonString) +{ + if (jsonString.empty()) { + return nullptr; + } + nlohmann::json jsonObject = nlohmann::json::parse(jsonString); + + int requestCode = -1; + if (jsonObject.contains("requestCode")) { + requestCode = jsonObject.at("requestCode").get(); + } + + WantAgentConstant::OperationType operationType = WantAgentConstant::OperationType::UNKNOWN_TYPE; + if (jsonObject.contains("operationType")) { + operationType = static_cast(jsonObject.at("operationType").get()); + } + + int flags = -1; + std::vector flagsVec = {}; + if (jsonObject.contains("flags")) { + flags = jsonObject.at("flags").get(); + } + if (flags | FLAG_ONE_SHOT) { + flagsVec.emplace_back(WantAgentConstant::Flags::ONE_TIME_FLAG); + } else if (flags | FLAG_NO_CREATE) { + flagsVec.emplace_back(WantAgentConstant::Flags::NO_BUILD_FLAG); + } else if (flags | FLAG_CANCEL_CURRENT) { + flagsVec.emplace_back(WantAgentConstant::Flags::CANCEL_PRESENT_FLAG); + } else if (flags | FLAG_UPDATE_CURRENT) { + flagsVec.emplace_back(WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + } else if (flags | FLAG_IMMUTABLE) { + flagsVec.emplace_back(WantAgentConstant::Flags::CONSTANT_FLAG); + } + + std::vector> wants = {}; + if (jsonObject.contains("wants")) { + for (auto &wantObj : jsonObject.at("wants")) { + auto wantString = wantObj.get(); + wants.emplace_back(std::make_shared(*Want::FromString(wantString))); + } + } + + std::shared_ptr extraInfo = nullptr; + if (jsonObject.contains("extraInfo")) { + auto extraInfoObj = jsonObject.at("extraInfo"); + if (extraInfoObj.contains("extraInfoValue")) { + auto pwWrapper = AAFwk::WantParamWrapper::Parse(extraInfoObj.at("extraInfoValue").get()); + AAFwk::WantParams params; + if (pwWrapper->GetValue(params) == ERR_OK) { + extraInfo = std::make_shared(params); + } + } + } + WantAgentInfo info(requestCode, operationType, flagsVec, wants, extraInfo); + + return GetWantAgent(info); +} } // namespace OHOS::Notification::WantAgent \ No newline at end of file diff --git a/frameworks/wantagent/src/want_agent_log_wrapper.cpp b/frameworks/wantagent/src/want_agent_log_wrapper.cpp index 059ffb295773be0173e4c969b29c5e89de94bbb5..e379cef2314edea1c742db7c67a161f5f004c686 100644 --- a/frameworks/wantagent/src/want_agent_log_wrapper.cpp +++ b/frameworks/wantagent/src/want_agent_log_wrapper.cpp @@ -14,7 +14,6 @@ */ #include "want_agent_log_wrapper.h" -#include namespace OHOS::Notification::WantAgent { // initial static member object diff --git a/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn index 45b7c58e89e625c0ec04ed2cf13bcf5c2f24a731..c2fdd1b29a5e7044a61e6c445390046dde6f8cfb 100644 --- a/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn @@ -19,13 +19,7 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("completed_dispatcher_test") { module_out_path = module_output_path - include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - ] + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] sources = [ "completed_dispatcher_test.cpp" ] @@ -37,26 +31,27 @@ ohos_unittest("completed_dispatcher_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn b/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn index 46d9f1e375e168767c51d2729ff6348a41ec3853..8c0f2efd5d6a4dc3ff6dbd2bcacdc5259955dec7 100644 --- a/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn @@ -20,12 +20,8 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("pending_want_test") { module_out_path = module_output_path include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//foundation/distributedschedule/samgr/adapter/interfaces/innerkits/include/", "//utils/system/safwk/native/include", "//utils/native/base/include", @@ -41,26 +37,28 @@ ohos_unittest("pending_want_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp index 196a3e36309e7bbf810c5638f4a12a983cc47385..4f66a28dcc39fa3bd42e63c5bab3c49a1111cfe2 100644 --- a/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp +++ b/frameworks/wantagent/test/unittest/pending_want_test/pending_want_test.cpp @@ -14,12 +14,11 @@ */ #include -#include "ability_context.h" #include "ability_manager_client.h" #include "cancel_listener.h" #include "completed_callback.h" #include "completed_dispatcher.h" -#include "context.h" +#include "context/context.h" #include "context_container.h" #include "element_name.h" #include "event_handler.h" @@ -101,6 +100,11 @@ Want PendingWantTest::MakeWant(std::string deviceId, std::string abilityName, st return want; } +std::shared_ptr GetAppContext() +{ + return OHOS::AbilityRuntime::Context::GetApplicationContext(); +} + void PendingWantTest::SetUpTestCase(void) {} @@ -166,7 +170,7 @@ HWTEST_F(PendingWantTest, PendingWant_0400, Function | MediumTest | Level1) want->SetElement(element); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbility(nullptr, requestCode, want, flags); + std::shared_ptr pendingWant = PendingWant::GetAbility(GetAppContext(), requestCode, want, flags); EXPECT_EQ(pendingWant, nullptr); } @@ -177,14 +181,13 @@ HWTEST_F(PendingWantTest, PendingWant_0400, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0500, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags); + std::shared_ptr pendingWant = PendingWant::GetAbility(GetAppContext(), requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); } @@ -195,7 +198,6 @@ HWTEST_F(PendingWantTest, PendingWant_0500, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0600, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -206,7 +208,8 @@ HWTEST_F(PendingWantTest, PendingWant_0600, Function | MediumTest | Level1) wParams->SetParam(key, Boolean::Box(value)); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbility(context, requestCode, want, flags, wParams); + std::shared_ptr pendingWant = PendingWant::GetAbility( + GetAppContext(), requestCode, want, flags, wParams); EXPECT_NE(pendingWant, nullptr); } @@ -229,7 +232,8 @@ HWTEST_F(PendingWantTest, PendingWant_0700, Function | MediumTest | Level1) wants.emplace_back(want2); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbilities(nullptr, requestCode, wants, flags); + std::shared_ptr pendingWant = PendingWant::GetAbilities( + nullptr, requestCode, wants, flags); EXPECT_EQ(pendingWant, nullptr); } @@ -240,7 +244,6 @@ HWTEST_F(PendingWantTest, PendingWant_0700, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -253,7 +256,8 @@ HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) wants.emplace_back(want2); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags); + std::shared_ptr pendingWant = PendingWant::GetAbilities( + GetAppContext(), requestCode, wants, flags); EXPECT_NE(pendingWant, nullptr); } @@ -264,7 +268,6 @@ HWTEST_F(PendingWantTest, PendingWant_0800, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_0900, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -281,7 +284,8 @@ HWTEST_F(PendingWantTest, PendingWant_0900, Function | MediumTest | Level1) wParams->SetParam(key, Boolean::Box(value)); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetAbilities(context, requestCode, wants, flags, wParams); + std::shared_ptr pendingWant = PendingWant::GetAbilities( + GetAppContext(), requestCode, wants, flags, wParams); EXPECT_NE(pendingWant, nullptr); } @@ -298,7 +302,8 @@ HWTEST_F(PendingWantTest, PendingWant_1000, Function | MediumTest | Level1) want->SetElement(element); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(nullptr, requestCode, want, flags, 0); + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + nullptr, requestCode, want, flags, 0); EXPECT_EQ(pendingWant, nullptr); } @@ -309,14 +314,14 @@ HWTEST_F(PendingWantTest, PendingWant_1000, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1100, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + GetAppContext(), requestCode, want, flags, 0); EXPECT_NE(pendingWant, nullptr); } @@ -327,12 +332,12 @@ HWTEST_F(PendingWantTest, PendingWant_1100, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1200, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser(context, requestCode, want, flags, 0); + std::shared_ptr pendingWant = PendingWant::GetCommonEventAsUser( + GetAppContext(), requestCode, want, flags, 0); EXPECT_NE(pendingWant, nullptr); } @@ -343,12 +348,12 @@ HWTEST_F(PendingWantTest, PendingWant_1200, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1300, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetService(context, requestCode, want, flags); + std::shared_ptr pendingWant = PendingWant::GetService( + GetAppContext(), requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); } @@ -376,12 +381,12 @@ HWTEST_F(PendingWantTest, PendingWant_1400, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1500, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; unsigned int flags = 1; flags |= FLAG_NO_CREATE; - std::shared_ptr pendingWant = PendingWant::GetForegroundService(context, requestCode, want, flags); + std::shared_ptr pendingWant = PendingWant::GetForegroundService( + GetAppContext(), requestCode, want, flags); EXPECT_NE(pendingWant, nullptr); } @@ -409,14 +414,13 @@ HWTEST_F(PendingWantTest, PendingWant_1600, Function | MediumTest | Level1) */ HWTEST_F(PendingWantTest, PendingWant_1700, Function | MediumTest | Level1) { - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want; unsigned int flags = 1; flags |= FLAG_NO_CREATE; WantAgentConstant::OperationType type = WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; std::shared_ptr pendingWant = - PendingWant::BuildServicePendingWant(context, requestCode, want, flags, type); + PendingWant::BuildServicePendingWant(GetAppContext(), requestCode, want, flags, type); EXPECT_NE(pendingWant, nullptr); } @@ -474,7 +478,6 @@ HWTEST_F(PendingWantTest, PendingWant_2000, Function | MediumTest | Level1) HWTEST_F(PendingWantTest, PendingWant_2100, Function | MediumTest | Level1) { PendingWant pendingWant(nullptr); - std::shared_ptr context = std::make_shared(); int requestCode = 10; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -487,7 +490,7 @@ HWTEST_F(PendingWantTest, PendingWant_2100, Function | MediumTest | Level1) flags |= FLAG_NO_CREATE; AbilityManagerClient::GetInstance()->Connect(); EXPECT_EQ(INNER_ERR, - pendingWant.SendAndReturnResult(context, requestCode, want, nullptr, "Permission", nullptr, nullptr)); + pendingWant.SendAndReturnResult(requestCode, want, nullptr, "Permission", nullptr, nullptr)); } /* @@ -509,7 +512,7 @@ HWTEST_F(PendingWantTest, PendingWant_2200, Function | MediumTest | Level1) unsigned int flags = 1; flags |= FLAG_NO_CREATE; AbilityManagerClient::GetInstance()->Connect(); - EXPECT_EQ(1, pendingWant.SendAndReturnResult(nullptr, requestCode, want, nullptr, "Permission", nullptr, nullptr)); + EXPECT_EQ(1, pendingWant.SendAndReturnResult(requestCode, want, nullptr, "Permission", nullptr, nullptr)); } /* diff --git a/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn index 13fcb04025e4b7229c66c955025807fe9e778bbb..936039c909cdf3f6d8c443da3e6ae26c37785c1c 100644 --- a/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn @@ -19,13 +19,7 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("trigger_Info_test") { module_out_path = module_output_path - include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - ] + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] sources = [ "trigger_Info_test.cpp" ] @@ -37,26 +31,27 @@ ohos_unittest("trigger_Info_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn index 02dd1270e82f3ff787cc84ed2edbef82088a6b59..e33afabc488db5ebf8dad66dd43c3e32338f7221 100644 --- a/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn @@ -20,11 +20,8 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_helper_test") { module_out_path = module_output_path include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", ] sources = [ "want_agent_helper_test.cpp" ] @@ -37,26 +34,28 @@ ohos_unittest("want_agent_helper_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp b/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp index 156b5dd3a8d3101f31464684f5cd549406ba5422..f555062ad2331e5fbdb0fca08149d222827aa6ca 100644 --- a/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp +++ b/frameworks/wantagent/test/unittest/want_agent_helper_test/want_agent_helper_test.cpp @@ -16,8 +16,8 @@ #include #include "ability_context.h" #include "completed_callback.h" -#include "context.h" #include "context_container.h" +#include "context/context.h" #include "element_name.h" #include "event_handler.h" #include "ohos/aafwk/base/base_types.h" @@ -177,7 +177,6 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_0700, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_0800, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); WantAgentInfo wantAgentInfo; auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); EXPECT_EQ(wantAgent, nullptr); @@ -192,7 +191,6 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_0800, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_0900, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); WantAgentInfo wantAgentInfo; wantAgentInfo.wants_.clear(); auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); @@ -208,7 +206,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_0900, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1000, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); WantAgentInfo wantAgentInfo; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -229,7 +227,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1000, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1100, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); WantAgentInfo wantAgentInfo; std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); @@ -251,7 +249,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1100, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1200, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -275,7 +273,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1200, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1300, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -299,7 +297,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1300, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1400, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -323,7 +321,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1400, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1500, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -347,7 +345,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1500, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1600, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -371,7 +369,7 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_1600, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_1700, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - std::shared_ptr context = std::make_shared(); + std::shared_ptr context = OHOS::AbilityRuntime::Context::GetApplicationContext(); std::shared_ptr want = std::make_shared(); ElementName element("device", "bundleName", "abilityName"); want->SetElement(element); @@ -506,9 +504,8 @@ HWTEST_F(WantAgentHelperTest, WantAgentHelper_2200, Function | MediumTest | Leve HWTEST_F(WantAgentHelperTest, WantAgentHelper_2300, Function | MediumTest | Level1) { std::shared_ptr wantAgentHelper = std::make_shared(); - sptr target(new (std::nothrow) WantSender()); - std::shared_ptr pendingWant = std::make_shared(target); - std::shared_ptr wantAgent = std::make_shared(pendingWant); + WantAgentInfo wantAgentInfo; + auto wantAgent = wantAgentHelper->GetWantAgent(nullptr, wantAgentInfo); auto type = wantAgentHelper->GetType(wantAgent); EXPECT_EQ(type, WantAgentConstant::OperationType::UNKNOWN_TYPE); } diff --git a/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn index 6175002f2ef60e5b0cbf37ec2138f2c7eea41c01..0d7bc82738ce8124e73003a4c3b027382a5a0f5b 100644 --- a/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn @@ -19,13 +19,7 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_info_test") { module_out_path = module_output_path - include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - ] + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] sources = [ "want_agent_info_test.cpp" ] @@ -37,26 +31,27 @@ ohos_unittest("want_agent_info_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp b/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp index b3b03055a5e7cc6459be00aea2b5f3e754042976..f724367661687b75396c3d8df34c1a41c9d67bcd 100644 --- a/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp +++ b/frameworks/wantagent/test/unittest/want_agent_info_test/want_agent_info_test.cpp @@ -16,7 +16,6 @@ #include #include "ability_context.h" #include "completed_callback.h" -#include "context.h" #include "context_container.h" #include "element_name.h" #include "event_handler.h" diff --git a/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn index 4a0ccaebd1d38e6dba64b7355950e0f8a248bce6..2d8437643ef9fd6378e50186ff88733df0bd4fd7 100644 --- a/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn @@ -19,13 +19,7 @@ module_output_path = "ans_standard/wantagent" ohos_unittest("want_agent_test") { module_out_path = module_output_path - include_dirs = [ - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/services/abilitymgr/include", - "//foundation/appexecfwk/adapter/interfaces/innerkits/libeventhandler/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/aafwk/standard/interfaces/innerkits/base/include", - ] + include_dirs = [ "//foundation/aafwk/standard/services/abilitymgr/include" ] sources = [ "want_agent_test.cpp" ] @@ -37,26 +31,27 @@ ohos_unittest("want_agent_test") { deps = [ "${core_path}:ans_core", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core:appexecfwk_core", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler:libeventhandler", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//third_party/googletest:gmock_main", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] external_deps = [ + "ability_runtime:ability_manager", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "samgr_standard:samgr_proxy", ] } diff --git a/frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp b/frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp index 8d7ef1d52a3e640e410154e82baa091e9e80dd9c..f8694df0ed096d59dcf23018775a4a18c7fdff0d 100644 --- a/frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp +++ b/frameworks/wantagent/test/unittest/want_agent_test/want_agent_test.cpp @@ -16,7 +16,6 @@ #include #include "ability_context.h" #include "completed_callback.h" -#include "context.h" #include "context_container.h" #include "element_name.h" #include "event_handler.h" diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn index 2c3010f9cc0e8536af768dddea767ee83903e2ee..d5d17329a3a911b355edd4323a28161df69bd8d0 100644 --- a/interfaces/BUILD.gn +++ b/interfaces/BUILD.gn @@ -14,6 +14,7 @@ group("interfaces_target") { deps = [ "kits/napi/ans:notification", + "kits/napi/ans/src/reminder:reminderagent", "kits/napi/wantagent:wantagent", ] } diff --git a/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 0e7717dda9b1ea5bee41c7a1e13de26a4569223a..93bb564c461307f199882e29daa466fbdea647a7 100644 --- a/interfaces/innerkits/ans/native/include/message_user.h +++ b/interfaces/innerkits/ans/native/include/message_user.h @@ -15,14 +15,14 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_MESSAGE_USER_H -#include +#include "notification_json_convert.h" #include "pixel_map.h" #include "parcel.h" #include "uri.h" namespace OHOS { namespace Notification { -class MessageUser final : public Parcelable { +class MessageUser final : public Parcelable, public NotificationJsonConvertionBase { public: /** * A constructor used to construct MessageUser @@ -124,6 +124,19 @@ public: */ std::string Dump() const; + /** + * Converts a MessageUser object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a MessageUser object from a Json. + * @param jsonObject Indicates the Json object. + * @return the MessageUser. + */ + static MessageUser *FromJson(const nlohmann::json &jsonObject); + /** * Marshals a MessageUser object into a Parcel. * @@ -150,12 +163,12 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::string key_{}; - std::string name_{}; - std::shared_ptr pixelMap_{nullptr}; + std::string key_ {}; + std::string name_ {}; + std::shared_ptr pixelMap_ {nullptr}; Uri uri_; - bool isMachine_{false}; - bool isUserImportant_{false}; + bool isMachine_ {false}; + bool isUserImportant_ {false}; // no object in parcel static constexpr int VALUE_NULL = -1; diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index e515d617a8815d1caa940dcbd4ddf3c7ecbd807b..a187b9534fdca6d046c4ec079a83cb49b84c097b 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -16,16 +16,12 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_H -#include -#include - #include "notification_request.h" #include "parcel.h" #include "uri.h" namespace OHOS { namespace Notification { - class Notification final : public Parcelable { public: /** @@ -35,6 +31,14 @@ public: */ Notification(const sptr &request); + /** + * A constructor used to create a Notification instance by existing NotificationRequest object. + * + * @param deviceId the device id. + * @param request the existing NotificationRequest object. + */ + Notification(const std::string &deviceId, const sptr &request); + /** * @brief A constructor used to create a Notification instance by copying parameters from an existing one. * @@ -160,6 +164,12 @@ public: */ pid_t GetPid() const; + /** + * Checks whether this notification is unremovable. + * @return true if this notification is unremovable; returns false otherwise. + */ + bool IsUnremovable() const; + /** * @brief Obtains the vibration style for this notifications. if * @@ -181,6 +191,38 @@ public: */ bool IsFloatingIcon() const; + /** + * @brief Obtains the remind type of a notification. + * @return the remind type of a notification. + */ + NotificationConstant::RemindType GetRemindType() const; + + /** + * Whether to support remove allowed. + * @return Current remove allowed status. + */ + bool IsRemoveAllowed() const; + + /** + * Gets the notification source. + * @return the notification slot type. + */ + NotificationConstant::SourceType GetSourceType() const; + + /** + * @brief Gets the device id of the notification source. + * + * @return Return the device id. + */ + std::string GetDeviceId() const; + + /** + * @brief Obtains the UserId of the notification creator. + * + * @return Return the UserId of the notification creator. + */ + int32_t GetUserId() const; + /** * @brief Dumps a string representation of the object. * @@ -216,16 +258,34 @@ private: void SetPostTime(const int64_t &time); void SetSound(const Uri &sound); void SetVibrationStyle(const std::vector &style); + void SetRemindType(const NotificationConstant::RemindType &reminType); + std::string GenerateNotificationKey( + const std::string &deviceId, int32_t uid, const std::string &label, int32_t id); + void SetRemoveAllowed(bool removeAllowed); + void SetSourceType(NotificationConstant::SourceType sourceType); bool ReadFromParcel(Parcel &parcel); - std::string GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id); + void ReadFromParcelBool(Parcel &parcel); + void ReadFromParcelString(Parcel &parcel); + void ReadFromParcelInt32(Parcel &parcel); + void ReadFromParcelInt64(Parcel &parcel); + void ReadFromParcelParcelable(Parcel &parcel); + bool MarshallingBool(Parcel &parcel) const; + bool MarshallingString(Parcel &parcel) const; + bool MarshallingInt32(Parcel &parcel) const; + bool MarshallingInt64(Parcel &parcel) const; + bool MarshallingParcelable(Parcel &parcel) const; private: bool enableSound_ {false}; bool enableLight_ {false}; bool enableViration_ {false}; + bool isRemoveAllowed_ {true}; std::string key_ {""}; + std::string deviceId_ {""}; int32_t ledLightColor_ {0}; NotificationConstant::VisiblenessType lockscreenVisibleness_ {NotificationConstant::VisiblenessType::NO_OVERRIDE}; + NotificationConstant::RemindType remindType_ {NotificationConstant::RemindType::NONE}; + NotificationConstant::SourceType sourceType_ {NotificationConstant::SourceType::TYPE_NORMAL}; sptr request_ {nullptr}; int64_t postTime_ {0}; std::shared_ptr sound_ {nullptr}; diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index 8cb3e395888b9720dc344278ecb2dce5fdcb7edb..1979223958dd132c33fd6447cc2726ccf8212c30 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -16,26 +16,23 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H -#include -#include -#include #include "notification_constant.h" +#include "notification_json_convert.h" #include "notification_user_input.h" -#include "want_agent.h" -#include "pac_map.h" -#include "pixel_map.h" #include "parcel.h" +#include "pixel_map.h" +#include "want_agent.h" namespace OHOS { namespace Notification { -class NotificationActionButton : public Parcelable { +class NotificationActionButton : public Parcelable, public NotificationJsonConvertionBase { public: /** * A static function used to create a NotificationActionButton instance with the input parameters passed. * @param icon Indicates the icon to represent this NotificationActionButton. * @param title Indicates the title of this NotificationActionButton. * @param wantAgent Indicates the wantAgent to be triggered when this NotificationActionButton is triggered. - * @param extras Indicates the PacMap object containing the additional data. + * @param extras Indicates the AAFwk::WantParams object containing the additional data. * @param semanticActionButton Indicates the semantic action to add. * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. * @param mimeTypeOnlyInputs Indicates the NotificationUserInput object to add which allows only values of @@ -48,7 +45,7 @@ public: */ static std::shared_ptr Create(const std::shared_ptr &icon, const std::string &title, const std::shared_ptr &wantAgent, - const std::shared_ptr &extras = {}, + const std::shared_ptr &extras = {}, NotificationConstant::SemanticActionButton semanticActionButton = NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON, bool autoCreatedReplies = true, @@ -89,15 +86,15 @@ public: /** * Adds additional data to this NotificationActionButton. - * @param pacMap Indicates the PacMap object containing the additional data. + * @param extras Indicates the AAFwk::WantParams object containing the additional data. */ - void AddAdditionalData(AppExecFwk::PacMap &pacMap); + void AddAdditionalData(AAFwk::WantParams &extras); /** * Obtains the additional data included in this NotificationActionButton. * @return the additional data included in this NotificationActionButton. */ - const std::shared_ptr GetAdditionalData() const; + const std::shared_ptr GetAdditionalData() const; /** * Sets a semantic action for this NotificationActionButton. @@ -176,6 +173,19 @@ public: */ std::string Dump(); + /** + * Converts a NotificationActionButton object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationActionButton object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationActionButton. + */ + static NotificationActionButton *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel @@ -199,7 +209,7 @@ private: * @param icon Indicates the icon to represent this NotificationActionButton. * @param title Indicates the title of this NotificationActionButton. * @param wantAgent Indicates the WantAgent to be triggered when this NotificationActionButton is triggered. - * @param extras Indicates the PacMap object containing the additional data. + * @param extras Indicates the AAFwk::WantParams object containing the additional data. * @param semanticActionButton Indicates the semantic action to add. * @param autoCreatedReplies Indicates whether to allow the platform to automatically generate possible replies. * @param mimeTypeOnlyInputs Indicates the NotificationUserInput object to add which allows only values of @@ -208,7 +218,7 @@ private: * @param isContextual Indicates whether this NotificationActionButton is a contextual action. */ NotificationActionButton(const std::shared_ptr &icon, const std::string &title, - const std::shared_ptr &wantAgent, const std::shared_ptr &extras, + const std::shared_ptr &wantAgent, const std::shared_ptr &extras, NotificationConstant::SemanticActionButton semanticActionButton, bool autoCreatedReplies, const std::vector> &mimeTypeOnlyInputs, const std::vector> &userInputs, bool isContextual); @@ -223,7 +233,7 @@ private: std::shared_ptr icon_ {}; std::string title_ {}; std::shared_ptr wantAgent_ {}; - std::shared_ptr extras_ {}; + std::shared_ptr extras_ {}; NotificationConstant::SemanticActionButton semanticActionButton_ { NotificationConstant::SemanticActionButton::NONE_ACTION_BUTTON }; diff --git a/interfaces/innerkits/ans/native/include/notification_basic_content.h b/interfaces/innerkits/ans/native/include/notification_basic_content.h index c1431546697e83a004948cab225b29ec5abb6d33..65ccd08bb9656714fd3206562091063c917794be 100644 --- a/interfaces/innerkits/ans/native/include/notification_basic_content.h +++ b/interfaces/innerkits/ans/native/include/notification_basic_content.h @@ -16,12 +16,12 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BASIC_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BASIC_CONTENT_H -#include +#include "notification_json_convert.h" #include "parcel.h" namespace OHOS { namespace Notification { -class NotificationBasicContent : public Parcelable { +class NotificationBasicContent : public Parcelable, public NotificationJsonConvertionBase { public: /** * Default deconstructor used to deconstruct. @@ -72,6 +72,12 @@ public: */ virtual std::string Dump(); + /** + * Converts a NotificationBasicContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + virtual bool ToJson(nlohmann::json &jsonObject) const override; + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel @@ -91,6 +97,12 @@ protected: */ virtual bool ReadFromParcel(Parcel &parcel); + /** + * Creates a NotificationBasicContent object from a Json. + * @param jsonObject Indicates the Json object. + */ + void ReadFromJson(const nlohmann::json &jsonObject); + protected: std::string text_ {}; std::string title_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_bundle_option.h b/interfaces/innerkits/ans/native/include/notification_bundle_option.h index 7c2fa9171aa53825cf990c0676bdd73ce76d83a3..992bfff9e80ca583685acd1107b21892b99cef1b 100644 --- a/interfaces/innerkits/ans/native/include/notification_bundle_option.h +++ b/interfaces/innerkits/ans/native/include/notification_bundle_option.h @@ -16,7 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_BUNDLE_OPTION_H -#include #include "parcel.h" namespace OHOS { @@ -91,8 +90,8 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::string bundleName_{}; - int32_t uid_{}; + std::string bundleName_ {}; + int32_t uid_ {}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index 554699724dc7bb0459ba48323ee611b9439f1959..b4e7bec4c5a749eae8f889a9f3a1646c8853126c 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -22,19 +22,9 @@ namespace OHOS { namespace Notification { class NotificationConstant { public: - enum DisturbMode { - ALLOW_ALARMS, // Indicates that only notifications of the NotificationRequest::CLASSIFICATION_ALARM - // category are allowed to interrupt the user in Do Not Disturb mode. - ALLOW_ALL, // Indicates that all notifications are allowed to interrupt the user in Do Not Disturb mode. - ALLOW_NONE, // Indicates that no notifications are allowed to interrupt the user in Do Not Disturb mode. - ALLOW_PRIORITY, // Indicates that only notifications meeting the specified priority criteria are allowed - // to interrupt the user in Do Not Disturb mode. - ALLOW_UNKNOWN, // Indicates the value returned if the Do Not Disturb mode type cannot be obtained. - }; - enum InputEditType { - EDIT_AUTO, // Indicates that the system determines whether to allow the user to edit the options before they - // are sent to the application. + EDIT_AUTO, // Indicates that the system determines whether to allow the user to edit the options before + // they are sent to the application. EDIT_DISABLED, // Indicates that the user is not allowed to edit an option before the option is sent to the // application. EDIT_ENABLED, // Indicates that the user is allowed to edit an option before the option is sent to the @@ -94,6 +84,42 @@ public: SECRET }; + enum class DoNotDisturbType { + NONE = 0, + ONCE = 1, // only once + DAILY = 2, // every day + CLEARLY = 3, // time period + }; + + enum class RemindType { + NONE = -1, + DEVICE_IDLE_DONOT_REMIND = 0, // The device is not in use, no reminder + DEVICE_IDLE_REMIND = 1, // The device is not in use, remind + DEVICE_ACTIVE_DONOT_REMIND = 2, // The device is in use, no reminder + DEVICE_ACTIVE_REMIND = 3, // The device is in use, reminder + }; + + enum class DistributedReminderPolicy { + DEFAULT, + ALWAYS_REMIND, + DO_NOT_REMIND, + }; + + enum class SourceType { + /** + * general notification. + */ + TYPE_NORMAL = 0x00000000, + /** + * long-term task notification. + */ + TYPE_CONTINUOUS = 0x00000001, + /** + * timed notification. + */ + TYPE_TIMER = 0x00000002 + }; + /** * Indicates that a notification is deleted because it is clicked. */ diff --git a/interfaces/innerkits/ans/native/include/notification_content.h b/interfaces/innerkits/ans/native/include/notification_content.h index ea5abb8cb46c1cc96be69c90dd52ddde594e7183..0923b9ea0401cc786f58d0faed4b2975f5019bce 100644 --- a/interfaces/innerkits/ans/native/include/notification_content.h +++ b/interfaces/innerkits/ans/native/include/notification_content.h @@ -16,20 +16,19 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONTENT_H -#include -#include #include "notification_basic_content.h" -#include "notification_normal_content.h" -#include "notification_long_text_content.h" -#include "notification_picture_content.h" #include "notification_conversational_content.h" -#include "notification_multiline_content.h" +#include "notification_json_convert.h" +#include "notification_long_text_content.h" #include "notification_media_content.h" +#include "notification_multiline_content.h" +#include "notification_normal_content.h" +#include "notification_picture_content.h" #include "parcel.h" namespace OHOS { namespace Notification { -class NotificationContent : public Parcelable { +class NotificationContent : public Parcelable, public NotificationJsonConvertionBase { public: enum class Type { /** @@ -147,6 +146,19 @@ public: */ std::string Dump(); + /** + * Converts a NotificationContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationContent. + */ + static NotificationContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel @@ -172,6 +184,8 @@ private: */ bool ReadFromParcel(Parcel &parcel); + static bool ConvertJsonToContent(NotificationContent *target, const nlohmann::json &jsonObject); + private: NotificationContent::Type contentType_ {NotificationContent::Type::NONE}; std::shared_ptr content_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h index 5b91d30e264ee6ad7793eb963362bf62a4d7f76c..999497416e064b5b24bb771f006b7936eb2c036b 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -16,12 +16,10 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_CONTENT_H -#include -#include -#include #include "message_user.h" #include "notification_basic_content.h" #include "notification_conversational_message.h" +#include "notification_json_convert.h" #include "parcel.h" namespace OHOS { @@ -52,7 +50,7 @@ public: /** * Sets the title to be displayed for the conversation. - * The title set in this method will overwrite the one set by calling setTitle(std::tring). + * The title set in this method will overwrite the one set by calling setTitle(std::string). * @param conversationTitle Indicates the title to be displayed for the conversation. */ void SetConversationTitle(const std::string &conversationTitle); @@ -107,6 +105,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationConversationalContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + virtual bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationConversationalContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationConversationalContent. + */ + static NotificationConversationalContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_message.h b/interfaces/innerkits/ans/native/include/notification_conversational_message.h index 06eb0b35099019017ec21cc517f66279f31be73a..b32fe9f654eccd4066ed3ec74290e8d1e446476e 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_message.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_message.h @@ -16,15 +16,14 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H -#include -#include #include "message_user.h" +#include "notification_json_convert.h" #include "parcel.h" #include "uri.h" namespace OHOS { namespace Notification { -class NotificationConversationalMessage : public Parcelable { +class NotificationConversationalMessage : public Parcelable, public NotificationJsonConvertionBase { public: /** * A constructor used to create a NotificationConversationalMessage instance with the input parameters passed. @@ -83,6 +82,19 @@ public: */ std::string Dump(); + /** + * Converts a NotificationConversationalMessage object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationConversationalMessage object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationConversationalMessage. + */ + static NotificationConversationalMessage *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_distributed_options.h b/interfaces/innerkits/ans/native/include/notification_distributed_options.h new file mode 100644 index 0000000000000000000000000000000000000000..56d9e65029dc002407362e75c07e88cdc12d21f3 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_distributed_options.h @@ -0,0 +1,127 @@ +/* + * 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_ANS_STANDARD_NATIVE_INCLUDE_NOTIFICATION_DISTRIBUTED_OPTIONS_H +#define BASE_NOTIFICATION_ANS_STANDARD_NATIVE_INCLUDE_NOTIFICATION_DISTRIBUTED_OPTIONS_H + +#include "notification_json_convert.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationDistributedOptions : public Parcelable, public NotificationJsonConvertionBase { +public: + /** + * Default constructor used to create a NotificationDistributedOptions instance. + */ + NotificationDistributedOptions() = default; + + /** + * Constructor used to create a NotificationDistributedOptions instance. + * @param distribute Specifies whether a notification is distributed. + * @param dvsDisplay The devices that support display. + * @param dvsOperate The devices that support operate. + */ + NotificationDistributedOptions( + bool distribute, const std::vector &dvsDisplay, const std::vector &dvsOperate); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationDistributedOptions() = default; + + /** + * Sets whether a notification is distributed. + * @param distribute Specifies whether a notification is distributed. + */ + void SetDistributed(bool distribute); + + /** + * Checks whether a notification is distributed. + * @return true if the notification is distributed; returns false otherwise. + */ + bool IsDistributed() const; + + /** + * Sets devices that support display. + * @param devices The devices that support display. + */ + void SetDevicesSupportDisplay(const std::vector &devices); + + /** + * Obtains the devices that support display. + * @return the devices that support display. + */ + std::vector GetDevicesSupportDisplay() const; + + /** + * Sets devices that support operate. + * @param devices The devices that support operate. + */ + void SetDevicesSupportOperate(const std::vector &devices); + + /** + * Obtains the devices that support operate. + * @return the devices that support operate. + */ + std::vector GetDevicesSupportOperate() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Converts a NotificationDistributedOptions object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationDistributedOptions object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationDistributedOptions. + */ + static NotificationDistributedOptions *FromJson(const nlohmann::json &jsonObject); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationDistributedOptions + */ + static NotificationDistributedOptions *Unmarshalling(Parcel &parcel); + +private: + /** + * Read a NotificationDistributedOptions object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + bool isDistributed_ {true}; + std::vector devicesSupportDisplay_ {}; + std::vector devicesSupportOperate_ {}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_NATIVE_INCLUDE_NOTIFICATION_DISTRIBUTED_OPTIONS_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/notification_do_not_disturb_date.h b/interfaces/innerkits/ans/native/include/notification_do_not_disturb_date.h new file mode 100644 index 0000000000000000000000000000000000000000..0f08ea71d7cd8b4d992a9a77376968bcaf1b0c10 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_do_not_disturb_date.h @@ -0,0 +1,116 @@ +/* + * 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_NATIVE_INCLUDE_NOTIFICATION_DO_NOT_DISTURB_DATE_H +#define BASE_NOTIFICATION_ANS_STANDARD_NATIVE_INCLUDE_NOTIFICATION_DO_NOT_DISTURB_DATE_H + +#include "notification_constant.h" +#include "parcel.h" + +namespace OHOS { +namespace Notification { +class NotificationDoNotDisturbDate : public Parcelable { +public: + /** + * Default constructor used to create a NotificationDoNotDisturbDate instance. + */ + NotificationDoNotDisturbDate() = default; + + /** + * A constructor used to create a NotificationDoNotDisturbDate instance with the input parameters passed. + * @param doNotDisturbType Indicates the do not disturb type to add. + * @param beginDate Indicates the begin time to add. + * @param endDate Indicates the begin time to add. + */ + NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType doNotDisturbType, + int64_t beginDate, int64_t endDate); + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationDoNotDisturbDate() = default; + + /** + * Sets do not disturb type for this NotificationDoNotDisturbDate. + * @param doNotDisturbType Indicates the do not disturb type to add. + * For available values, see NotificationConstant::DoNotDisturbType. + */ + void SetDoNotDisturbType(NotificationConstant::DoNotDisturbType doNotDisturbType); + + /** + * Obtains the do not disturb type of this NotificationDoNotDisturbDate. + * @return the do not disturb type of this NotificationDoNotDisturbDate, + * as enumerated in NotificationConstant::DoNotDisturbType. + */ + NotificationConstant::DoNotDisturbType GetDoNotDisturbType() const; + + /** + * Sets begin time for this NotificationDoNotDisturbDate. + * @param beginDate Indicates the begin time to add. + */ + void SetBeginDate(const int64_t beginDate); + + /** + * Obtains the begin time of this NotificationDoNotDisturbDate. + * @return the begin time of this NotificationDoNotDisturbDate. + */ + int64_t GetBeginDate() const; + + /** + * Sets end time for this NotificationDoNotDisturbDate. + * @param endDate Indicates the end time to add. + */ + void SetEndDate(const int64_t endDate); + + /** + * Obtains the end time of this NotificationDoNotDisturbDate. + * @return the end time of this NotificationDoNotDisturbDate. + */ + int64_t GetEndDate() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationDoNotDisturbDate + */ + static NotificationDoNotDisturbDate *Unmarshalling(Parcel &parcel); + +private: + /** + * Read a NotificationDoNotDisturbDate object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + NotificationConstant::DoNotDisturbType doNotDisturbType_ {NotificationConstant::DoNotDisturbType::NONE}; + int64_t beginDate_ {0}; + int64_t endDate_ {0}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_NATIVE_INCLUDE_NOTIFICATION_DO_NOT_DISTURB_DATE_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/notification_flags.h b/interfaces/innerkits/ans/native/include/notification_flags.h new file mode 100644 index 0000000000000000000000000000000000000000..09664ed4d1575837df2a3b965cab60b567e080ce --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_flags.h @@ -0,0 +1,107 @@ +/* + * 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_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_FLAGS_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_FLAGS_H + +#include +#include "parcel.h" +#include "notification_json_convert.h" + +namespace OHOS { +namespace Notification { +class NotificationFlags : public Parcelable, public NotificationJsonConvertionBase { +public: + /** + * Default constructor used to create an empty NotificationFlags instance. + */ + NotificationFlags() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationFlags() = default; + + /** + * Sets the notification whether enable sound. + * @param soundEnabled whether enable sound. + */ + void SetSoundEnabled(bool soundEnabled); + + /** + * Checks whether enable sound. + * @return sound enable. + */ + bool IsSoundEnabled() const; + + /** + * Sets the notification whether enable vibration. + * @param vibrationEnabled whether enable vibration. + */ + void SetVibrationEnabled(bool vibrationEnabled); + + /** + * Checks whether enable vibration. + * @return vibration enable. + */ + bool IsVibrationEnabled() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Converts a NotificationFlags object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationFlags object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationFlags. + */ + static NotificationFlags *FromJson(const nlohmann::json &jsonObject); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationFlags + */ + static NotificationFlags *Unmarshalling(Parcel &parcel); + +private: + /** + * Read a NotificationFlags object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + bool soundEnabled_ {true}; + bool vibrationEnabled_ {false}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_FLAGS_H + diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index b6b5fbf65936495fce013a40afe962384a32b5bf..665303846d6eb5e4a736ad246ef776d3b12c1eb1 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -17,6 +17,7 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_HELPER_H #include "notification_bundle_option.h" +#include "notification_do_not_disturb_date.h" #include "notification_request.h" #include "notification_slot.h" #include "notification_slot_group.h" @@ -96,7 +97,7 @@ public: * calling NotificationSlot::SetSlotGroup(string). * @note A NotificationSlotGroup instance cannot be used directly after being initialized. * Instead, you have to call this method to create a notification slot group so that you can bind - * NotificationSlot objects to it. + * NotificationSlot objects to it. * * @param slotGroup Indicates the notification slot group to be created, which is set by NotificationSlotGroup. * This parameter must be specified. the notification slot to be created, which is set by @@ -334,9 +335,9 @@ public: * @note To subscribe to a notification, inherit the {NotificationSubscriber} class, override its * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. * After the notification is published, subscribers that meet the filter criteria can receive the - * notification. To subscribe to notifications published only by specified sources, for example, notifications from - * certain applications, call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} - * method. + * notification. To subscribe to notifications published only by specified sources, for example, + * notifications from certain applications, + * call the {SubscribeNotification(NotificationSubscriber, NotificationSubscribeInfo)} method. * * @param subscriber Indicates the {NotificationSubscriber} to receive notifications. * This parameter must be specified. @@ -352,8 +353,8 @@ public: * To subscribe to a notification, inherit the {NotificationSubscriber} class, override its * callback methods and create a subscriber. The subscriber will be used as a parameter of this method. * After the notification is published, subscribers that meet the filter criteria can receive the - * notification. To subscribe to and receive all notifications, call the - * {SubscribeNotification(NotificationSubscriber)} method. + * notification. To subscribe to and receive all notifications, call the + * {SubscribeNotification(NotificationSubscriber)} method. * * @param subscriber Indicates the subscribers to receive notifications. This parameter must be specified. * For details, see {NotificationSubscriber}. @@ -509,8 +510,8 @@ public: * @param deviceId Indicates the ID of the device running the application. At present, this parameter can only * be null or an empty string, indicating the current device. * @param enabled Specifies whether to allow all applications to publish notifications. The value true - * indicates that notifications are allowed, and the value false indicates that notifications are not - * allowed. + * indicates that notifications are allowed, and the value false indicates that notifications + * are not allowed. * @return Returns set notifications enabled for all bundles result. */ static ErrCode SetNotificationsEnabledForAllBundles(const std::string &deviceId, bool enabled); @@ -523,7 +524,7 @@ public: * only be null or an empty string, indicating the current device. * @param enabled Specifies whether to allow the current application to publish notifications. The value * true indicates that notifications are allowed, and the value false indicates that - * notifications are not allowed.\ + * notifications are not allowed. * @return Returns set notifications enabled for default bundle result. */ static ErrCode SetNotificationsEnabledForDefaultBundle(const std::string &deviceId, bool enabled); @@ -570,25 +571,132 @@ public: static ErrCode GetShowBadgeEnabled(bool &enabled); /** - * Sets the type of the Do Not Disturb mode. The Do Not Disturb mode type specifies the type of notifications - * that are allowed to interrupt users. + * Cancel the notification of the specified group of this application. + * + * @param groupName the specified group name. + * @return Returns cancel group result. + */ + static ErrCode CancelGroup(const std::string &groupName); + + /** + * Remove the notification of the specified group of the specified application. + * + * @param bundleOption Indicates the bundle name and uid of the specified application. + * @param groupName the specified group name. + * @return Returns remove group by bundle result. + */ + static ErrCode RemoveGroupByBundle(const NotificationBundleOption &bundleOption, const std::string &groupName); + + /** + * Sets the do not disturb time. * @note Your application must have system signature to call this method. * - * @param mode Indicates the Do Not Disturb mode to set. The value must be - * {NotificationConstant.DisturbMode.ALLOW_ALL}, {NotificationConstant.DisturbMode.ALLOW_PRIORITY}, - * {NotificationConstant.DisturbMode.ALLOW_NONE}, or {NotificationConstant.DisturbMode.ALLOW_ALARMS}. - * @return Returns set disturb mode result. + * @param doNotDisturbDate Indicates the do not disturb time to set. + * @return Returns set do not disturb time result. */ - static ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); + static ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate); /** - * Obtains the Disturb Mode. - * @param disturbMode The current type of the Do Not Disturb mode. - * @return Returns get disturb mode result. + * Obtains the do not disturb time. + * @note Your application must have system signature to call this method. + * + * @param doNotDisturbDate Indicates the do not disturb time to get. + * @return Returns set do not disturb time result. */ - static ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); -}; + static ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); + + /** + * Obtains the flag that whether to support do not disturb mode. + * + * @param doesSupport Specifies whether to support do not disturb mode. + * @return Returns check result. + */ + static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + + /** + * Check if the device supports distributed notification. + * + * @param enabled True if the device supports distributed notification; false otherwise. + * @return Returns is distributed enabled result. + */ + static ErrCode IsDistributedEnabled(bool &enabled); + + /** + * Set whether the device supports distributed notifications. + * + * @param enable Specifies whether to enable the device to support distributed notification. + * The value true indicates that the device is enabled to support distributed notifications, and + * the value false indicates that the device is forbidden to support distributed notifications. + * @return Returns enable distributed result. + */ + static ErrCode EnableDistributed(const bool enabled); + + /** + * Set whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled Specifies whether to enable an application to support distributed notification. + * The value true indicates that the application is enabled to support distributed notifications, + * and the value false indicates that the application is forbidden to support distributed + * notifications. + * @return Returns enable distributed by bundle result. + */ + static ErrCode EnableDistributedByBundle(const NotificationBundleOption &bundleOption, const bool enabled); + + /** + * Set whether this application supports distributed notifications. + * + * @param enabled Specifies whether to enable this application to support distributed notification. + * The value true indicates that this application is enabled to support distributed notifications, + * and the value false indicates that this application is forbidden to support distributed + * notifications. + * @return Returns enable distributed self result. + */ + static ErrCode EnableDistributedSelf(const bool enabled); + + /** + * Check whether an application supports distributed notifications. + * + * @param bundleOption Indicates the bundle name and uid of an application. + * @param enabled True if the application supports distributed notification; false otherwise. + * @return Returns is distributed enabled by bundle result. + */ + static ErrCode IsDistributedEnableByBundle(const NotificationBundleOption &bundleOption, bool &enabled); + + /** + * Obtains the device remind type. + * @note Your application must have system signature to call this method. + * + * @param remindType Indicates the device remind type to get. + * @return Returns get device reminder type result. + */ + static ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType); + /** + * Publishes a continuous task notification. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish continuous task notification result. + */ + static ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); + + /** + * Cancels a published continuous task notification matching the specified label and notificationId. + * + * @param label Indicates the label of the continuous task notification to cancel. + * @param notificationId Indicates the ID of the continuous task notification to cancel. + * @return Returns cancel continuous task notification result. + */ + static ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId); + + /** + * Obtains whether the template is supported by the system. + * + * @param support whether is it a system supported template. + * @return Returns check result. + */ + static ErrCode IsSupportTemplate(const std::string &templateName, bool &support); +}; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_json_convert.h b/interfaces/innerkits/ans/native/include/notification_json_convert.h new file mode 100644 index 0000000000000000000000000000000000000000..2a6fb1683bcc312619b78acd7ee8851049432dd2 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_json_convert.h @@ -0,0 +1,97 @@ +/* + * 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_ANS_STANDARD_NOTIFICATION_JSON_CONVERT_H +#define BASE_NOTIFICATION_ANS_STANDARD_NOTIFICATION_JSON_CONVERT_H + +#include +#include "ans_log_wrapper.h" +#include "nlohmann/json.hpp" + +namespace OHOS { +namespace Notification { +class NotificationJsonConvertionBase { +public: + /** + * Default deconstructor used to deconstruct. + */ + virtual ~NotificationJsonConvertionBase() = default; + + virtual bool ToJson(nlohmann::json &jsonObject) const = 0; +}; + +class NotificationJsonConverter { +public: + /** + * Convert NotificationJsonConvertionBase object to json object. + */ + static bool ConvertToJosn(const NotificationJsonConvertionBase *convertionBase, nlohmann::json &jsonObject) + { + if (convertionBase == nullptr) { + ANS_LOGE("Converter : Invalid base object"); + return false; + } + + return convertionBase->ToJson(jsonObject); + } + + static bool ConvertToJosnString(const NotificationJsonConvertionBase *convertionBase, std::string &jsonString) + { + if (convertionBase == nullptr) { + ANS_LOGE("Converter : Invalid base object"); + return false; + } + + nlohmann::json jsonObject; + if (!convertionBase->ToJson(jsonObject)) { + ANS_LOGE("Converter : Cannot convert to JSON object"); + return false; + } + jsonString = jsonObject.dump(); + + return true; + } + + template + static T *ConvertFromJosn(const nlohmann::json &jsonObject) + { + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Converter : Invalid JSON object"); + return nullptr; + } + + return T::FromJson(jsonObject); + } + + template + static T *ConvertFromJosnString(const std::string &jsonString) + { + if (jsonString.empty()) { + ANS_LOGE("Converter : Invalid JSON string"); + return nullptr; + } + + auto jsonObject = nlohmann::json::parse(jsonString); + if (jsonObject.is_null() or !jsonObject.is_object()) { + ANS_LOGE("Converter : Invalid JSON object"); + return nullptr; + } + + return T::FromJson(jsonObject); + } +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_NOTIFICATION_JSON_CONVERT_H diff --git a/interfaces/innerkits/ans/native/include/notification_long_text_content.h b/interfaces/innerkits/ans/native/include/notification_long_text_content.h index b64685f5d696c5718b4f4a1d2cb8d1ab29ba07df..85d50017f84f8e10d128657851d052742b5bbabd 100644 --- a/interfaces/innerkits/ans/native/include/notification_long_text_content.h +++ b/interfaces/innerkits/ans/native/include/notification_long_text_content.h @@ -16,8 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_LONG_TEXT_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_LONG_TEXT_CONTENT_H -#include -#include #include "notification_basic_content.h" #include "parcel.h" @@ -88,6 +86,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationLongTextContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationLongTextContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationLongTextContent. + */ + static NotificationLongTextContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_media_content.h b/interfaces/innerkits/ans/native/include/notification_media_content.h index c725db2ae3a58fb83a66b68f7e3870db281aa686..5044fa89b3206b7065a85fb4e9d0d288523773fd 100644 --- a/interfaces/innerkits/ans/native/include/notification_media_content.h +++ b/interfaces/innerkits/ans/native/include/notification_media_content.h @@ -16,9 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MEDIA_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MEDIA_CONTENT_H -#include -#include -#include #include "notification_basic_content.h" #include "parcel.h" @@ -79,6 +76,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationMediaContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + virtual bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationMediaContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationMediaContent. + */ + static NotificationMediaContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_multiline_content.h b/interfaces/innerkits/ans/native/include/notification_multiline_content.h index 485f6c1fa0495f9809af61cfdac29cde6494a20f..7f0e91655289d225592102ec49b8f7aab7f5eeef 100644 --- a/interfaces/innerkits/ans/native/include/notification_multiline_content.h +++ b/interfaces/innerkits/ans/native/include/notification_multiline_content.h @@ -16,8 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MULTILINE_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_MULTILINE_CONTENT_H -#include -#include #include "notification_basic_content.h" #include "parcel.h" @@ -85,6 +83,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationMultiLineContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + virtual bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationMultiLineContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationMultiLineContent. + */ + static NotificationMultiLineContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_normal_content.h b/interfaces/innerkits/ans/native/include/notification_normal_content.h index 4bb177e95d9572f952e325f890edcd28dc2d043a..6bd04ae5760fe620eef0b390e610229eb6da2403 100644 --- a/interfaces/innerkits/ans/native/include/notification_normal_content.h +++ b/interfaces/innerkits/ans/native/include/notification_normal_content.h @@ -16,7 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_NORMAL_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_NORMAL_CONTENT_H -#include #include "notification_basic_content.h" #include "parcel.h" @@ -40,6 +39,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationNormalContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationNormalContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationNormalContent. + */ + static NotificationNormalContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h index 91a3dd8062ddbc1416321d7185543ce9832f0502..8ed0dc54b0824b45ae92a1c2dbbd0453f8c51366 100644 --- a/interfaces/innerkits/ans/native/include/notification_picture_content.h +++ b/interfaces/innerkits/ans/native/include/notification_picture_content.h @@ -16,11 +16,9 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_PICTURE_CONTENT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_PICTURE_CONTENT_H -#include -#include #include "notification_basic_content.h" -#include "pixel_map.h" #include "parcel.h" +#include "pixel_map.h" namespace OHOS { namespace Notification { @@ -84,6 +82,19 @@ public: */ std::string Dump() override; + /** + * Converts a NotificationPictureContent object into a Json. + * @param jsonObject Indicates the Json object. + */ + virtual bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationPictureContent object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationPictureContent. + */ + static NotificationPictureContent *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 1536f675bc07ebc95ed98951705f4a5def950195..e2f6190f8ec06c8b690ba0f72a2355336bd9ce9c 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -16,21 +16,21 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_REQUEST_H -#include -#include -#include #include "message_user.h" #include "notification_action_button.h" #include "notification_content.h" -#include "want_agent.h" -#include "context.h" +#include "notification_distributed_options.h" +#include "notification_flags.h" +#include "notification_json_convert.h" +#include "notification_template.h" #include "ohos/aafwk/content/want_params.h" -#include "pixel_map.h" #include "parcel.h" +#include "pixel_map.h" +#include "want_agent.h" namespace OHOS { namespace Notification { -class NotificationRequest : public Parcelable { +class NotificationRequest : public Parcelable, public NotificationJsonConvertionBase { public: enum class BadgeStyle { /** @@ -137,22 +137,6 @@ public: */ static const uint32_t COLOR_DEFAULT; -private: - /** - * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). - */ - static const uint32_t COLOR_MASK; - - /** - * the maximum number of user input history is 5. - */ - static const std::size_t MAX_USER_INPUT_HISTORY; - - /** - * the maximum number of action buttons is 3. - */ - static const std::size_t MAX_ACTION_BUTTONS; - public: /** * Default constructor used to create a NotificationRequest instance. @@ -165,14 +149,6 @@ public: */ explicit NotificationRequest(int32_t notificationId); - /** - * A constructor used to create a NotificationRequest instance based on the specified context and notification ID. - * To publish a notification with a custom view, you must call such a constructor with the Context specified. - * @param context the specified context - * @param notificationId notification ID - */ - NotificationRequest(const std::shared_ptr &context, int32_t notificationId); - /** * A constructor used to create a NotificationRequest instance by copying parameters from an existing one. * @param other the existing object @@ -325,7 +301,7 @@ public: /** * Adds a NotificationActionButton to this notification. - * An operation button is usually placed next to the notification content by the system. + * An operation button is usually placed next to the notification content by the system. * Each action button must contain an icon, a title, and an WantAgent. When a notification is expanded, * a maximum of three action buttons can be displayed from left to right in the order they were added. * When the notification is collapsed, no action buttons will be displayed. @@ -339,6 +315,11 @@ public: */ const std::vector> GetActionButtons() const; + /** + * Clear the list of all NotificationActionButton objects included in this notification. + */ + void ClearActionButtons(); + /** * Checks whether the platform is allowed to generate contextual NotificationActionButton objects for this * notification. @@ -454,7 +435,7 @@ public: * Checks whether background color is enabled for this notification. * @return true if background color is enabled; returns false otherwise. */ - bool IsColorEnabled(); + bool IsColorEnabled() const; /** * Sets whether to enable background color for this notification. @@ -530,8 +511,8 @@ public: /** * Sets whether to use this notification as the overview of its group. - * This method helps display the notifications that are assigned the same group value by calling - * setGroupValue(string) as one stack in the notification bar. + * This method helps display the notifications that are assigned the same group name by calling + * setGroupName(string) as one stack in the notification bar. * Each group requires only one group overview. After a notification is set as the group overview, * it becomes invisible if another notification in the same group is published. * @param overView Specifies whether to set this notification as the group overview. @@ -542,21 +523,21 @@ public: * Sets the group information for this notification. * If no groups are set for notifications, all notifications from the same application will appear * in the notification bar as one stack with the number of stacked notifications displayed. - * If notifications are grouped and there are multiple groups identified by different groupValue, - * notifications with different groupValue will appear in separate stacks. + * If notifications are grouped and there are multiple groups identified by different groupName, + * notifications with different groupName will appear in separate stacks. * Note that one of the notifications in a group must be set as the overview of its group by calling * setGroupOverview(bool), and other notifications are considered as child notifications. - * Otherwise, notifications will not be displayed as one group even if they are assigned the same groupValue by - * calling setGroupValue(string). - * @param groupValue Specifies whether to set this notification as the group overview. + * Otherwise, notifications will not be displayed as one group even if they are assigned the same groupName by + * calling setGroupName(string). + * @param groupName Specifies whether to set this notification as the group overview. */ - void SetGroupValue(const std::string &groupValue); + void SetGroupName(const std::string &groupName); /** * Obtains the group information about this notification. * @return the group information about this notification. */ - std::string GetGroupValue() const; + std::string GetGroupName() const; /** * Checks whether this notification is relevant only to the local device and cannot be displayed on remote devices. @@ -856,12 +837,61 @@ public: */ std::string GetLabel() const; + /** + * Sets whether this notification is distributed. + * @param distribute Specifies whether a notification is displayed as a floating icon on top of the screen. + */ + void SetDistributed(bool distribute); + + /** + * Sets devices that support display. + * @param devices The devices that support display. + */ + void SetDevicesSupportDisplay(const std::vector &devices); + + /** + * Sets devices that support operate. + * @param devices The devices that support operate. + */ + void SetDevicesSupportOperate(const std::vector &devices); + + /** + * Obtains the distributed Options. + * @return the distributed Options. + */ + NotificationDistributedOptions GetNotificationDistributedOptions() const; + + /** + * Sets the UserId of the notification creator. + * @param userId the UserId of the notification creator. + */ + void SetCreatorUserId(int32_t userId); + + /** + * Obtains the UserId of the notification creator. + * @return the UserId of the notification creator. + */ + int32_t GetCreatorUserId() const; + /** * Returns a string representation of the object. * @return a string representation of the object. */ std::string Dump(); + /** + * Converts a NotificationRequest object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationRequest object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationRequest. + */ + static NotificationRequest *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a NotificationRequest object into a Parcel. * @param parcel the object into the parcel @@ -870,10 +900,50 @@ public: /** * Unmarshal object from a Parcel. - * @return the NotificationRequest + * @return the NotificationRequest. */ static NotificationRequest *Unmarshalling(Parcel &parcel); + /** + * Sets the template of this notification. + * @param template the template of this notification. + */ + void SetTemplate(const std::shared_ptr &templ); + + /** + * Obtains the Template of the notification. + * @return the Template of the notification. + */ + std::shared_ptr GetTemplate() const; + + /** + * Sets the flags of this notification. + * @param flags the flags of this notification. + */ + void SetFlags(const std::shared_ptr &flags); + + /** + * Obtains the flags of the notification. + * @return the flags of the notification. + */ + std::shared_ptr GetFlags() const; + +private: + /** + * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). + */ + static const uint32_t COLOR_MASK; + + /** + * the maximum number of user input history is 5. + */ + static const std::size_t MAX_USER_INPUT_HISTORY; + + /** + * the maximum number of action buttons is 3. + */ + static const std::size_t MAX_ACTION_BUTTONS; + private: /** * Read a NotificationRequest object from a Parcel. @@ -887,6 +957,22 @@ private: */ int64_t GetNowSysTime(); + void CopyBase(const NotificationRequest &other); + void CopyOther(const NotificationRequest &other); + + bool ConvertObjectsToJson(nlohmann::json &jsonObject) const; + + static void ConvertJsonToNum(NotificationRequest *target, const nlohmann::json &jsonObject); + static void ConvertJsonToString(NotificationRequest *target, const nlohmann::json &jsonObject); + static void ConvertJsonToEnum(NotificationRequest *target, const nlohmann::json &jsonObject); + static void ConvertJsonToBool(NotificationRequest *target, const nlohmann::json &jsonObject); + static void ConvertJsonToPixelMap(NotificationRequest *target, const nlohmann::json &jsonObject); + static bool ConvertJsonToNotificationContent(NotificationRequest *target, const nlohmann::json &jsonObject); + static bool ConvertJsonToNotificationActionButton(NotificationRequest *target, const nlohmann::json &jsonObject); + static bool ConvertJsonToNotificationDistributedOptions( + NotificationRequest *target, const nlohmann::json &jsonObject); + static bool ConvertJsonToNotificationFlags(NotificationRequest *target, const nlohmann::json &jsonObject); + private: int32_t notificationId_ {0}; uint32_t color_ {NotificationRequest::COLOR_DEFAULT}; @@ -899,11 +985,12 @@ private: pid_t creatorPid_ {0}; pid_t creatorUid_ {0}; + int32_t creatorUserId_ {-1}; std::string settingsText_ {}; std::string creatorBundleName_ {}; std::string ownerBundleName_ {}; - std::string groupValue_ {}; + std::string groupName_ {}; std::string statusBarText_ {}; std::string label_ {}; std::string shortcutId_ {}; @@ -930,7 +1017,6 @@ private: bool onlyLocal_ {false}; bool permitted_ {true}; - std::shared_ptr context_ {}; std::shared_ptr wantAgent_ {}; std::shared_ptr removalWantAgent_ {}; std::shared_ptr maxScreenWantAgent_ {}; @@ -943,6 +1029,11 @@ private: std::vector> actionButtons_ {}; std::vector> messageUsers_ {}; std::vector userInputHistory_ {}; + + NotificationDistributedOptions distributedOptions_; + + std::shared_ptr notificationTemplate_ {}; + std::shared_ptr notificationFlags_ {}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h index f9594c65ed63fcb13ac8283ed93f92e63d6abebd..6b53430328c795c1de165aef9314f7013b12bc71 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -16,8 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_H -#include - #include "notification_content.h" #include "notification_request.h" #include "parcel.h" @@ -240,8 +238,8 @@ public: * @note If an empty array or null is passed to this method, the system then calls * SetEnableVibration(bool) with the input parameter set to false. * If a valid value is passed to this method, the system calls SetEnableVibration(bool) with the input - * parameter set to true. This method takes effect only before - * NotificationHelper::AddNotificationSlot(NotificationSlot) is called. + * parameter set to true. This method takes effect only before + * NotificationHelper::AddNotificationSlot(NotificationSlot) is called. * * @param vibration Indicates the vibration style to set. */ diff --git a/interfaces/innerkits/ans/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h index f979cdd93a758859bbc14e71f56aa4cf04eced8d..7becacaaef4e782e29809db053c3e68c82b5460e 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot_group.h +++ b/interfaces/innerkits/ans/native/include/notification_slot_group.h @@ -16,8 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_GROUP_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SLOT_GROUP_H -#include - #include "notification_slot.h" namespace OHOS { @@ -30,7 +28,7 @@ public: * * @param id Indicates the ID of the NotificationSlotGroup. * The ID must be unique and its length must not exceed 1000 characters (the excess part is automatically - * truncated). + * truncated). * @param name Indicates the name of the NotificationSlotGroup. * Its length must not exceed 1000 characters (the excess part is automatically truncated). */ @@ -140,11 +138,11 @@ private: bool ReadFromParcel(Parcel &parcel); private: - std::string id_{}; - std::string name_{}; - std::string description_{}; - std::vector slots_{}; - bool isDisabled_{false}; + std::string id_ {}; + std::string name_ {}; + std::string description_ {}; + std::vector slots_ {}; + bool isDisabled_ {false}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h index 4be3ba5b49bffb0943175e61a489ee84780aacfd..ca38d5bb09ccea4d0923959d94e70de2bc0aa396 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting.h @@ -16,9 +16,6 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_H -#include -#include - #include "ans_log_wrapper.h" #include "notification_slot.h" #include "parcel.h" @@ -26,7 +23,6 @@ namespace OHOS { namespace Notification { - class NotificationSorting final : public Parcelable { public: /** @@ -175,7 +171,7 @@ private: bool isHiddenNotification_ {}; std::string groupKeyOverride_ {}; int32_t visiblenessOverride_ {}; - sptr slot_ {nullptr}; + sptr slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); friend class AdvancedNotificationService; }; diff --git a/interfaces/innerkits/ans/native/include/notification_sorting_map.h b/interfaces/innerkits/ans/native/include/notification_sorting_map.h index 54fb3f37a083a13d8310287230204f13db90946d..cd7d83a1204fca7f1029012bdef80d808e2bd705 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting_map.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting_map.h @@ -16,16 +16,11 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_MAP_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SORTING_MAP_H -#include -#include -#include - #include "notification_sorting.h" #include "parcel.h" namespace OHOS { namespace Notification { - class NotificationSortingMap final : public Parcelable { public: /** @@ -96,7 +91,6 @@ private: std::vector sortedKey_ {}; std::map sortings_ {}; }; - } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h index 1eb370e590ea1e33718589e546d77e48caab852b..7da904f412bc51169575290fe6375e245be6b0d2 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h +++ b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h @@ -16,15 +16,10 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATIN_SUBSCRIBER_INFO_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATIN_SUBSCRIBER_INFO_H -#include -#include -#include - #include "parcel.h" namespace OHOS { namespace Notification { - class NotificationSubscribeInfo final : public Parcelable { public: /** @@ -69,6 +64,20 @@ public: **/ std::vector GetAppNames() const; + /** + * @brief application current userid. + * + * @param appNames Indicates the userid of application. + **/ + void AddAppUserId(const int32_t userId); + + /** + * @brief Obtains the userid of application. + * + * @return Returns the userid of application. + **/ + int32_t GetAppUserId() const; + /** * @brief Marshals a NotificationSubscribeInfo object into a Parcel. * @@ -95,6 +104,7 @@ private: private: std::vector appNames_ {}; + int32_t userId_ {-1}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 6cbdecc3e3d64e0801dd1ca3f028fd451a4bca61..aefa50b6a58683522c91b38fa43de816ff147172 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -16,18 +16,14 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SUBSCRIBER_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_SUBSCRIBER_H -#include - #include "ans_manager_interface.h" #include "ans_subscriber_stub.h" -#include "notification_constant.h" #include "notification_request.h" #include "notification_sorting.h" #include "notification_sorting_map.h" namespace OHOS { namespace Notification { - class NotificationSubscriber { public: /** @@ -59,11 +55,9 @@ public: const std::shared_ptr &sortingMap, int deleteReason) = 0; /** - * @brief Called back when the subscriber is connected to the Advanced Notification Service (ANS). - * - * @param result Indicates subscribe result. + * Called back when the subscriber is connected to the Advanced Notification Service (ANS). **/ - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) = 0; + virtual void OnConnected() = 0; /** * @brief Called back when the subscriber receives a new notification. @@ -83,11 +77,9 @@ public: const std::shared_ptr &request, const std::shared_ptr &sortingMap) = 0; /** - * @brief Called back when the subscriber is disconnected from the ANS. - * - * @param result Indicates unsubscribe result. + * Called back when the subscriber is disconnected from the ANS. **/ - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) = 0; + virtual void OnDisconnected() = 0; /** * @brief Called back when the ranking information about the current notification changes. @@ -102,11 +94,11 @@ public: virtual void OnDied() = 0; /** - * @brief Called when the Do Not Disturb mode type changes. + * @brief Called when the Do Not Disturb date changes. * - * @param disturbMode Indicates the current Do Not Disturb mode type. + * @param date Indicates the current Do Not Disturb date. **/ - virtual void OnDisturbModeChanged(int disturbMode) = 0; + virtual void OnDoNotDisturbDateChange(const std::shared_ptr &date) = 0; private: class SubscriberImpl final : public AnsSubscriberStub { @@ -125,11 +117,11 @@ private: public: SubscriberImpl(NotificationSubscriber &subscriber); - ~SubscriberImpl(){}; + ~SubscriberImpl() {}; - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnConnected() override; - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + void OnDisconnected() override; void OnConsumed(const sptr ¬ification) override; @@ -143,7 +135,7 @@ private: void OnUpdated(const sptr ¬ificationMap) override; - void OnDisturbModeChanged(NotificationConstant::DisturbMode mode) override; + void OnDoNotDisturbDateChange(const sptr &date) override; bool GetAnsManagerProxy(); diff --git a/interfaces/innerkits/ans/native/include/notification_template.h b/interfaces/innerkits/ans/native/include/notification_template.h new file mode 100644 index 0000000000000000000000000000000000000000..0b56be3373617c70a946805b4e0d02ad3a035833 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_template.h @@ -0,0 +1,95 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_TEMPLATE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_TEMPLATE_H + +#include +#include +#include "parcel.h" +#include "ohos/aafwk/content/want_params.h" + +namespace OHOS { +namespace Notification { +class NotificationTemplate : public Parcelable { +public: + /** + * Default constructor used to create an empty NotificationTemplate instance. + */ + NotificationTemplate() = default; + + /** + * Default deconstructor used to deconstruct. + */ + ~NotificationTemplate() = default; + + /** + * Sets the template name to be included in a template notification. + * @param name template name. + */ + void SetTemplateName(const std::string &name); + + /** + * Obtains the template name to be included in a template notification. + * @return template name. + */ + std::string GetTemplateName() const; + + /** + * Sets the template data to be included in a template notification. + * @param data template data. + */ + void SetTemplateData(const std::shared_ptr &data); + + /** + * Obtains the template data to be included in a template notification. + * @return template data. + */ + std::shared_ptr GetTemplateData() const; + + /** + * Returns a string representation of the object. + * @return a string representation of the object. + */ + std::string Dump(); + + /** + * Marshal a object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationTemplate + */ + static NotificationTemplate *Unmarshalling(Parcel &parcel); + +private: + /** + * Read a NotificationTemplate object from a Parcel. + * @param parcel the parcel + */ + bool ReadFromParcel(Parcel &parcel); + +private: + std::string templateName_; + std::shared_ptr templateData_ {}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_TEMPLATE_H + diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 1327bca968d9fd37054852492c00e3fe9c0c05c4..2e68134dcd223b881947c9a6d78c73872d89f8cf 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -16,19 +16,15 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H -#include -#include -#include -#include #include "notification_constant.h" -#include "pac_map.h" -#include "want.h" +#include "notification_json_convert.h" #include "parcel.h" #include "uri.h" +#include "want.h" namespace OHOS { namespace Notification { -class NotificationUserInput : public Parcelable { +class NotificationUserInput : public Parcelable, public NotificationJsonConvertionBase { public: /** * Sets the input source of this NotificationUserInput object. @@ -50,22 +46,22 @@ public: * collection services when sending input results to an WantAgent. * @param userInputs Indicates the list of NotificationUserInput objects for which the input results are provided. * @param want Indicates the Want to which the input results are to be added. - * @param pacMap Indicates the PacMap object holding the input results. - * The PacMap key must match the keys contained in the objects specified in userInputs. + * @param additional Indicates the AAFwk::WantParams object holding the input results. + * The AAFwk::WantParams key must match the keys contained in the objects specified in userInputs. */ static void AddInputsToWant(const std::vector> &userInputs, - AAFwk::Want &want, const AppExecFwk::PacMap &pacMap); + AAFwk::Want &want, const AAFwk::WantParams &additional); /** * Obtains the input text results from a specified Want. * @param want Indicates the Want object containing one or more user input results. - * @return the PacMap object containing the input text results. + * @return the AAFwk::WantParams object containing the input text results. */ - static std::shared_ptr GetInputsFromWant(const AAFwk::Want &want); + static std::shared_ptr GetInputsFromWant(const AAFwk::Want &want); /** * Adds the given NotificationUserInput object of a specified MIME type to an Want. This method is similar to - * addInputsToWant(NotificationUserInput, Want, PacMap) except that the MIME type must be specified. + * addInputsToWant(NotificationUserInput, Want, AAFwk::WantParams) except that the MIME type must be specified. * @param userInput Indicates the NotificationUserInput object for which the input results are provided. * @param want Indicates the Want to which the input results are to be added. * @param results Indicates a map containing the MIME type and its URI result. @@ -86,7 +82,8 @@ public: public: /** * A static function used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param inputKey Indicates the AAFwk::WantParams key used to identify this input + * when the input is collected from the user. * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if * inputKey is empty. */ @@ -94,14 +91,15 @@ public: /** * A static function used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param inputKey Indicates the AAFwk::WantParams key used to identify this input + * when the input is collected from the user. * @param tag Indicates the tag to be displayed. * @param options Indicates the list of predefined options to be provided for user input. * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, * indicating that arbitrary text values are allowed. If this parameter is set to false, you must pass a non-empty * std::vector of options or a non-empty std::set of permitMimeTypes. Otherwise, return empty object. * @param permitMimeTypes Indicates the MIME type allowed. - * @param pacMap Indicates the PacMap object containing the additional data. + * @param additional Indicates the AAFwk::WantParams object containing the additional data. * @param editType Indicates the edit type to set. For details about available values, see * NotificationConstant::InputEditType. * @return the shared_ptr object owns the created NotificationUserInput object otherwise return empty object if @@ -109,7 +107,7 @@ public: */ static std::shared_ptr Create(const std::string &inputKey, const std::string &tag, const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, - const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType); + const std::shared_ptr &additional, NotificationConstant::InputEditType editType); /** * Default deconstructor used to deconstruct. @@ -124,16 +122,16 @@ public: /** * Adds additional data to this Builder. - * The value of pacMap will replace the existing extras value in this Builder. - * @param pacMap Indicates the PacMap object containing the additional data. + * The value of AAFwk::WantParams will replace the existing extras value in this Builder. + * @param additional Indicates the AAFwk::WantParams object containing the additional data. */ - void AddAdditionalData(AppExecFwk::PacMap &pacMap); + void AddAdditionalData(AAFwk::WantParams &additional); /** * Obtains the additional data included in this NotificationUserInput object. * @return the additional data in this NotificationUserInput object. */ - const std::shared_ptr GetAdditionalData() const; + const std::shared_ptr GetAdditionalData() const; /** * Sets the edit type of the options provided by this NotificationUserInput object. @@ -216,6 +214,19 @@ public: */ std::string Dump(); + /** + * Converts a NotificationUserInput object into a Json. + * @param jsonObject Indicates the Json object. + */ + bool ToJson(nlohmann::json &jsonObject) const override; + + /** + * Creates a NotificationUserInput object from a Json. + * @param jsonObject Indicates the Json object. + * @return the NotificationUserInput. + */ + static NotificationUserInput *FromJson(const nlohmann::json &jsonObject); + /** * Marshal a object into a Parcel. * @param parcel the object into the parcel @@ -236,13 +247,15 @@ private: /** * A constructor used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param inputKey Indicates the AAFwk::WantParams key used to identify this input + * when the input is collected from the user. */ explicit NotificationUserInput(const std::string &inputKey); /** * A constructor used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the PacMap key used to identify this input when the input is collected from the user. + * @param inputKey Indicates the AAFwk::WantParams key used to identify this input + * when the input is collected from the user. * @param tag Indicates the tag to be displayed. * @param options Indicates the list of predefined options to be provided for user input. * @param permitFreeFormInput Specifies whether to allow arbitrary text values. The default value is true, @@ -250,13 +263,13 @@ private: * setOptions(const std::vector &) to set a non-empty list or call * setPermitMimeTypes(std::string, bool) to allow a MIME type. * @param permitMimeTypes Indicates the MIME type allowed. - * @param pacMap Indicates the PacMap object containing the additional data. + * @param additional Indicates the AAFwk::WantParams object containing the additional data. * @param editType Indicates the edit type to set. For details about available values, see * NotificationConstant::InputEditType. */ NotificationUserInput(const std::string &inputKey, const std::string &tag, const std::vector &options, bool permitFreeFormInput, const std::set &permitMimeTypes, - const std::shared_ptr &pacMap, NotificationConstant::InputEditType editType); + const std::shared_ptr &additional, NotificationConstant::InputEditType editType); /** * Read a NotificationUserInput object from a Parcel. @@ -270,7 +283,7 @@ private: std::vector options_ {}; bool permitFreeFormInput_ {true}; std::set permitMimeTypes_ {}; - std::shared_ptr pacMap_ {}; + std::shared_ptr additionalData_ {}; NotificationConstant::InputEditType editType_ {NotificationConstant::InputEditType::EDIT_AUTO}; }; } // namespace Notification diff --git a/interfaces/innerkits/ans/native/include/reminder_helper.h b/interfaces/innerkits/ans/native/include/reminder_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..0d7f34d8880c0a3ee6fec2c2810703f5256b6473 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_helper.h @@ -0,0 +1,106 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_REMINDER_HELPER_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_REMINDER_HELPER_H + +#include + +#include "notification_slot.h" +#include "reminder_request.h" + +namespace OHOS { +namespace Notification { +class ReminderHelper { +public: + /** + * Publishes a scheduled reminder. + * + * Third-party applications can call this method to publish a scheduled reminder. After this method is called, + * the timing and pop-up notification functions of the calling application will be performed by the system service + * agent in the background, even when the application is frozen or exits. You can call the + * ReminderRequest::SetWantAgentInfo(WantAgentInfo wantAgentInfo) method to specify whether to start the + * application after the pop-up notification is taped. + * + * The background agent maintains an ordered list of reminders for all third-party applications. The list is + * updated based on the scheduled trigger time of each reminder. The system starts only one most recent scheduled + * reminder at a time. If a reminder with a more recent trigger time is added, the new scheduled reminder will + * be put on top of the list. The next reminder is triggered only after the current reminder is complete. + * + * @note One application can create a maximum of 30 valid reminders, and the total number of valid reminders + * in the system cannot exceed 2000. The minimum snooze interval for a reminder is 5 minutes. + * + * @param reminder Indicates the reminder instance to publish. This parameter cannot be null. Otherwise, + * an exception will be thrown due to invalid parameters, causing the application to crash. + * @return Returns publish reminder result. + * 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); + + /** + * Cancels a specified reminder. + * + * @param reminderId Indicates the ID of the reminder instace to cancel. + * @return Returns cancel reminder result. + */ + static ErrCode CancelReminder(const int32_t reminderId); + + /** + * Cancels all reminders of current third part application. + * + * @return Returns cancel all reminders result. + */ + static ErrCode CancelAllReminders(); + + /** + * Obtains all valid reminder notifications set by the current application, namely, the reminders that will + * still be triggered later. If a reminder will never be triggered again, it is not considered a valid reminder. + * + * @param[out] validReminders Indicates an initial vector to recieve the result. + * @return Returns an array list containing all valid reminder notifications set by the current application. + */ + static ErrCode GetValidReminders(std::vector> &validReminders); + + /** + * Creates a 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. + * + * You can call the ReminderRequest#setSlotId(String) method to bind the slot for publishing a reminder. + * When the application is uninstalled, all notification slots related to the application will be deleted. + * + * @param slot Indicates the NotificationSlot instance to add. + * @return Returns add notification slot result. + */ + static ErrCode AddNotificationSlot(const NotificationSlot &slot); + + /** + * Removes a NotificationSlot instance used by the reminder. + * + * @param slotType Indicates the type of the slot, which is set when calling AddNotificationSlot to add a slot. + * @return Returns remove notification slot result. + */ + static ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType); + +private: + static bool CheckPermission(); +}; +} // namespace Reminder +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_REMINDER_HELPER_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/reminder_request.h b/interfaces/innerkits/ans/native/include/reminder_request.h new file mode 100644 index 0000000000000000000000000000000000000000..b671414152b079807abe67523dae330629a23d0b --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -0,0 +1,630 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_H + +#include +#include + +#include "notification_constant.h" +#include "notification_request.h" + +namespace OHOS { +namespace Notification { +class ReminderRequest : public Parcelable { +public: + /** + * @brief Supported reminder type. + */ + enum class ReminderType : uint8_t { + /** + * Indicates the classification of reminder for timer. + */ + TIMER, + + /** + * Indicates the classification of reminder for calendar. + */ + CALENDAR, + + /** + * Indicates the classification of reminder for alarm. + */ + ALARM, + INVALID + }; + + /** + * @brief Supported action button type. + */ + enum class ActionButtonType : uint8_t { + /** + * @brief Indicates that this action button is used to close reminder's notfication. + * It always works well, whether the application is running at the time. + * + */ + CLOSE, + + /** + * @brief Indicates that this action button is used to snooze reminder. + * It always work well, whether the application is running at the time. + * + */ + SNOOZE, + INVALID + }; + + /** + * @brief Supported notification update type. + */ + enum class UpdateNotificationType : uint8_t { + COMMON, + REMOVAL_WANT_AGENT, + WANT_AGENT, + MAX_SCREEN_WANT_AGENT, + CONTENT + }; + + /** + * @brief Enumerates the Time type for converting between c time and acture time. + */ + enum class TimeTransferType : uint8_t { + YEAR, + MONTH, + WEEK + }; + + /** + * @brief Enumerates the Time format for print. + */ + enum class TimeFormat : uint8_t { + YMDHMS, + HM + }; + + /** + * @brief Attributes of action button. + */ + struct ActionButtonInfo { + /** + * Type of the button. + */ + ActionButtonType type; + + /** + * Content show on the button. + */ + std::string title = ""; + }; + + /** + * @brief Want agent information. Indicates the package and the ability to switch to. + */ + struct WantAgentInfo { + std::string pkgName = ""; + std::string abilityName = ""; + }; + + struct MaxScreenAgentInfo { + std::string pkgName = ""; + std::string abilityName = ""; + }; + + /** + * @brief Copy construct from an exist reminder. + * + * @param Indicates the exist reminder. + */ + explicit ReminderRequest(const ReminderRequest &other); + ReminderRequest& operator = (const ReminderRequest &other); + virtual ~ReminderRequest() override {}; + + /** + * @brief Marshal a NotificationRequest object into a Parcel. + * + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * @brief Unmarshal object from a Parcel. + * + * @return the NotificationRequest + */ + static ReminderRequest *Unmarshalling(Parcel &parcel); + virtual bool ReadFromParcel(Parcel &parcel); + + /** + * @brief If the reminder is showing on the notification panel, it should not be removed automatically. + * + * @return true if it can be removed automatically. + */ + bool CanRemove() const; + + bool CanShow() const; + + /** + * @brief Obtains all the information of the reminder. + * + * @return Information of the reminder. + */ + std::string Dump() const; + + /** + * @brief Obtains the configured action buttons. + * + * @return map of action buttons. + */ + std::map GetActionButtons() const; + + /** + * @brief Obtains the configured content. + * + * @return content text. + */ + std::string GetContent() const; + + /** + * @brief Obtains the configured expired content. + * + * @return expired content text. + */ + std::string GetExpiredContent() const; + + std::shared_ptr GetMaxScreenWantAgentInfo() const; + + /** + * @brief Obtains notification id. + * + * @return notification id. + */ + int32_t GetNotificationId() const; + + /** + * @brief Obtains notification request. + * + * @return notification request instance. + */ + sptr GetNotificationRequest() const; + + /** + * @brief Obtains reminder id. + * + * @return reminder id. + */ + int32_t GetReminderId() const; + + uint64_t GetReminderTimeInMilli() const; + + /** + * @brief Obtains reminder type. + * + * @return reminder type. + */ + ReminderType GetReminderType() const; + + /** + * @brief Obtains the ringing or vibration duration configured for this reminder. + * + * @return uint16_t The ringing or vibration duration in seconds. + */ + uint16_t GetRingDuration() const; + + /** + * @brief Obtains slot type. + * + * @return slot type. + */ + NotificationConstant::SlotType GetSlotType() const; + + std::string GetSnoozeContent() const; + uint8_t GetSnoozeTimes() const; + uint8_t GetSnoozeTimesDynamic() const; + uint8_t GetState() const; + + /** + * @brief Obtains the Time Interval in seconds. + * + * @return uint64_t Time Interval in seconds. + */ + uint64_t GetTimeInterval() const; + + /** + * @brief Obtains title. + * + * @return title. + */ + std::string GetTitle() const; + + /** + * @brief Obtains trigger time in milli. + * + * @return trigger time. + */ + uint64_t GetTriggerTimeInMilli() const; + + /** + * @brief Obtains want agent information. + * + * @return want agent information. + */ + std::shared_ptr GetWantAgentInfo() const; + + /** + * @brief Inits reminder id when publish reminder success. + * Assign a unique reminder id for each reminder. + */ + void InitReminderId(); + + /** + * @brief Check the reminder is alerting or not. + * + * @return true if the reminder is playing sound or vibrating. + */ + bool IsAlerting() const; + + /** + * @brief Check the reminder is expired or not. + * + * @return true is the reminder is expired. + */ + bool IsExpired() const; + + /** + * @brief Check the reminder is showing on the panel. + * + * @return true if the reminder is showing on the panel. + */ + bool IsShowing() const; + + /** + * @brief Closes the reminder by manual. + * + * 1) Resets the state of "Alering/Showing/Snooze" + * 2) Resets snoozeTimesDynamic_ if update to next trigger time, otherwise set reminder to expired. + * + * @param updateNext Whether to update to next reminder. + */ + void OnClose(bool updateNext); + + /** + * @brief When date/time change, reminder need to refresh next trigger time. + * + * @return true if need to show reminder immediately. + */ + virtual bool OnDateTimeChange(); + + /** + * When shown notification is covered by a new notification with the same id, we should remove + * the state of showing, so that the reminder can be removed automatically when it is expired. + */ + void OnSameNotificationIdCovered(); + + /** + * @brief Shows the reminder on panel. TriggerTime will be updated to next. + * + * @param isPlaySoundOrVibration true means it is play sound or vibration. + * @param isSysTimeChanged true means it is called when the system time is changed by user, otherwise false. + * @param allowToNotify true means that the notification will be shown as normal, otherwise false. + */ + void OnShow(bool isPlaySoundOrVibration, bool isSysTimeChanged, bool allowToNotify); + + /** + * @brief Reset the state of "Showing" when the reminder is shown failed. + */ + void OnShowFail(); + + /** + * @brief Snooze the reminder by manual. + * + * 1) Updates the trigger time to the next one. + * 2) Updates the notification content for "Snooze". + * 3) Switchs the state from "Showing[, Alerting]" to "Snooze". + */ + bool OnSnooze(); + + /** + * @brief Starts the reminder + * + * Sets the state from "Inactive" to "Active". + */ + void OnStart(); + + /** + * @brief Stops the reminder. + * + * Sets the state from "Active" to "Inactive". + */ + void OnStop(); + + /** + * @brief Terminate the alerting reminder, which is executed when the ring duration is over. + * + * 1) Disables the state of "Alerting". + * 2) Updates the notification content for "Alert". + * + * @return false if alerting state has already been set false before calling the method. + */ + bool OnTerminate(); + + /** + * @brief When timezone change, reminder need to refresh next trigger time. + * + * @return true if need to show reminder immediately. + */ + virtual bool OnTimeZoneChange(); + + /** + * @brief Sets action button. + * + * @param title Indicates the title of the button. + * @param type Indicates the type of the button. + * @return Current reminder self. + */ + ReminderRequest& SetActionButton(const std::string &title, const ActionButtonType &type); + + /** + * @brief Sets reminder content. + * + * @param content Indicates content text. + * @return Current reminder self. + */ + ReminderRequest& SetContent(const std::string &content); + + /** + * @brief Sets reminder is expired or not. + * + * @param isExpired Indicates the reminder is expired or not. + */ + void SetExpired(bool isExpired); + + /** + * @brief Sets expired content. + * + * @param expiredContent Indicates expired content. + * @return Current reminder self. + */ + ReminderRequest& SetExpiredContent(const std::string &expiredContent); + + ReminderRequest& SetMaxScreenWantAgentInfo(const std::shared_ptr &maxScreenWantAgentInfo); + + /** + * @brief Sets notification id. + * + * @param notificationId Indicates notification id. + * @return Current reminder self. + */ + ReminderRequest& SetNotificationId(int32_t notificationId); + + /** + * @brief Sets reminder id. + * + * @param reminderId Indicates reminder id. + */ + void SetReminderId(int32_t reminderId); + + void SetReminderTimeInMilli(const uint64_t reminderTimeInMilli); + + /** + * @brief Sets the ringing or vibration duration for this reminder, in seconds. + * + * @param ringDurationInSeconds Indicates the duration. The defautl is 1 second. + * @return Current reminder self. + */ + ReminderRequest& SetRingDuration(const uint64_t ringDurationInSeconds); + + /** + * @brief Sets slot type. + * + * @param slotType Indicates slot type. + * @return Current reminder self. + */ + ReminderRequest& SetSlotType(const NotificationConstant::SlotType &slotType); + + ReminderRequest& SetSnoozeContent(const std::string &snoozeContent); + + /** + * @brief Set the number of snooze times for this reminder. + * + * @note If the value of snoozeTimes is less than or equals to 0, this reminder is a one-shot + * reminder and will not be snoozed. + * + * It the value of snoozeTimes is greater than 0, for example, snoozeTimes=3, this reminder + * will be snoozed three times after the first alarm, that is, this reminder will be triggered + * for four times. + * + * This method does not take affect on the reminders for countdown timers. + * + * @param snoozeTimes Indicates the number of times that the reminder will be snoozed. + * @return ReminderRequest& Current reminder self. + */ + ReminderRequest& SetSnoozeTimes(const uint8_t snoozeTimes); + + ReminderRequest& SetSnoozeTimesDynamic(const uint8_t snooziTimes); + + /** + * @brief Sets the Time Interval for this reminder, in seconds. The default value is 0. + * + * @note The minimum snooze interval is 5 minute. If the snooze interval is set to a value greater + * than 0 and less than 5 minutes, the system converts it to 5 minutes by default. + * + * This method does not take effect on the reminders for countdown timers. + * + * @param timeIntervalInSeconds Indicates the snooze interval to set. If the value is less or equals to 0, + * the reminder will not be snoozed. + * @return ReminderRequest& Current reminder self. + */ + ReminderRequest& SetTimeInterval(const uint64_t timeIntervalInSeconds); + + /** + * @brief Sets title. + * + * @param title Indicates title. + * @return Current reminder self. + */ + ReminderRequest& SetTitle(const std::string &title); + + /** + * @brief Sets trigger time. + * + * @param triggerTimeInMilli Indicates trigger time in milli. + */ + void SetTriggerTimeInMilli(uint64_t triggerTimeInMilli); + + /** + * @brief Sets want agent information. + * + * @param wantAgentInfo Indicates want agent information. + * @return Current reminder self. + */ + ReminderRequest& SetWantAgentInfo(const std::shared_ptr &wantAgentInfo); + + bool ShouldShowImmediately() const; + + /** + * @brief Updates {@link triggerTimeInMilli_} to next. + * @note If next trigger time not exist, {@link isExpired_} flag will be set with true. + * + * @return true if next trigger time exist and set success. + */ + virtual bool UpdateNextReminder(); + + /** + * @brief Update notification attibutes. + * + * Some attributes need to be updated after the reminder published or before the notification publish. + * 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. + */ + void UpdateNotificationRequest(UpdateNotificationType type, std::string extra); + + static int32_t GLOBAL_ID; + static const uint64_t INVALID_LONG_LONG_VALUE; + static const uint16_t INVALID_U16_VALUE; + static const uint8_t INVALID_U8_VALUE; + static const uint16_t MILLI_SECONDS; + static const uint16_t SAME_TIME_DISTINGUISH_MILLISECONDS; + static const std::string NOTIFICATION_LABEL; + + /** + * @brief Show the reminder with a notification. + */ + static const std::string REMINDER_EVENT_ALARM_ALERT; + + /** + * @brief Close the reminder when click the close button of notification. + */ + static const std::string REMINDER_EVENT_CLOSE_ALERT; + + /** + * @brief Snooze the reminder when click the snooze button of notification. + */ + static const std::string REMINDER_EVENT_SNOOZE_ALERT; + + /** + * @brief Used to control ring duration. + */ + static const std::string REMINDER_EVENT_ALERT_TIMEOUT; + + /** + * @brief Update the reminder when remove notification from the systemUI. + */ + static const std::string REMINDER_EVENT_REMOVE_NOTIFICATION; + static const std::string PARAM_REMINDER_ID; + static int GetActualTime(const TimeTransferType &type, int cTime); + static int GetCTime(const TimeTransferType &type, int actualTime); + +protected: + ReminderRequest(); + explicit ReminderRequest(ReminderType reminderType); + std::string GetDateTimeInfo(const time_t &timeInSecond) const; + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const + { + return INVALID_LONG_LONG_VALUE; + } + static const int BASE_YEAR; + +private: + void AddActionButtons(const bool includeSnooze); + void AddRemovalWantAgent(); + std::shared_ptr CreateWantAgent(AppExecFwk::ElementName &element) const; + uint64_t GetNowInstantMilli() const; + std::string GetShowTime(const uint64_t showTime) const; + std::string GetTimeInfoInner(const time_t &timeInSecond, const TimeFormat &format) const; + std::string GetState(const uint8_t state) const; + bool HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optTriggerTime); + bool HandleTimeZoneChange(uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime); + void InitNotificationRequest(); + void SetMaxScreenWantAgent(AppExecFwk::ElementName &element); + void SetState(bool deSet, const uint8_t newState, std::string function); + void SetWantAgent(AppExecFwk::ElementName &element); + void UpdateActionButtons(const bool &setSnooze); + bool UpdateNextReminder(const bool &force); + void UpdateNotificationContent(const bool &setSnooze); + void UpdateNotificationCommon(); + + /** + * @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(); + + /** + * @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(); + + static const uint8_t REMINDER_STATUS_INACTIVE; + static const uint8_t REMINDER_STATUS_ACTIVE; + static const uint8_t REMINDER_STATUS_ALERTING; + static const uint8_t REMINDER_STATUS_SHOWING; + static const uint8_t REMINDER_STATUS_SNOOZE; + static const uint32_t MIN_TIME_INTERVAL_IN_MILLI; + + std::string content_ {}; + std::string expiredContent_ {}; + std::string snoozeContent_ {}; + std::string displayContent_ {}; + std::string title_ {}; + bool isExpired_ {false}; + uint8_t snoozeTimes_ {0}; + uint8_t snoozeTimesDynamic_ {0}; + uint8_t state_ {0}; + int32_t notificationId_ {0}; + int32_t reminderId_ {-1}; + + // Indicates the reminder has been shown in the past time. + // When the reminder has been created but not showed, it is equals to 0. + uint64_t reminderTimeInMilli_ {0}; + uint64_t ringDurationInMilli_ {MILLI_SECONDS}; + uint64_t triggerTimeInMilli_ {0}; + uint64_t timeIntervalInMilli_ {0}; + ReminderType reminderType_ {ReminderType::INVALID}; + NotificationConstant::SlotType slotType_ {NotificationConstant::SlotType::SOCIAL_COMMUNICATION}; + sptr notificationRequest_ = nullptr; + std::shared_ptr wantAgentInfo_ = nullptr; + std::shared_ptr maxScreenWantAgentInfo_ = nullptr; + std::map actionButtonMap_ {}; +}; +} // namespace Reminder +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h new file mode 100644 index 0000000000000000000000000000000000000000..07239f1ea3b9cb57afcee7db461a6fc0d04969cf --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h @@ -0,0 +1,155 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_ALARM_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_ALARM_H + +#include "reminder_request.h" + +#include + +namespace OHOS { +namespace Notification { +class ReminderRequestAlarm : public ReminderRequest { +public: + /** + * @brief A {@link ReminderRequest} child class used for creating reminders of alarm clocks. + * You can use this class to publish alarm reminders at a specified time (accurate to minute) on a + * particular day or on particular days every week. + * + * @note The params must meet the following conditions, + * otherwise the application may crash due to an illegal parameter exception. + * + * @param hour The value must between [0, 23]. + * @param minute The value must between [0, 59]. + * @param daysOfWeek The value must between [1, 7], and the length of array can not be greater than 7. + * + * @see ReminderRequestTimer + */ + ReminderRequestAlarm(uint8_t hour, uint8_t minute, std::vector daysOfWeek); + + /** + * @brief Copy construct from an exist reminder. + * + * @param Indicates the exist alarm reminder. + */ + explicit ReminderRequestAlarm(const ReminderRequestAlarm &other); + ReminderRequestAlarm& operator = (const ReminderRequestAlarm &other); + ~ReminderRequestAlarm() override {}; + + /** + * Obtains the repeat days vector. + * + * @return vector of repeat days. + */ + std::vector GetDaysOfWeek() const; + + /** + * @brief Obtains the setted {@link hour_}. + * + * @return setted hour. + */ + uint8_t GetHour() const; + + /** + * @brief Obtains the setted {@link minute_}. + * + * @return setted minute. + */ + uint8_t GetMinute() const; + uint8_t GetRepeatDay() const; + virtual bool OnDateTimeChange() override; + virtual bool OnTimeZoneChange() override; + virtual bool UpdateNextReminder() override; + + /** + * Marshal a reminder object into a Parcel. + * + * @param parcel Indicates the Parcel. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * + * @param parcel Indicates the Parcel. + * @return reminder object. + */ + static ReminderRequestAlarm *Unmarshalling(Parcel &parcel); + + /** + * Unmarshal unique properties of alarm from a Parcel. + * + * @param parcel Indicates the Parcel. + * @return true if read parcel success. + */ + bool ReadFromParcel(Parcel &parcel) override; + +protected: + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; + +private: + ReminderRequestAlarm() : ReminderRequest() {}; + void CheckParamValid() const; + + /** + * Obtains the next trigger time. + * + * @param forceToGetNext Indicates whether force to get next reminder. + * When set the alarm firstly, you should set force with true, so if repeat information + * is not set, and the target time is overdue, the reminder will be set to next day. + * When change the time manually by user, you should set force with false, so if repeat + * information is not set, and target time is overdue, the reminder will not be set to + * next day. + * @return next trigger time in milli. + */ + uint64_t GetNextTriggerTime(bool forceToGetNext) const; + + /** + * Judge is it the repeat day setted by user or not. + * + * @param day Indicates the day of week. + * @return true if it is a repeat day. + */ + bool IsRepeatDay(int day) const; + bool IsRepeatReminder() const; + void SetDaysOfWeek(bool set, std::vector daysOfWeek); + + /** + * Obtains the next day interval if it is a week repeat alarm. + * + * @param now Indicates current time. + * @param now Indicatet target time. + * @return next day interval. Returns {@link INVALID_INT_VALUE} if it is not a week repeat alarm. + */ + int8_t GetNextAlarm(const time_t now, const time_t target) const; + + static const uint8_t DAYS_PER_WEEK; + static const uint8_t MONDAY; + static const uint8_t SUNDAY; + static const uint8_t HOURS_PER_DAY; + static const uint16_t SECONDS_PER_HOUR; + static const uint8_t MINUTES_PER_HOUR; + static const int8_t INVALID_INT_VALUE; + static const int8_t DEFAULT_SNOOZE_TIMES; + + uint8_t hour_ = {0}; + uint8_t minute_ = {0}; + uint8_t repeatDays_ = {0}; +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_ALARM_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h new file mode 100644 index 0000000000000000000000000000000000000000..8c6868e98c0537ee2d2ac89ba2f591c153f84f63 --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h @@ -0,0 +1,182 @@ +/* + * 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_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_CALENDAR_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_CALENDAR_H + +#include "reminder_request.h" + +namespace OHOS { +namespace Notification { +class ReminderRequestCalendar : public ReminderRequest { +public: + /** + * @brief A {@link ReminderRequest} child class used for creating reminders of calendar clocks. + * + * @note The params must meet the following conditions. + * otherwise the application may crash due to an illegal parameter exception. + *
    + *
  • The length of repeatMonths vectory cannot exceed 12.
  • + *
  • The length of repeateDays vectory cannot exceed 31.
  • + *
  • There must be at least one valid reminder time. Ensure that the time specified by dateTime + * does not expired, or repeatMonths and repeateDays are valid.
  • + *
+ * + * The repeateMonths and repeatDays must both be set to implements repeated reminders. + * By default, this reminder is not snoozed. You can call {@link SetTimeInterval} to + * set the snooze interval. + * + * @param dateTime Indicates the date and time when this calendar event reminder will be triggered. + * The time is accurate to minute. For example, the value + * {@link LocalDateTime(2021, 3, 3, 16, 15)} indicates that the reminder will be + * triggered at 16:15 on March 3, 2021. + * @param repeatMonths Indicates the months in which this reminder will be repeated. For example, + * the value {2, 4} indicates that the reminder will be triggered on particular + * days in February and April. + * @param repeatDays Indicates the days in a month when this reminder will be repeated. For example, + * the value {2, 4} indicates that the reminder will be triggered on the second + * and fourth day of the specific months. + */ + ReminderRequestCalendar(const tm &dateTime, + const std::vector &repeatMonths, const std::vector &repeatDays); + + explicit ReminderRequestCalendar(const ReminderRequestCalendar &other); + ReminderRequestCalendar& operator = (const ReminderRequestCalendar &other); + ~ReminderRequestCalendar() override {} + + inline uint16_t GetYear() const + { + return year_; + } + + inline uint8_t GetMonth() const + { + return month_; + } + + inline uint8_t GetDay() const + { + return day_; + } + + inline uint8_t GetHour() const + { + return hour_; + } + + inline uint8_t GetMinute() const + { + return minute_; + } + + inline uint8_t GetSecond() const + { + return second_; + } + + inline uint16_t GetFirstDesignateYear() const + { + return firstDesignateYear_; + } + + inline uint16_t GetFirstDesignageMonth() const + { + return firstDesignateMonth_; + } + + inline uint16_t GetFirstDesignateDay() const + { + return firstDesignateDay_; + } + + std::vector GetRepeatMonths() const; + std::vector GetRepeatDays() const; + + virtual bool OnDateTimeChange() override; + virtual bool OnTimeZoneChange() override; + virtual bool UpdateNextReminder() override; + + /** + * Marshal a reminder object into a Parcel. + * + * @param parcel Indicates the Parcel. + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * + * @param parcel Indicates the Parcel. + * @return reminder object. + */ + static ReminderRequestCalendar *Unmarshalling(Parcel &parcel); + + /** + * Unmarshal unique properties of alarm from a Parcel. + * + * @param parcel Indicates the Parcel. + * @return true if read parcel success. + */ + bool ReadFromParcel(Parcel &parcel) override; + + static const uint8_t MAX_MONTHS_OF_YEAR; + static const uint8_t MAX_DAYS_OF_MONTH; + +protected: + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; + +private: + ReminderRequestCalendar() : ReminderRequest() {} + + uint8_t GetDaysOfMonth(const uint16_t &year, const uint8_t &month) const; + uint8_t GetNextDay(const uint16_t &settedYear, const uint8_t &settedMonth, const tm &now, const tm &target) const; + uint64_t GetNextTriggerTime() const; + uint64_t GetNextTriggerTimeAsRepeatReminder(const tm &nowTime, const tm &tarTime) const; + uint64_t GetTimeInstantMilli( + uint16_t year, uint8_t month, uint8_t day, uint8_t hour, uint8_t minute, uint8_t second) const; + + /** + * @brief Init dateTime_ when read from parcel. + */ + void InitDateTime(); + void InitDateTime(const tm &dateTime); + bool IsRepeatReminder() const; + bool IsRepeatMonth(uint8_t month) const; + bool IsRepeatDay(uint8_t day) const; + void SetDay(const uint8_t &day, const bool &isSet); + void SetMonth(const uint8_t &month, const bool &isSet); + void SetRepeatMonths(const std::vector &repeatMonths); + void SetRepeatDaysOfMonth(const std::vector &repeateDays); + + static const uint8_t JANUARY; + static const uint8_t DECEMBER; + static const uint8_t DEFAULT_SNOOZE_TIMES; + + tm dateTime_; + uint16_t firstDesignateYear_ {1}; + uint8_t firstDesignateMonth_ {1}; + uint8_t firstDesignateDay_ {1}; + uint16_t year_ {1}; + uint8_t month_ {1}; + uint8_t day_ {1}; + uint8_t hour_ {1}; + uint8_t minute_ {1}; + uint8_t second_ {0}; + uint16_t repeatMonth_; + uint32_t repeatDay_; +}; +} +} +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_CALENDAR_H \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/reminder_request_timer.h b/interfaces/innerkits/ans/native/include/reminder_request_timer.h new file mode 100644 index 0000000000000000000000000000000000000000..9fc2362f2effe12f4758313624e55562c48318cd --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -0,0 +1,77 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_TIMER_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_TIMER_H + +#include "reminder_request.h" + +namespace OHOS { +namespace Notification { +class ReminderRequestTimer : public ReminderRequest { +public: + /** + * A constructor used to create a ReminderRequestTimer instance. The countdown timer reminder + * will be triggered after a specified duration. + * + * @note The input parameter must be larger than 0 and less than UINT64_MAX/1000, + * otherwise, the application may crash due to an illegal parameter exception. + * + * @param countDownTimeInSeconds Indicates the duration after which this timer reminder will be triggered. + */ + ReminderRequestTimer(uint64_t countDownTimeInSeconds); + + /** + * @brief Copy construct from an exist reminder. + * + * @param Indicates the exist reminder. + */ + explicit ReminderRequestTimer(const ReminderRequestTimer &other); + ReminderRequestTimer& operator = (const ReminderRequestTimer &other); + ~ReminderRequestTimer() override {}; + + uint64_t GetInitInfo() const; + virtual bool OnDateTimeChange() override; + virtual bool OnTimeZoneChange() override; + virtual bool UpdateNextReminder() override; + + /** + * Marshal a NotificationRequest object into a Parcel. + * @param parcel the object into the parcel + */ + virtual bool Marshalling(Parcel &parcel) const override; + + /** + * Unmarshal object from a Parcel. + * @return the NotificationRequest + */ + static ReminderRequestTimer *Unmarshalling(Parcel &parcel); + + bool ReadFromParcel(Parcel &parcel) override; + +protected: + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; + +private: + ReminderRequestTimer() {}; + void CheckParamsValid(const uint64_t countDownTimeInSeconds) const; + void UpdateTimeInfo(const std::string description); + uint64_t countDownTimeInSeconds_ {0}; + uint64_t firstRealTimeInMilliSeconds_ {-1}; + uint64_t whenToChangeSysTime_ {-1}; +}; +} // namespace Reminder +} // namespace OHOS +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_REQUEST_TIMER_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/cancel_listener.h b/interfaces/innerkits/wantagent/include/cancel_listener.h index 10cea7b5f323829d6d959f3b0594a985e0a2a253..cb3a24495a6fc0503f5ed214900ed5397fd5e276 100644 --- a/interfaces/innerkits/wantagent/include/cancel_listener.h +++ b/interfaces/innerkits/wantagent/include/cancel_listener.h @@ -18,12 +18,12 @@ namespace OHOS::Notification::WantAgent { class CancelListener { +public: /** * Called when a Cancel operation as completed. * * @param resultCode The final result code determined by the Send. */ -public: virtual void OnCancelled(int resultCode) = 0; virtual ~CancelListener() = default; }; diff --git a/interfaces/innerkits/wantagent/include/completed_callback.h b/interfaces/innerkits/wantagent/include/completed_callback.h index 5740a899de5027b2dfc2dd6adacd9e244d76192d..5657c86b43e504b5123cc063d4a94e1e85c6a97e 100644 --- a/interfaces/innerkits/wantagent/include/completed_callback.h +++ b/interfaces/innerkits/wantagent/include/completed_callback.h @@ -23,7 +23,8 @@ namespace OHOS::Notification::WantAgent { class CompletedCallback { - +public: + virtual ~CompletedCallback() = default; /** * Called when a Send operation as completed. * @@ -32,8 +33,6 @@ class CompletedCallback { * @param resultData The final data collected by a broadcast. * @param resultExtras The final extras collected by a broadcast. */ -public: - virtual ~CompletedCallback() = default; virtual void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, const AAFwk::WantParams &resultExtras) = 0; }; diff --git a/interfaces/innerkits/wantagent/include/completed_dispatcher.h b/interfaces/innerkits/wantagent/include/completed_dispatcher.h index bd17fbecf3aa817780cca5b056981ed8c0cf5917..3b987c8fd158c91f414dea0049da5f5d8dd41097 100644 --- a/interfaces/innerkits/wantagent/include/completed_dispatcher.h +++ b/interfaces/innerkits/wantagent/include/completed_dispatcher.h @@ -27,15 +27,6 @@ namespace OHOS::Notification::WantAgent { class PendingWant; class CompletedDispatcher : public AAFwk::WantReceiverStub { -private: - const std::shared_ptr pendingWant_; - const std::shared_ptr callback_; - const std::shared_ptr handler_; - AAFwk::Want want_; - int resultCode_ = 0; - std::string resultData_; - AAFwk::WantParams resultExtras_; - public: CompletedDispatcher(const std::shared_ptr &pendingWant, const std::shared_ptr &callback, const std::shared_ptr &handler); @@ -47,6 +38,15 @@ public: const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; void Run(); + +private: + const std::shared_ptr pendingWant_; + const std::shared_ptr callback_; + const std::shared_ptr handler_; + AAFwk::Want want_; + int resultCode_ = 0; + std::string resultData_; + AAFwk::WantParams resultExtras_; }; } // namespace OHOS::Notification::WantAgent #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_COMPLETED_DISPATCHER_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/pending_want.h b/interfaces/innerkits/wantagent/include/pending_want.h index 7ab84bd4ee814dd9eb1cfcb9e67b3c4e4933d8c1..ece50a14e2ac03fc644511454ed7ecfac1502340 100644 --- a/interfaces/innerkits/wantagent/include/pending_want.h +++ b/interfaces/innerkits/wantagent/include/pending_want.h @@ -21,18 +21,20 @@ #include #include #include "cancel_listener.h" -#include "context.h" +#include "context/context.h" #include "completed_dispatcher.h" #include "event_handler.h" #include "want.h" #include "want_agent_constant.h" -#include "want_receiver_stub.h" #include "want_params.h" +#include "want_receiver_stub.h" +#include "want_sender_info.h" +#include "want_sender_stub.h" namespace OHOS::Notification::WantAgent { class PendingWant final : public std::enable_shared_from_this, public Parcelable { public: - PendingWant(){}; + PendingWant() {}; PendingWant(const sptr &target); PendingWant(const sptr &target, const sptr whitelistToken); virtual ~PendingWant() = default; @@ -53,8 +55,8 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetAbility(const std::shared_ptr &context, int requestCode, - const std::shared_ptr &want, unsigned int flags); + static std::shared_ptr GetAbility(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); /** * Retrieve a PendingWant that will start a new ability @@ -72,9 +74,9 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetAbility(const std::shared_ptr &context, int requestCode, - const std::shared_ptr &want, unsigned int flags, - const std::shared_ptr &options); + static std::shared_ptr GetAbility(const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, + unsigned int flags, const std::shared_ptr &options); /** * Like GetAbility(Context, int, Want, int)}, but allows an @@ -93,7 +95,7 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetAbilities(const std::shared_ptr &context, + static std::shared_ptr GetAbilities(const std::shared_ptr &context, int requestCode, std::vector> &wants, unsigned int flags); /** @@ -114,7 +116,7 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetAbilities(const std::shared_ptr &context, + static std::shared_ptr GetAbilities(const std::shared_ptr &context, int requestCode, std::vector> &wants, unsigned int flags, const std::shared_ptr &options); @@ -133,14 +135,15 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetCommonEvent(const std::shared_ptr &context, + static std::shared_ptr GetCommonEvent(const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags); /** * Note that current user will be interpreted at the time the * common event is sent, not when the pending want is created. */ - static std::shared_ptr GetCommonEventAsUser(const std::shared_ptr &context, + static std::shared_ptr GetCommonEventAsUser( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags, int uid); /** @@ -158,8 +161,9 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetService(const std::shared_ptr &context, int requestCode, - const std::shared_ptr &want, unsigned int flags); + static std::shared_ptr GetService( + const std::shared_ptr &context, + int requestCode, const std::shared_ptr &want, unsigned int flags); /** * Retrieve a PendingWant that will start a foreground service. @@ -176,7 +180,8 @@ public: * parameters. May return null only if FLAG_NO_CREATE has been * supplied. */ - static std::shared_ptr GetForegroundService(const std::shared_ptr &context, + static std::shared_ptr GetForegroundService( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags); /** @@ -204,28 +209,26 @@ public: void Send(int resultCode, const sptr &target); - void Send(const std::shared_ptr &context, int resultCode, + void Send(int resultCode, const std::shared_ptr &want, const sptr &target); void Send(int resultCode, const sptr &onCompleted, const sptr &target); - void Send(const std::shared_ptr &context, int resultCode, + void Send(int resultCode, const std::shared_ptr &want, const sptr &onCompleted, const sptr &target); - void Send(const std::shared_ptr &context, int resultCode, + void Send(int resultCode, const std::shared_ptr &want, const sptr &onCompleted, const std::string &requiredPermission, const sptr &target); - void Send(const std::shared_ptr &context, int resultCode, - const std::shared_ptr &want, const sptr &onCompleted, - const std::string &requiredPermission, const std::shared_ptr &options, - const sptr &target); + void Send(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target); - int SendAndReturnResult(const std::shared_ptr &context, int resultCode, - const std::shared_ptr &want, const sptr &onCompleted, - const std::string &requiredPermission, const std::shared_ptr &options, - const sptr &target); + int SendAndReturnResult(int resultCode, const std::shared_ptr &want, + const sptr &onCompleted, const std::string &requiredPermission, + const std::shared_ptr &options, const sptr &target); std::string GetBundleName(const sptr &target); @@ -247,6 +250,8 @@ public: std::shared_ptr GetWant(const sptr &target); + std::shared_ptr GetWantSenderInfo(const sptr &target); + private: std::mutex lock_object; sptr target_; @@ -255,9 +260,6 @@ private: std::vector> cancelListeners_; class CancelReceiver : public AAFwk::WantReceiverStub { - private: - std::weak_ptr outerInstance_; - public: explicit CancelReceiver(const std::weak_ptr &outerInstance); virtual ~CancelReceiver() = default; @@ -265,9 +267,13 @@ private: void Send(const int32_t resultCode) override; void PerformReceive(const AAFwk::Want &want, int resultCode, const std::string &data, const AAFwk::WantParams &extras, bool serialized, bool sticky, int sendingUser) override; + + private: + std::weak_ptr outerInstance_; }; - static std::shared_ptr BuildServicePendingWant(const std::shared_ptr &context, + static std::shared_ptr BuildServicePendingWant( + const std::shared_ptr &context, int requestCode, const std::shared_ptr &want, unsigned int flags, WantAgentConstant::OperationType serviceKind); }; diff --git a/interfaces/innerkits/wantagent/include/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h index ce60016a4f2758f687fa2dd2495ca816d59e8b78..a41ba98ec90d32ec6bd780fdd2cc1f7d18722151 100644 --- a/interfaces/innerkits/wantagent/include/trigger_info.h +++ b/interfaces/innerkits/wantagent/include/trigger_info.h @@ -23,11 +23,11 @@ namespace OHOS::Notification::WantAgent { class TriggerInfo final : public std::enable_shared_from_this { +public: /** * Default constructor used to create a {@code TriggerInfo} instance. * */ -public: TriggerInfo(); virtual ~TriggerInfo() = default; @@ -100,17 +100,11 @@ public: */ public: class Builder final : public std::enable_shared_from_this { - private: - std::string permission_; - std::shared_ptr params_; - std::shared_ptr want_; - int resultCode_ = 0; - + public: /** * Default constructor used to create a {@code Builder} instance. * */ - public: Builder(); virtual ~Builder() = default; @@ -161,6 +155,12 @@ public: * @return Returns the created {@code TriggerInfo} object. */ std::shared_ptr Build(); + + private: + std::string permission_; + std::shared_ptr params_; + std::shared_ptr want_; + int resultCode_ = 0; }; private: diff --git a/interfaces/innerkits/wantagent/include/want_agent.h b/interfaces/innerkits/wantagent/include/want_agent.h index 06d6cd36bbaa03c524ee2600ce1c87ccd9a8f418..3af5ac876e678926e32501133313fb18c47b11a8 100644 --- a/interfaces/innerkits/wantagent/include/want_agent.h +++ b/interfaces/innerkits/wantagent/include/want_agent.h @@ -25,17 +25,14 @@ namespace OHOS::Notification::WantAgent { class WantAgent final : public std::enable_shared_from_this, public Parcelable { -private: - std::shared_ptr pendingWant_; - +public: + WantAgent() {}; + virtual ~WantAgent() = default; /** * Constructor. * * @param obj The proxy object. */ -public: - WantAgent(){}; - virtual ~WantAgent() = default; explicit WantAgent(const std::shared_ptr &pendingWant); /** @@ -48,7 +45,7 @@ public: /** * Sets proxy obj. * - * @return Return obj. + * @param obj The proxy object. */ void SetPendingWant(const std::shared_ptr &pendingWant); @@ -67,6 +64,9 @@ public: * @return Returns true if the unmarshalling is successful; returns false otherwise. */ static WantAgent *Unmarshalling(Parcel &parcel); + +private: + std::shared_ptr pendingWant_; }; } // namespace OHOS::Notification::WantAgent #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent_constant.h b/interfaces/innerkits/wantagent/include/want_agent_constant.h index 461b023c1fb8d2946e3cbff3116ed5df90150b28..4f611ffa5a2e57019cf92870fcbff9b9ee38f058 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_constant.h +++ b/interfaces/innerkits/wantagent/include/want_agent_constant.h @@ -126,7 +126,7 @@ public: }; private: - WantAgentConstant(){}; + WantAgentConstant() {}; virtual ~WantAgentConstant() = default; }; } // namespace OHOS::Notification::WantAgent diff --git a/interfaces/innerkits/wantagent/include/want_agent_helper.h b/interfaces/innerkits/wantagent/include/want_agent_helper.h index cf775dde26013fa2d08189843925e5f490a2caa6..52ea8d9834df9aa417a20d5880035047c69f349c 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_helper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_helper.h @@ -18,10 +18,11 @@ #include #include -#include "context.h" +#include "context/context.h" #include "completed_callback.h" #include "completed_dispatcher.h" #include "event_handler.h" +#include "nlohmann/json.hpp" #include "trigger_info.h" #include "want.h" #include "want_agent.h" @@ -42,10 +43,6 @@ static const int FLAG_UPDATE_CURRENT = 1 << 27; static const int FLAG_IMMUTABLE = 1 << 26; class WantAgentHelper final : public std::enable_shared_from_this { -private: - WantAgentHelper(); - virtual ~WantAgentHelper() = default; - public: /** * Obtains an WantAgent object. @@ -58,7 +55,7 @@ public: * @return Returns the created WantAgent object. */ static std::shared_ptr GetWantAgent( - const std::shared_ptr &context, const WantAgentInfo ¶msInfo); + const std::shared_ptr &context, const WantAgentInfo ¶msInfo); /** * Obtains an WantAgent object. @@ -95,8 +92,8 @@ public: * the current process. * @param paramsInfo Indicates the TriggerInfo object that contains triggering parameters. */ - static void TriggerWantAgent(const std::shared_ptr &context, - const std::shared_ptr &agent, const std::shared_ptr &callback, + static void TriggerWantAgent(const std::shared_ptr &agent, + const std::shared_ptr &callback, const TriggerInfo ¶msInfo); /** @@ -167,10 +164,31 @@ public: static void UnregisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + /** + * Convert WantAgentInfo object to json string. + * + * @param jsonObject Json object. + * @return WantAgentInfo object's json string. + */ + static std::string ToString(const std::shared_ptr &agent); + + /** + * Convert json string to WantAgentInfo object. + * + * @param jsonString Json string. + * @return WantAgentInfo object. + */ + static std::shared_ptr FromString(const std::string &jsonString); + +private: + WantAgentHelper(); + virtual ~WantAgentHelper() = default; + private: - static void Send(const std::shared_ptr &context, - const std::shared_ptr &pendingWant, WantAgentConstant::OperationType type, - const sptr &callBack, const TriggerInfo ¶msInfo); + static void Send(const std::shared_ptr &pendingWant, + WantAgentConstant::OperationType type, + const sptr &callBack, + const TriggerInfo ¶msInfo); static unsigned int FlagsTransformer(const std::vector &flags); }; diff --git a/interfaces/innerkits/wantagent/include/want_agent_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h index 15c411dc90e75bab07b2a0f44de7e35a260fd684..70315d122c3c3124d02ca7827586f99a43799054 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_info.h +++ b/interfaces/innerkits/wantagent/include/want_agent_info.h @@ -32,18 +32,11 @@ namespace OHOS::Notification::WantAgent { * */ class WantAgentInfo final : public std::enable_shared_from_this { -private: - int requestCode_ = 0; - WantAgentConstant::OperationType operationType_ = WantAgentConstant::OperationType::UNKNOWN_TYPE; - std::vector flags_ = std::vector(); - std::vector> wants_ = std::vector>(); - std::shared_ptr extraInfo_; - +public: /** * Default constructor used to create an empty WantAgentInfo instance. * */ -public: WantAgentInfo(); virtual ~WantAgentInfo() = default; @@ -119,6 +112,13 @@ public: * @return Returns the extra information of the WantAgent object. */ std::shared_ptr GetExtraInfo() const; + +private: + int requestCode_ = 0; + WantAgentConstant::OperationType operationType_ = WantAgentConstant::OperationType::UNKNOWN_TYPE; + std::vector flags_ = std::vector(); + std::vector> wants_ = std::vector>(); + std::shared_ptr extraInfo_; }; } // namespace OHOS::Notification::WantAgent #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_INFO_H \ No newline at end of file diff --git a/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h index 263310dfe9d8c8e453bc81c4d3f25ef1dc457511..8c9c141a35b4427e5295b2e8fa22bcf50f40bc21 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_log_wrapper.h @@ -16,8 +16,8 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_WANTAGENT_INCLUDE_WANT_AGENT_LOG_WRAPPER_H -#include "hilog/log.h" #include +#include "hilog/log.h" namespace OHOS::Notification::WantAgent { #ifndef WANT_AGENT_LOG_DOMAIN diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index 869beba60ae1571b8d17f51e908d61aef11a6863..edbbd33d71fed6fbdbb0d7e49f95857247434dc9 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -34,6 +34,7 @@ import { NotificationRequest } from './notification/notificationRequest'; * @since 7 * @sysCap SystemCapability.Notification.ANS * @devices phone, tablet, tv, wearable, car + * @import import notification from '@ohos.notification'; * @permission N/A */ declare namespace notification { @@ -43,39 +44,29 @@ declare namespace notification { *

If a notification with the same ID has been published by the current application and has not been deleted, * this method will update the notification. * - * @param request Indicates the {@link NotificationRequest} object for setting the notification content. - * This parameter must be specified. - * - * @since 7 + * @param Publishes a notification. */ function publish(request: NotificationRequest, callback: AsyncCallback): void; function publish(request: NotificationRequest): Promise; /** - * Cancels a published notification. + * Cancels a notification with the specified ID. * - * @param id Indicates the unique notification ID in the application. The value must be the ID - * of a published notification. Otherwise, this method does not take effect. - * - * @since 7 + * @param ID of the notification to cancel, which must be unique in the application. */ function cancel(id: number, callback: AsyncCallback): void; /** - * Cancels a published notification matching the specified {@code label} and {@code notificationId}. + * Cancels a notification with the specified label and ID. * - * @param label Indicates the label of the notification to cancel. - * @param id Indicates the ID of the notification to cancel. - * - * @since 7 + * @param ID of the notification to cancel, which must be unique in the application. + * @param Label of the notification to cancel. */ function cancel(id: number, label: string, callback: AsyncCallback): void; function cancel(id: number, label?: string): Promise; /** - * Cancels all the published notifications. - * - * @since 7 + * Cancels all notifications of the current application. */ function cancelAll(callback: AsyncCallback): void; function cancelAll(): Promise; @@ -87,18 +78,23 @@ declare namespace notification { * This parameter must be specified. * * @systemapi Hide this for inner system use. - * @since 7 */ function addSlot(slot: NotificationSlot, callback: AsyncCallback): void; - function addSlot(slot: NotificationSlot): Promise; /** * Creates a notification slot. * - * @param slot Indicates the notification slot to be created, which is set by {@link SlotType}. + * @param slot Indicates the notification slot to be created, which is set by {@link NotificationSlot}. * This parameter must be specified. * - * @since 7 + * @systemapi Hide this for inner system use. + */ + function addSlot(slot: NotificationSlot): Promise; + + /** + * Adds a slot type. + * + * @param Slot type to add. */ function addSlot(type: SlotType, callback: AsyncCallback): void; function addSlot(type: SlotType): Promise; @@ -110,66 +106,83 @@ declare namespace notification { * This parameter must be specified. * * @systemapi Hide this for inner system use. - * @since 7 */ function addSlots(slots: Array, callback: AsyncCallback): void; + + /** + * Creates a notification slot. + * + * @param slots Indicates the notification slots to be created, which is set by {@link NotificationSlot}. + * This parameter must be specified. + * + * @systemapi Hide this for inner system use. + */ function addSlots(slots: Array): Promise; /** - * Queries a created notification slot. + * Obtains a notification slot of the specified slot type. * - * @param slotType Indicates the type of the slot, which is created by + * @param Type of the notification slot to obtain. * * @return Returns the created {@link NotificationSlot}. - * - * @since 7 */ function getSlot(slotType: SlotType, callback: AsyncCallback): void; function getSlot(slotType: SlotType): Promise; /** - * Obtains all notification slots of this application. + * Obtains all NotificationSlot objects created by the current application. * * @return Returns all notification slots of this application. - * - * @since 7 */ function getSlots(callback: AsyncCallback>): void; function getSlots(): Promise>; /** - * Deletes a created notification slot based on the slot type. - * - * @param slotType Indicates the type of the slot. + * Removes a NotificationSlot of the specified SlotType created by the current application. * - * @since 7 + * @param Type of the NotificationSlot to remove. */ function removeSlot(slotType: SlotType, callback: AsyncCallback): void; function removeSlot(slotType: SlotType): Promise; /** - * Deletes all notification slots. - * - * @since 7 + * Removes all NotificationSlot objects created by the current application. */ function removeAllSlots(callback: AsyncCallback): void; function removeAllSlots(): Promise; /** - * Indicates the type of the slot - * - * @since 7 + * Describes NotificationSlot types. */ export enum SlotType { + /** + * NotificationSlot of an unknown type. + */ UNKNOWN_TYPE = 0, + + /** + * NotificationSlot for social communication. + */ SOCIAL_COMMUNICATION = 1, + + /** + * NotificationSlot for service information. + */ SERVICE_INFORMATION = 2, + + /** + * NotificationSlot for service information. + */ CONTENT_INFORMATION = 3, + + /** + * NotificationSlot for other purposes. + */ OTHER_TYPES = 0xFFFF, } /** - * Indicates the type of the content + * Describes notification content types. * * @name ContentType * @since 7 @@ -178,23 +191,63 @@ declare namespace notification { * @permission N/A */ export enum ContentType { + /** + * Normal text notification. + */ NOTIFICATION_CONTENT_BASIC_TEXT, + + /** + * Long text notification. + */ NOTIFICATION_CONTENT_LONG_TEXT, + + /** + * Picture-attached notification. + */ NOTIFICATION_CONTENT_PICTURE, + + /** + * Conversation notification. + */ NOTIFICATION_CONTENT_CONVERSATION, + + /** + * Multi-line text notification. + */ NOTIFICATION_CONTENT_MULTILINE, } /** * Indicates the level of the slot - * - * @since 7 */ export enum SlotLevel { + /** + * Indicates that the notification function is disabled. + */ LEVEL_NONE = 0, + + /** + * Indicates that the notification function is enabled but notification + * icons are not displayed in the status bar, with no banner or prompt tone. + */ LEVEL_MIN = 1, + + /** + * Indicates that the notification function is enabled and notification + * icons are displayed in the status bar, with no banner or prompt tone. + */ LEVEL_LOW = 2, + + /** + * Indicates that the notification function is enabled and notification + * icons are displayed in the status bar, with no banner but with a prompt tone. + */ LEVEL_DEFAULT = 3, + + /** + * Indicates that the notification function is enabled and notification + * icons are displayed in the status bar, with a banner and a prompt tone. + */ LEVEL_HIGH = 4, } @@ -202,119 +255,214 @@ declare namespace notification { * subscribe * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; + + /** + * subscribe + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback): void; + + /** + * subscribe + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function subscribe(subscriber: NotificationSubscriber, info?: NotificationSubscribeInfo): Promise; /** * unsubscribe * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback): void; + + /** + * unsubscribe + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function unsubscribe(subscriber: NotificationSubscriber): Promise; /** * enableNotification * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; + + /** + * enableNotification + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function enableNotification(bundle: BundleOption, enable: boolean): Promise; /** * isNotificationEnabled * * @systemapi Hide this for inner system use. - * @since 7 */ function isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback): void; + + /** + * isNotificationEnabled + * + * @systemapi Hide this for inner system use. + */ function isNotificationEnabled(bundle: BundleOption): Promise; /** * isNotificationEnabled * * @systemapi Hide this for inner system use. - * @since 7 */ function isNotificationEnabled(callback: AsyncCallback): void; + + /** + * isNotificationEnabled + * + * @systemapi Hide this for inner system use. + */ function isNotificationEnabled(): Promise; /** * displayBadge * * @systemapi Hide this for inner system use. - * @since 7 */ function displayBadge(bundle: BundleOption, enable: boolean, callback: AsyncCallback): void; + + /** + * displayBadge + * + * @systemapi Hide this for inner system use. + */ function displayBadge(bundle: BundleOption, enable: boolean): Promise; /** * isBadgeDisplayed * * @systemapi Hide this for inner system use. - * @since 7 */ function isBadgeDisplayed(bundle: BundleOption, callback: AsyncCallback): void; + + /** + * isBadgeDisplayed + * + * @systemapi Hide this for inner system use. + */ function isBadgeDisplayed(bundle: BundleOption): Promise; /** * setSlotByBundle * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot, callback: AsyncCallback): void; + + /** + * setSlotByBundle + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function setSlotByBundle(bundle: BundleOption, slot: NotificationSlot): Promise; /** * getSlotsByBundle * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function getSlotsByBundle(bundle: BundleOption, callback: AsyncCallback>): void; + + /** + * getSlotsByBundle + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function getSlotsByBundle(bundle: BundleOption): Promise>; /** * getSlotNumByBundle * * @systemapi Hide this for inner system use. - * @since 7 */ function getSlotNumByBundle(bundle: BundleOption, callback: AsyncCallback): void; + + /** + * getSlotNumByBundle + * + * @systemapi Hide this for inner system use. + */ function getSlotNumByBundle(bundle: BundleOption): Promise; /** * remove * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function remove(bundle: BundleOption, notificationKey: NotificationKey, callback: AsyncCallback): void; + + /** + * remove + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function remove(bundle: BundleOption, notificationKey: NotificationKey): Promise; /** * remove * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function remove(hashCode: string, callback: AsyncCallback): void; + + /** + * remove + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function remove(hashCode: string): Promise; /** * removeAll * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function removeAll(bundle: BundleOption, callback: AsyncCallback): void; + + /** + * removeAll + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function removeAll(callback: AsyncCallback): void; + + /** + * removeAll + * + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ function removeAll(bundle?: BundleOption): Promise; /** @@ -322,31 +470,90 @@ declare namespace notification { * call this method. * * @systemapi Hide this for inner system use. - * @since 7 + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function getAllActiveNotifications(callback: AsyncCallback>): void; - function getAllActiveNotifications(): Promise>; /** - * Obtains the number of active notifications of the current application in the system. + * Obtains all active notifications in the current system. The caller must have system permissions to + * call this method. * - * @since 7 + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ + function getAllActiveNotifications(): Promise>; + + /** + * Obtains the number of all active notifications. */ function getActiveNotificationCount(callback: AsyncCallback): void; function getActiveNotificationCount(): Promise; /** - * Obtains active notifications of the current application in the system. - * - * @since 7 + * Obtains an array of active notifications. */ function getActiveNotifications(callback: AsyncCallback>): void; function getActiveNotifications(): Promise>; /** - * BundleOption + * Cancel the notification of a specified group for this application. * - * @since 7 + * @since 8 + */ + function cancelGroup(groupName: string, callback: AsyncCallback): void; + function cancelGroup(groupName: string): Promise; + + /** + * Delete the notification of a specified group for this application. + * + * @since 8 + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ + function removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback): void; + function removeGroupByBundle(bundle: BundleOption, groupName: string): Promise; + + /** + * Set the Do Not Disturb date. + * + * @since 8 + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ + function setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback): void; + function setDoNotDisturbDate(date: DoNotDisturbDate): Promise; + + /** + * Obtains the Do Not Disturb date. + * + * @since 8 + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ + function getDoNotDisturbDate(callback: AsyncCallback): void; + function getDoNotDisturbDate(): Promise; + + /** + * Obtains whether to support the Do Not Disturb mode. + * + * @since 8 + * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER + */ + function supportDoNotDisturbMode(callback: AsyncCallback): void; + function supportDoNotDisturbMode(): Promise; + + /** + * Obtains whether the template is supported by the system. + * + * @since 8 + * @param templateName Name of template to be Obtained + */ + function isSupportTemplate(templateName: string, callback: AsyncCallback): void; + function isSupportTemplate(templateName: string): Promise; + + /** + * Describes a BundleOption. */ export interface BundleOption { bundle: string; @@ -354,9 +561,7 @@ declare namespace notification { } /** - * NotificationKey - * - * @since 7 + * Describes a NotificationKey, which can be used to identify a notification. */ export interface NotificationKey { id: number; @@ -364,35 +569,161 @@ declare namespace notification { } /** - * DisturbMode + * The type of the Do Not Disturb. * + * @since 8 * @systemapi Hide this for inner system use. - * @since 7 */ - export enum DoNotDisturbMode { - ALLOW_UNKNOWN, + export enum DoNotDisturbType { + /** + * Non do not disturb type notification + */ + TYPE_NONE = 0, + + /** + * Execute do not disturb once in the set time period (only watch hours and minutes) + */ + TYPE_ONCE = 1, + + /** + * Execute do not disturb every day with a set time period (only watch hours and minutes) + */ + TYPE_DAILY = 2, + + /** + * Execute in the set time period (specify the time, month, day and hour) + */ + TYPE_CLEARLY = 3, + } + + /** + * Describes a DoNotDisturbDate instance. + * + * @systemapi Hide this for inner system use. + */ + export interface DoNotDisturbDate { + /** + * the type of the Do Not Disturb. + * + * @since 8 + */ + type: DoNotDisturbType; /** - * Indicates that all notifications are allowed to interrupt the user in Do Not Disturb mode. + * the start time of the Do Not Disturb. + * + * @since 8 */ - ALLOW_ALL, + begin: Date; + + /** + * the end time of the Do Not Disturb. + * + * @since 8 + */ + end: Date; + } + + /** + * Notification source type + * + * @since 8 + * @systemapi Hide this for inner system use. + */ + export enum SourceType { + /** + * General notification + */ + TYPE_NORMAL = 0x00000000, + + /** + * Continuous notification + */ + TYPE_CONTINUOUS = 0x00000001, + + /** + * Scheduled notification + */ + TYPE_TIMER = 0x00000002, + } + /** + * The type of the Do Not Disturb. + * + * @since 8 + * @systemapi Hide this for inner system use. + */ + export enum DoNotDisturbType { + /** + * Non do not disturb type notification + */ + TYPE_NONE = 0, + + /** + * Execute do not disturb once in the set time period (only watch hours and minutes) + */ + TYPE_ONCE = 1, + + /** + * Execute do not disturb every day with a set time period (only watch hours and minutes) + */ + TYPE_DAILY = 2, + + /** + * Execute in the set time period (specify the time, month, day and hour) + */ + TYPE_CLEARLY = 3, + } + + /** + * Describes a DoNotDisturbDate instance. + * + * @systemapi Hide this for inner system use. + */ + export interface DoNotDisturbDate { + /** + * the type of the Do Not Disturb. + * + * @since 8 + */ + type: DoNotDisturbType; + + /** + * the start time of the Do Not Disturb. + * + * @since 8 + */ + begin: Date; + + /** + * the end time of the Do Not Disturb. + * + * @since 8 + */ + end: Date; + } + + /** + * Notification source type + * + * @since 8 + * @systemapi Hide this for inner system use. + */ + export enum SourceType { /** - * Indicates that only notifications meeting the specified priority criteria are allowed to interrupt - * the user in Do Not Disturb mode. + * General notification */ - ALLOW_PRIORITY, + TYPE_NORMAL = 0x00000000, /** - * Indicates that no notifications are allowed to interrupt the user in Do Not Disturb mode. + * Continuous notification */ - ALLOW_NONE, + TYPE_CONTINUOUS = 0x00000001, /** - * Indicates that only notifications of the {@link NotificationRequest#CLASSIFICATION_ALARM} category - * are allowed to interrupt the user in Do Not Disturb mode. + * Scheduled notification */ - ALLOW_ALARMS + TYPE_TIMER = 0x00000002, } } diff --git a/interfaces/kits/js/@ohos.reminderAgent.d.ts b/interfaces/kits/js/@ohos.reminderAgent.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..96c26e2dce021bf44c655890cba66354e5538ab0 --- /dev/null +++ b/interfaces/kits/js/@ohos.reminderAgent.d.ts @@ -0,0 +1,295 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AsyncCallback } from './basic'; +import notification from './@ohos.notification'; +import { NotificationSlot } from './notification/notificationSlot'; + +/** + * Providers static methods for managing reminders, including publishing or canceling a reminder. + * adding or removing a notification slot, and obtaining or cancelling all reminders of the current application. + * + * @since 7 + * @sysCap Agent-Powered Reminder. + * @import reminderAgent from '@ohos.reminderAgent'; + */ +declare namespace reminderAgent { + /** + * Publishes a scheduled reminder. + * + * @since 7 + * @sysCap Publishes an agent-powered reminder. + * @permission ohos.permission.PUBLISH_AGENT_REMINDER + * @param reminderReq Indicates the reminder instance to publish. + * @param callback Indicates the callback function. + * @returns reminder id. + */ + function publishReminder(reminderReq: ReminderRequest, callback: AsyncCallback): void; + function publishReminder(reminderReq: ReminderRequest): Promise; + + /** + * Cancels a reminder. + * + * @since 7 + * @sysCap Cancels the reminder with the specified ID. + * @param reminderId Indicates the reminder id. + * @param callback Indicates the callback function. + */ + function cancelReminder(reminderId: number, callback: AsyncCallback): void; + function cancelReminder(reminderId: number): Promise; + + /** + * Obtains all the valid reminders of current application. + * + * @since 7 + * @sysCap Obtains all valid (not yet expired) remindeers set by the current application. + * @param callback Indicates the callback function. + */ + function getValidReminders(callback: AsyncCallback>): void; + function getValidReminders(): Promise>; + + /** + * Cancels all the reminders of current application. + * + * @since 7 + * @sysCap Cancels all the reminders set by the current application. + * @param callback Indicates the callback function. + */ + function cancelAllReminders(callback: AsyncCallback): void; + function cancelAllReminders(): Promise; + + /** + * Add notification slot. + * + * @since 7 + * @sysCap Adds a reminder notification slot. + * @param slot Indicates the slot. + * @param callback Indicates the callback function. + */ + function addNotificationSlot(slot: NotificationSlot, callback: AsyncCallback): void; + function addNotificationSlot(slot: NotificationSlot): Promise; + + /** + * Deletes a created notification slot based on the slot type. + * + * @since 7 + * @sysCap Removes a notification slot instance of a specified type. + * @param slotType Indicates the type of the slot. + * @param callback Indicates the callback function. + */ + function removeNotificationSlot(slotType: notification.SlotType, callback: AsyncCallback): void; + function removeNotificationSlot(slotType: notification.SlotType): Promise; + + /** + * Declares action button type. + * + * @since 7 + * @sysCap Define action button type. + */ + export enum ActionButtonType { + /** + * Button for closing the reminder. + * @since 7 + * @sysCap Agent-Powered reminder. + */ + ACTION_BUTTON_TYPE_CLOSE = 0, + + /** + * Button for snoozing the reminder. + * @since 7 + * @sysCap Agent-Powered reminder. + */ + ACTION_BUTTON_TYPE_SNOOZE = 1 + } + + /** + * Declares reminder type. + * + * @since 7 + * @sysCap Define reminder type. + */ + export enum ReminderType { + /** + * Countdown reminder. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + REMINDER_TYPE_TIMER = 0, + + /** + * Calendar reminder. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + REMINDER_TYPE_CALENDAR = 1, + + /** + * Alarm reminder. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + REMINDER_TYPE_ALARM = 2 + } + + /** + * Action button information. The button will show on displayed reminder. + * + * @since 7 + * @sysCap Define action button object. + */ + interface ActionButton { + /** + * Text on the button. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + title: string; + + /** + * Button type. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + type: ActionButtonType; + } + + /** + * Want agent information. + * It will switch to target ability when you click the displayed reminder. + * + * @since 7 + * @sysCap Define want agent object. + */ + interface WantAgent { + /** + * Name of the package redirected to when the reminder notification is clicked. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + pkgName: string; + + /** + * Name of the ability that is redirected to when the reminder notification is clicked. + * @since 7 + * @sysCap Agent-Powered Reminder. + */ + abilityName: string; + } + + /** + * Reminder Common information. + * + * @since 7 + * @sysCap Define reminder request object. + */ + interface ReminderRequest { + /** + * Type of the reminder. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + reminderType: ReminderType; + + /** + * Action button displayed on the reminder notification. + * (The parameter is optional. Up to two buttons are supported). + * @since 7 + * @sysCap Agent-Powered Reminder + */ + actionButton?: [ActionButton?, ActionButton?]; + + /** + * Information about the ability that is redirected to when the notification is clicked. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + wantAgent?: WantAgent; + + /** + * Reminder title. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + title?: string; + + /** + * Reminder content. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + content?: string; + + /** + * Content to be displayed when the reminder is snoozing. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + expiredContent?: string; + + /** + * notification id. If there are reminders with the same ID, the later one will overwrite the earlier one. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + notificationId?: number; + + /** + * Type of the slot used by the reminder. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + slotType?: notification.SlotType; + } + + /** + * Alarm reminder information. + * + * @since 7 + * @sysCap Define alarm reminder object. + */ + interface ReminderRequestAlarm extends ReminderRequest { + /** + * Hour portion of the reminder time. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + hour: number; + + /** + * minute portion of the remidner time. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + minute: number; + + /** + * Days of a week when the reminder repeates. + * @since 7 + * @sysCap Agent-Powered Reminder + */ + daysOfWeek?: Array; + } + + /** + * CountDown reminder information. + * + * @since 7 + * @sysCap Define count down timer reminder object. + */ + interface ReminderRequestTimer extends ReminderRequest { + triggerTimeInSeconds: number; + } +} +export default reminderAgent; diff --git a/interfaces/kits/js/@ohos.wantAgent.d.ts b/interfaces/kits/js/@ohos.wantAgent.d.ts index f7eab8a04f132e0681e147a410e316dde067d16f..e5de044ce78a3d2579ab81dbd9f5dbca33ee1dab 100644 --- a/interfaces/kits/js/@ohos.wantAgent.d.ts +++ b/interfaces/kits/js/@ohos.wantAgent.d.ts @@ -25,26 +25,24 @@ import { TriggerInfo } from './wantAgent/triggerInfo'; * @name wantAgent * @since 7 * @devices phone, tablet, tv, wearable, car - * @import wantAgent from '@ohos.wantAgent'; + * @import import wantAgent from '@ohos.wantAgent'; * @permission N/A */ declare namespace wantAgent { /** - * Obtains the bundle name of an {@link WantAgent}. + * Obtains the bundle name of a WantAgent. * - * @param agent Indicates the {@link WantAgent} whose bundle name is to be obtained. + * @param WantAgent whose bundle name to obtain. * @return Returns the bundle name of the {@link WantAgent} if any. - * @since 7 */ function getBundleName(agent: WantAgent, callback: AsyncCallback): void; function getBundleName(agent: WantAgent): Promise; /** - * Obtains the bundle name of an {@link WantAgent}. + * Obtains the UID of a WantAgent. * - * @param agent Indicates the {@link WantAgent} whose UID is to be obtained. + * @param WantAgent whose UID to obtain. * @return Returns the UID of the {@link WantAgent} if any; returns {@code -1} otherwise. - * @since 7 */ function getUid(agent: WantAgent, callback: AsyncCallback): void; function getUid(agent: WantAgent): Promise; @@ -55,98 +53,152 @@ declare namespace wantAgent { * @param agent Indicates the {@link WantAgent} whose UID is to be obtained. * @return Returns the {@link Want} of the {@link WantAgent}. * @systemapi Hide this for inner system use. - * @since 7 */ function getWant(agent: WantAgent, callback: AsyncCallback): void; + + /** + * Obtains the {@link Want} of an {@link WantAgent}. + * + * @param agent Indicates the {@link WantAgent} whose UID is to be obtained. + * @return Returns the {@link Want} of the {@link WantAgent}. + * @systemapi Hide this for inner system use. + */ function getWant(agent: WantAgent): Promise; /** - * Cancels an {@link WantAgent}. Only the application that creates the {@link IntentAgent} can cancel it. + * Cancels a WantAgent. Only the application that creates the WantAgent can cancel it. * - * @param agent Indicates the {@link WantAgent} to cancel. - * @since 7 + * @param WantAgent to cancel. */ function cancel(agent: WantAgent, callback: AsyncCallback): void; function cancel(agent: WantAgent): Promise; /** - * Obtains the bundle name of an {@link WantAgent}. + * Triggers a WantAgent. * - * @param agent Indicates the {@link WantAgent} whose bundle name is to be obtained. - * @param triggerInfo Indicates the {@link TriggerInfo} object that contains triggering parameters. + * @param WantAgent to trigger. + * @param Trigger parameters. * @param callback Indicates the callback method to be called after the {@link WantAgent} is triggered. - * @since 7 */ function trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback): void; /** - * Checks whether two {@link WantAgent} objects are the same. + * Checks whether two WantAgent objects are equal. * - * @param agent Indicates one of the {@link WantAgent} object to compare. - * @param otherAgent Indicates the other {@link WantAgent} object to compare. + * @param WantAgent to compare. + * @param WantAgent to compare. * @return Returns {@code true} If the two objects are the same; returns {@code false} otherwise. - * @since 7 */ function equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback): void; function equal(agent: WantAgent, otherAgent: WantAgent): Promise; /** - * Obtains an {@link WantAgent} object. + * Obtains a WantAgent object. * - * @param info Indicates the {@link WantAgentInfo} object that contains parameters of the - * {@link WantAgent} object to create. + * @param Information about the WantAgent object to obtain. * @return Returns the created {@link WantAgent} object. - * @since 7 */ function getWantAgent(info: WantAgentInfo, callback: AsyncCallback): void; function getWantAgent(info: WantAgentInfo): Promise; /** - * Enumerates flags for using an {@link WantAgent}. - * - * @since 7 + * Enumerates flags for using a WantAgent. */ export enum WantAgentFlags { + /** + * Indicates that the WantAgent can be used only once. + * This flag is valid only when OperationType is set to START_ABILITY, START_SERVICE, or SEND_COMMON_EVENT. + */ ONE_TIME_FLAG = 0, + + /** + * Indicates that null is returned if the WantAgent does not exist. + * This flag is valid only when OperationType is set to START_ABILITY, START_SERVICE, or SEND_COMMON_EVENT. + */ NO_BUILD_FLAG, + + /** + * Indicates that the existing WantAgent should be canceled before a new object is generated. + * This flag is valid only when OperationType is set to START_ABILITY, START_SERVICE, or SEND_COMMON_EVENT. + */ CANCEL_PRESENT_FLAG, + + /** + * Indicates that the system only replaces the extra data of the existing WantAgent with that of the new object. + * This flag is valid only when OperationType is set to START_ABILITY, START_SERVICE, or SEND_COMMON_EVENT. + */ UPDATE_PRESENT_FLAG, - CONSTANT_FLAG, - REPLACE_ELEMENT, - REPLACE_ACTION, - REPLACE_URI, - REPLACE_ENTITIES, - REPLACE_BUNDLE + + /** + * Indicates that the created WantAgent should be immutable. + */ + CONSTANT_FLAG } /** - * Identifies the operation for using an {@link WantAgent}, such as starting an ability or sending a common event. - * - * @since 7 + * Identifies the operation for using a WantAgent, such as starting an ability or sending a common event. */ export enum OperationType { + /** + * Unknown operation. + */ UNKNOWN_TYPE = 0, + + /** + * Starts an ability with a UI. + */ START_ABILITY, + + /** + * Starts multiple abilities with a UI. + */ START_ABILITIES, + + /** + * Starts an ability without a UI. + */ START_SERVICE, + + /** + * Sends a common event. + */ SEND_COMMON_EVENT } /** - * A callback for the {@link trigger()} method. After the method execution is complete, - * the callback process will start. - * - * @since 7 + * Describes the data returned by after wantAgent.trigger is called. */ export interface CompleteData { + /** + * Triggered WantAgent. + */ info: WantAgent; + + /** + * Existing Want that is triggered. + */ want: Want; + + /** + * Request code used to trigger the WantAgent. + */ finalCode: number; + + /** + * Final data collected by the common event. + */ finalData: string; + + /** + * Extra data collected by the common event. + */ extraInfo?: {[key: string]: any}; } } +/** + * WantAgent object. + */ export type WantAgent = object; export default wantAgent; \ No newline at end of file diff --git a/interfaces/kits/js/notification/notificationActionButton.ts b/interfaces/kits/js/notification/notificationActionButton.d.ts similarity index 70% rename from interfaces/kits/js/notification/notificationActionButton.ts rename to interfaces/kits/js/notification/notificationActionButton.d.ts index 140215050e83fcd221ae81a436d28b747f233353..9428cc4f0d34c8bed47bc6c6b6e034e981f6fb1d 100644 --- a/interfaces/kits/js/notification/notificationActionButton.ts +++ b/interfaces/kits/js/notification/notificationActionButton.d.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http?://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -13,18 +13,37 @@ * limitations under the License. */ +import { NotificationUserInput } from './notificationUserInput'; import { WantAgent } from '../@ohos.wantAgent'; /** - * The action button of notification + * Describes an action button displayed in a notification. * @name NotificationActionButton * @since 7 - * @sysCap SystemCapability.Notification.ANS * @devices phone, tablet, tv, wearable, car * @permission N/A + * @sysCap SystemCapability.Notification.ANS */ export interface NotificationActionButton { + /** + * Button title. + */ title: string; + + /** + * WantAgent of the button. + */ wantAgent: WantAgent; + + /** + * Extra information of the button. + */ extras?: {[key: string]: any}; + + /** + * User input + * + * @since 8 + */ + userInput?: NotificationUserInput; } diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts index 7624cd304a6e7b08d1852f62296c449a32597e3e..037300c24bfc8c1de315cb4dab649be24786488d 100644 --- a/interfaces/kits/js/notification/notificationContent.d.ts +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -14,10 +14,11 @@ */ import notification from '../@ohos.notification'; -import image from './@ohos.multimedia.image'; +import image from '../@ohos.multimedia.image'; +import { MessageUser } from './notificationMessageUser'; /** - * Constructs basic notifications. + * Describes a normal text notification. * * @name NotificationBasicContent * @since 7 @@ -26,13 +27,24 @@ import image from './@ohos.multimedia.image'; * @permission N/A */ export interface NotificationBasicContent { + /** + * Title of the normal text notification. + */ title: string; + + /** + * Content of the normal text notification. + */ text: string; + + /** + * Additional information of the normal text notification. + */ additionalText?: string; } /** - * Constructs notifications that include long text. The long text contains a maximum of 1024 characters. + * Describes a long text notification. * * @name NotificationLongTextContent * @since 7 @@ -41,13 +53,24 @@ export interface NotificationBasicContent { * @permission N/A */ export interface NotificationLongTextContent extends NotificationBasicContent { + /** + * Long text content of the notification. + */ longText: string; + + /** + * Brief text of the long text notification. + */ briefText: string; + + /** + * Title that will be displayed for the long text notification when it is expanded. + */ expandedTitle: string; } /** - * Constructs a notification that includes multiple lines of text. + * Describes a multi-line text notification. * * @name NotificationMultiLineContent * @since 7 @@ -56,13 +79,24 @@ export interface NotificationLongTextContent extends NotificationBasicContent { * @permission N/A */ export interface NotificationMultiLineContent extends NotificationBasicContent { + /** + * Brief text of the multi-line text notification. + */ briefText: string; + + /** + * Brief text of the multi-line text notification. + */ longTitle: string; + + /** + * Multi-line content of the multi-line text notification. + */ lines: Array; } /** - * Constructs a notification that includes a picture. + * Describes a picture-attached notification. * * @name NotificationPictureContent * @since 7 @@ -71,13 +105,86 @@ export interface NotificationMultiLineContent extends NotificationBasicContent { * @permission N/A */ export interface NotificationPictureContent extends NotificationBasicContent { + /** + * Multi-line content of the multi-line text notification. + */ briefText: string; + + /** + * Title that will be displayed for the picture-attached notification when it is expanded. + */ expandedTitle: string; + + /** + * Picture to be included in a notification. + */ picture: image.PixelMap; } /** - * Constructs a notification. + * Constructs a conversation-like notification that includes message communication among multiple users. + * + * @since 8 + */ +export interface NotificationConversationalContent extends NotificationBasicContent { + /** + * Indicates the {@code MessageUser} who sends all objects in this conversation-like notification. + * This parameter cannot be null. + */ + user: MessageUser; + + /** + * Obtains all messages included in this conversation-like notification. + */ + messages: Array; + + /** + * Checks whether this notification represents a group conversation. + */ + conversationGroup?: boolean; + + /** + * Obtains the title to be displayed for the conversation. + */ + conversationTitle?: string; +} + +/** + * Provides methods for defining a conversational message that is used in notifications created with + * {@link NotificationConversationalContent}. Each message contains the message content, timestamp, and + * sender; and the message content and sender information will be displayed in the notification bar. + * + * @since 8 + */ +export interface ConversationalMessage { + /** + * Obtains the text to be displayed as the content of this message. + */ + text: string; + + /** + * Obtains the time when this message arrived. + */ + timestamp: number; + + /** + * Obtains the sender of this message. + */ + sender: MessageUser; + + /** + * Obtains the MIME type of this message. + */ + mimeType?: string; + + /** + * Obtains the URI of this message. + */ + uri?: string; +} + +/** + * Describes notification types. * * @name NotificationContent * @since 7 @@ -86,9 +193,35 @@ export interface NotificationPictureContent extends NotificationBasicContent { * @permission N/A */ export interface NotificationContent { + /** + * Notification content type. + */ contentType: notification.ContentType; + + /** + * Normal text notification. + */ normal?: NotificationBasicContent; + + /** + * Long text notification. + */ longText?: NotificationLongTextContent; + + /** + * Multi-line text notification. + */ multiLine?: NotificationMultiLineContent; + + /** + * Picture-attached notification. + */ picture?: NotificationPictureContent; + + /** + * Constructs a conversation-like notification that includes message communication among multiple users. + * + * @since 8 + */ + conversation?: NotificationConversationalContent; } diff --git a/interfaces/kits/js/notification/notificationFlags.ts b/interfaces/kits/js/notification/notificationFlags.ts new file mode 100644 index 0000000000000000000000000000000000000000..58c4a68314afc35be19aed5e06956446a8bd9c8e --- /dev/null +++ b/interfaces/kits/js/notification/notificationFlags.ts @@ -0,0 +1,35 @@ +/* + * 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. + */ + +/** + * Describes a NotificationFlags instance. + * + * @name NotificationFlags + * @since 8 + * @devices phone, tablet, tv, wearable, car + * @permission N/A + * @sysCap SystemCapability.Notification.ANS + */ + export interface NotificationFlags { + /** + * Whether to enable sound reminder. + */ + readonly soundEnabled?: boolean; + + /** + * Whether to enable vibration reminder. + */ + readonly vibrationEnabled?: boolean; +} diff --git a/interfaces/kits/js/notification/notificationMessageUser.d.ts b/interfaces/kits/js/notification/notificationMessageUser.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..40d01bde11edcb54e6bcbc6719089e6a37818c71 --- /dev/null +++ b/interfaces/kits/js/notification/notificationMessageUser.d.ts @@ -0,0 +1,57 @@ +/* + * 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 image from '../@ohos.multimedia.image'; + +/** + * Represents a message sender that can be used by {@link NotificationRequest}, + * + * @name MessageUser + * @since 8 + * @devices phone, tablet, tv, wearable, car + * @permission N/A + * @sysCap SystemCapability.Notification.ANS + */ +export interface MessageUser { + /** + * Obtains the name of this {@code MessageUser}. + */ + name: string; + + /** + * Obtains the key of this {@code MessageUser}. + */ + key: string; + + /** + * Obtains the URI of this {@code MessageUser}. + */ + uri: string; + + /** + * Checks whether this {@code MessageUser} is important. + */ + isMachine: boolean; + + /** + * Checks whether this {@code MessageUser} is a machine. + */ + isUserImportant: boolean; + + /** + * Obtains the icon of this {@code MessageUser}. + */ + icon?: image.PixelMap; +} diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index f3e2657fe0b4ed4e0a8d7162e568f16c6b2c0c46..971ecb0c744167e6b9bd77deb0acd6b178627c7b 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -4,7 +4,7 @@ * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * - * http?://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, @@ -18,9 +18,11 @@ import image from '../@ohos.multimedia.image'; import { WantAgent } from '../@ohos.wantAgent'; import { NotificationContent } from './notificationContent'; import { NotificationActionButton } from './notificationActionButton'; +import { NotificationTemplate } from './notificationTemplate'; +import { NotificationFlags } from './notificationFlags'; /** - * Carries notifications. + * Defines a NotificationRequest instance. * * @name NotificationRequest * @since 7 @@ -29,44 +31,178 @@ import { NotificationActionButton } from './notificationActionButton'; * @permission N/A */ export interface NotificationRequest { + /** + * Notification content. + */ content: NotificationContent; + + /** + * Notification ID. + */ id?: number; + + /** + * Notification slot type. + */ slotType?: notification.SlotType; + + /** + * Whether the notification is an ongoing notification. + */ isOngoing?: boolean; + + /** + * Whether the notification can be removed. + */ isUnremovable?: boolean; + + /** + * Time when the notification is sent. + */ deliveryTime?: number; + + /** + * Whether the notification is automatically cleared. + */ tapDismissed?: boolean; + + /** + * Time when the notification is automatically cleared. + */ autoDeletedTime?: number; + + /** + * WantAgent instance to which the notification will be redirected after being clicked. + */ wantAgent?: WantAgent; + + /** + * Extended parameter. + */ extraInfo?: {[key: string]: any}; + + /** + * Background color of the notification. + */ color?: number; + + /** + * Whether the notification background color can be enabled. + */ colorEnabled?: boolean; + + /** + * Whether the notification triggers an alert only once. + */ isAlertOnce?: boolean; + + /** + * Whether to display the stopwatch. + */ isStopwatch?: boolean; + + /** + * Whether to display the countdown time. + */ isCountDown?: boolean; + + /** + * Whether the notification is displayed as a floating icon. + */ isFloatingIcon?: boolean; + + /** + * Notification label. + */ label?: string; + + /** + * Notification badge type. + */ badgeIconStyle?: number; + + /** + * Whether to display the time when the notification is delivered. + */ showDeliveryTime?: boolean; + + /** + * Buttons in the notification. Up to two buttons are allowed. + */ actionButtons?: Array; + + /** + * Small notification icon. + */ smallIcon?: image.PixelMap; + + /** + * Large notification icon. + */ largeIcon?: image.PixelMap; + + /** + * The group information for this notification. + * + * @since 8 + */ + groupName?: string; + + /** + * Read-only name of the package for which a notification is created. + */ readonly creatorBundleName?: string; + + /** + * Read-only UID of the notification creator. + */ readonly creatorUid?: number; + + /** + * Read-only PID of the notification creator. + */ readonly creatorPid?: number; /** * Obtains the classification of this notification. * * @systemapi Hide this for inner system use. - * @since 7 */ classification?: string; /** * Obtains the unique hash code of a notification in the current application. - * - * @since 7 */ readonly hashCode?: string; + + /** + * Whether the notification can be remove. + * + * @default true + * @since 8 + * @systemapi Hide this for inner system use. + */ + readonly isRemoveAllowed?: boolean; + + /** + * Notification source. enum SourceType + * + * @since 8 + * @systemapi Hide this for inner system use. + */ + readonly source?: number; + + /** + * Obtains the template of this notification. + * + * @since 8 + */ + template?: NotificationTemplate; + + /** + * Obtains the set of identifiers for the notification. + * + * @since 8 + */ + readonly notificationFlags?: NotificationFlags; } diff --git a/interfaces/kits/js/notification/notificationSlot.d.ts b/interfaces/kits/js/notification/notificationSlot.d.ts index 56f987e69eecab5a125c9ba077f6c5d27153ba18..82ff360f74f57ce33f6749c346ba2e29f15019eb 100644 --- a/interfaces/kits/js/notification/notificationSlot.d.ts +++ b/interfaces/kits/js/notification/notificationSlot.d.ts @@ -16,89 +16,67 @@ import notification from '../@ohos.notification'; /** - * A constructor used to initialize the type, desc, and level of a {@code NotificationSlot} object. + * Describes a NotificationSlot instance. * * @name NotificationSlot * @since 7 - * @sysCap SystemCapability.Notification.ANS * @devices phone, tablet, tv, wearable, car * @permission N/A + * @sysCap SystemCapability.Notification.ANS */ export interface NotificationSlot { /** * Obtains the type of a notification slot. - * - * @since 7 */ type: notification.SlotType; /** * Obtains the level of a notification slot - * - * @since 7 */ level?: notification.SlotLevel; /** * Obtains the description of a notification slot. - * - * @since 7 */ desc?: string; /** * Obtains the application icon badge status of a notification slot. - * - * @since 7 */ badgeFlag?: boolean; /** * Obtains whether DND mode is bypassed for a notification slot. - * - * @since 7 */ bypassDnd?: boolean; /** * Whether and how to display notifications on the lock screen. - * - * @since 7 */ lockscreenVisibility?: number; /** * Obtains the vibration status of the notification slot. - * - * @since 7 */ vibrationEnabled?: boolean; /** * Obtains the prompt tone of the notification slot. - * - * @since 7 */ sound?: string; /** * Obtains whether the notification light is enabled in a notification slot. - * - * @since 7 */ lightEnabled?: boolean; /** * Obtains the color of the notification light in a notification slot. - * - * @since 7 */ lightColor?: number; /** * Obtains the vibration style of notifications in this notification slot. - * - * @since 7 */ vibrationValues?: Array; } diff --git a/interfaces/kits/js/notification/notificationSubscribeInfo.ts b/interfaces/kits/js/notification/notificationSubscribeInfo.d.ts similarity index 100% rename from interfaces/kits/js/notification/notificationSubscribeInfo.ts rename to interfaces/kits/js/notification/notificationSubscribeInfo.d.ts diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts index a659a9d0f17b31028603b3228d257116df9a78ba..3ae878775d5b2ad008e0fe566a4aee598f845a96 100644 --- a/interfaces/kits/js/notification/notificationSubscriber.d.ts +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -35,7 +35,13 @@ export interface NotificationSubscriber { onConnect?:() => void; onDisconnect?:() => void; onDestroy?:() => void; - onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void; + + /** + * Callback when the Do Not Disturb setting changed. + * + * @since 8 + */ + onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void; } /** diff --git a/interfaces/kits/js/notification/notificationTemplate.d.ts b/interfaces/kits/js/notification/notificationTemplate.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d131ed5cb2afa784543246f7ed70d20651717b60 --- /dev/null +++ b/interfaces/kits/js/notification/notificationTemplate.d.ts @@ -0,0 +1,35 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Describes a NotificationTemplate instance. + * + * @name NotificationTemplate + * @since 8 + * @devices phone, tablet, tv, wearable, car + * @permission N/A + * @sysCap SystemCapability.Notification.ANS + */ +export interface NotificationTemplate { + /** + * Obtains the type of a notification template. + */ + name: string; + + /** + * Obtains the data of a notification template. + */ + data: {[key: string]: Object}; +} diff --git a/interfaces/kits/js/notification/notificationUserInput.d.ts b/interfaces/kits/js/notification/notificationUserInput.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..389d1c43c713fbf53a07d47a753463212fae7e1b --- /dev/null +++ b/interfaces/kits/js/notification/notificationUserInput.d.ts @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Describes a NotificationUserInput instance. + * + * @name NotificationUserInput + * @since 8 + * @devices phone, tablet, tv, wearable, car + * @permission N/A + * @sysCap SystemCapability.Notification.ANS + */ +export interface NotificationUserInput { + /** + * Obtains the key used to identify this input when the input is collected from the user. + */ + inputKey: string; + + /** + * Obtains the tag to be displayed to the user when collecting this input from the user. + */ + tag: string; + + /** + * Obtains the options provided to users to satisfy user input needs. All options are displayed in a single line. + */ + options: Array; + + /** + * Obtains whether users can input values of the given MIME type. + */ + permitMimeTypes?: Array; + + /** + * Obtains the edit type of the options provided by this {@code NotificationUserInput} object. + */ + editType?: number; + + /** + * Obtains additional data to this NotificationUserInput. + */ + additionalData?: {[key: string]: Object}; +} diff --git a/interfaces/kits/js/wantAgent/triggerInfo.d.ts b/interfaces/kits/js/wantAgent/triggerInfo.d.ts index 20dfdeab1fc8bd7d13e886209198ea49f4e91f14..8cd951dce9dd5e01050781527b93b30a26b1c32f 100644 --- a/interfaces/kits/js/wantAgent/triggerInfo.d.ts +++ b/interfaces/kits/js/wantAgent/triggerInfo.d.ts @@ -16,7 +16,7 @@ import { Want } from '../ability/want'; /** - * the info when object of WantAgent trigger + * Provides the information required for triggering a WantAgent. * * @name TriggerInfo * @since 7 @@ -24,8 +24,30 @@ import { Want } from '../ability/want'; * @permission N/A */ export interface TriggerInfo { + /** + * Result code. + */ code: number; + + /** + * Extra Want. + * If flags in WantAgentInfo contain CONSTANT_FLAG, this parameter is invalid. + * If flags contain REPLACE_ELEMENT, REPLACE_ACTION, REPLACE_URI, REPLACE_ENTITIES, and REPLACE_BUNDLE, + * the element, action, uri, entities, and bundleName attributes of the Want specified in this parameter + * will be used to replace the corresponding attributes in the original Want, respectively. + * If this parameter is null, the original Want remains unchanged. + */ want?: Want; + + /** + * Permission required for a WantAgent recipient. + * This parameter is valid only when the WantAgent is triggered to send common events. + * If permission is null, no permission is required on the recipient. + */ permission?: string; + + /** + * Custom extra data you want to add for triggering a WantAgent. + */ extraInfo?: {[key: string]: any}; } \ No newline at end of file diff --git a/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts index d4d1c8705268dabffb6e72240f02633426371da3..f33531d327fef0445af7e2609cd3fb924ded1971 100644 --- a/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts +++ b/interfaces/kits/js/wantAgent/wantAgentInfo.d.ts @@ -17,7 +17,7 @@ import { Want } from '../ability/want'; import wantAgent from '../@ohos.wantAgent' /** - * the info of WantAgent + * Provides the information required for triggering a WantAgent. * * @name WantAgentInfo * @since 7 @@ -25,9 +25,29 @@ import wantAgent from '../@ohos.wantAgent' * @permission N/A */ export interface WantAgentInfo { + /** + * An array of all Wants for starting abilities or sending common events. Only Wants can be displayed. + */ wants: Array; + + /** + * Type of the action specified in a Want. + */ operationType: wantAgent.OperationType; + + /** + * Request code defined by the user. + */ requestCode: number; + + /** + * An array of flags for using the WantAgent. + */ wantAgentFlags?: Array; + + /** + * Extra information about how the Want starts an ability. + * If there is no extra information to set, this constant can be left empty. + */ extraInfo?: {[key: string]: any}; } \ No newline at end of file diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn old mode 100755 new mode 100644 index 66da3426a486297d57cb9acd3d81ee3cc83b3d9a..d13d88323e3cdd2e2ae1aac689003dd5105bb4a6 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -35,21 +35,23 @@ ohos_shared_library("notification") { include_dirs = [ "//foundation/aafwk/standard/frameworks/kits/ability/native/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", - "//foundation/ace/napi/interfaces/kits/napi", "//foundation/multimedia/image_standard/interfaces/kits/js/common/include/", "include", "//third_party/node/src", "//third_party/libuv/include", + "//third_party/json/single_include", "//third_party/jsoncpp/include", ] configs = [ ":native_module_config" ] sources = [ + "src/ans_template.cpp", "src/cancel.cpp", "src/common.cpp", "src/constant.cpp", "src/display_badge.cpp", + "src/distributed.cpp", "src/disturb_mode.cpp", "src/enable_notification.cpp", "src/get_active.cpp", @@ -61,18 +63,11 @@ ohos_shared_library("notification") { "src/unsubscribe.cpp", ] - ldflags = [ "-Wl,-rpath=/system/lib/module/multimedia/" ] - deps = [ "${frameworks_path}/ans/core:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", - "//foundation/ace/napi:ace_napi", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/multimedia/image_standard/interfaces/innerkits:image", "//third_party/jsoncpp:jsoncpp", "//third_party/libuv:uv_static", @@ -80,9 +75,14 @@ ohos_shared_library("notification") { ] external_deps = [ - "appexecfwk_standard:appexecfwk_base", + "ability_runtime:abilitykit_native", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "napi:ace_napi", ] relative_install_dir = "module" diff --git a/services/ans/include/disturb_filter.h b/interfaces/kits/napi/ans/include/ans_template.h similarity index 53% rename from services/ans/include/disturb_filter.h rename to interfaces/kits/napi/ans/include/ans_template.h index 7ced699c5dc4e37b7bbd775a2dd0eadf9ef98744..2919b62332f327cbfe90a89c80924f7c0ed1b348 100644 --- a/services/ans/include/disturb_filter.h +++ b/interfaces/kits/napi/ans/include/ans_template.h @@ -13,26 +13,17 @@ * limitations under the License. */ -#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H -#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H -#include "notification_filter.h" +#include "common.h" namespace OHOS { -namespace Notification { +namespace NotificationNapi { +using namespace OHOS::Notification; -class DisturbFilter : public INotificationFilter { -public: - DisturbFilter(){}; - ~DisturbFilter(){}; - - void OnStart() override; - void OnStop() override; - - ErrCode OnPublish(const std::shared_ptr &record) override; -}; - -} // namespace Notification +napi_value IsSupportTemplate(napi_env env, napi_callback_info info); +} // namespace NotificationNapi } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/cancel.h b/interfaces/kits/napi/ans/include/cancel.h index 6d41052f8af2140bf54bd577c1f265e61406f096..4cdc87e7953f2396d8cf7d7e69c59f7b8d0ac93e 100644 --- a/interfaces/kits/napi/ans/include/cancel.h +++ b/interfaces/kits/napi/ans/include/cancel.h @@ -24,7 +24,7 @@ using namespace OHOS::Notification; napi_value Cancel(napi_env env, napi_callback_info info); napi_value CancelAll(napi_env env, napi_callback_info info); - +napi_value CancelGroup(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index ace3fefc313e264d2d6b7f4a59d386602b4de402..ba4cd1aadaee35e5170f873578c06b42e05a6729 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -28,17 +28,19 @@ const std::int32_t STR_MAX_SIZE = 64; const std::int32_t LONG_STR_MAX_SIZE = 1024; const int NO_ERROR = 0; const int ERROR = -1; +const int PARAM0 = 0; +const int PARAM1 = 1; +const int PARAM2 = 2; -enum ContentType { +enum class ContentType { NOTIFICATION_CONTENT_BASIC_TEXT, NOTIFICATION_CONTENT_LONG_TEXT, NOTIFICATION_CONTENT_PICTURE, NOTIFICATION_CONTENT_CONVERSATION, - NOTIFICATION_CONTENT_MULTILINE, - NOTIFICATION_CONTENT_MEDIA + NOTIFICATION_CONTENT_MULTILINE }; -enum SlotType { +enum class SlotType { UNKNOWN_TYPE = 0, SOCIAL_COMMUNICATION = 1, SERVICE_INFORMATION = 2, @@ -46,7 +48,7 @@ enum SlotType { OTHER_TYPES = 0xFFFF, }; -enum SlotLevel { +enum class SlotLevel { LEVEL_NONE = 0, LEVEL_MIN = 1, LEVEL_LOW = 2, @@ -54,7 +56,7 @@ enum SlotLevel { LEVEL_HIGH = 4, }; -enum NotificationReason { +enum class NotificationReason { CLICK_REASON_DELETE, CANCEL_REASON_DELETE, CANCEL_ALL_REASON_DELETE, @@ -67,7 +69,7 @@ enum NotificationReason { APP_CANCEL_REASON_OTHER }; -enum SemanticActionButton { +enum class SemanticActionButton { NONE_ACTION_BUTTON, REPLY_ACTION_BUTTON, READ_ACTION_BUTTON, @@ -81,11 +83,42 @@ enum SemanticActionButton { CALL_ACTION_BUTTON }; -enum InputsSource { FREE_FORM_INPUT, OPTION }; +enum class InputsSource { + FREE_FORM_INPUT, + OPTION +}; -enum DisturbMode { ALLOW_UNKNOWN, ALLOW_ALL, ALLOW_PRIORITY, ALLOW_NONE, ALLOW_ALARMS }; +enum class DisturbMode { + ALLOW_UNKNOWN, + ALLOW_ALL, + ALLOW_PRIORITY, + ALLOW_NONE, + ALLOW_ALARMS +}; -enum InputEditType { EDIT_AUTO, EDIT_DISABLED, EDIT_ENABLED }; +enum class InputEditType { + EDIT_AUTO, + EDIT_DISABLED, + EDIT_ENABLED +}; + +enum class DoNotDisturbType { + TYPE_NONE, TYPE_ONCE, + TYPE_DAILY, TYPE_CLEARLY +}; + +enum class SourceType { + TYPE_NORMAL = 0x00000000, + TYPE_CONTINUOUS = 0x00000001, + TYPE_TIMER = 0x00000002 +}; + +enum class DeviceRemindType { + IDLE_DONOT_REMIND, + IDLE_REMIND, + ACTIVE_DONOT_REMIND, + ACTIVE_REMIND +}; struct NotificationSubscribeInfo { std::vector bundleNames; @@ -93,14 +126,9 @@ struct NotificationSubscribeInfo { bool hasSubscribeInfo = false; }; -struct BundleOption { - std::string bundle{}; - int uid{}; -}; - struct NotificationKey { - int id{}; - std::string label{}; + int id {}; + std::string label {}; }; struct CallbackPromiseInfo { @@ -116,7 +144,7 @@ class Common { ~Common(); public: - static napi_value NapiGetboolean(napi_env env, const bool &isValue); + static napi_value NapiGetBoolean(napi_env env, const bool &isValue); static napi_value NapiGetNull(napi_env env); @@ -132,15 +160,36 @@ public: static void SetCallback( const napi_env &env, const napi_ref &callbackIn, const int &errorCode, const napi_value &result); - static void SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result); + static void SetCallback( + const napi_env &env, const napi_ref &callbackIn, const napi_value &result); + + static void SetPromise( + const napi_env &env, const napi_deferred &deferred, const int &errorCode, const napi_value &result); static napi_value JSParaError(const napi_env &env, const napi_ref &callback); + static napi_value ParseParaOnlyCallback(const napi_env &env, const napi_callback_info &info, napi_ref &callback); + static napi_value SetNotification( - const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result); + const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result); static napi_value SetNotificationRequest( - const napi_env &env, OHOS::Notification::NotificationRequest *request, napi_value &result); + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByString( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByNumber( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByBool( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByWantAgent( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByPixelMap( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + static napi_value SetNotificationRequestByCustom( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result); + + static napi_value SetNotificationByDistributedOptions( + const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result); static napi_value SetNotificationSortingMap( const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result); @@ -152,35 +201,90 @@ public: static napi_value SetNotificationContent( const napi_env &env, const std::shared_ptr &content, napi_value &result); - + static napi_value SetNotificationContentDetailed(const napi_env &env, const ContentType &type, + const std::shared_ptr &content, napi_value &result); static napi_value SetNotificationBasicContent( - const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); - + const napi_env &env, const NotificationBasicContent *basicContent, napi_value &result); static napi_value SetNotificationLongTextContent( - const napi_env &env, OHOS::Notification::NotificationLongTextContent *longTextContent, napi_value &result); - + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); static napi_value SetNotificationPictureContent( - const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result); - + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); static napi_value SetNotificationConversationalContent(const napi_env &env, - OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &result); - + NotificationBasicContent *basicContent, napi_value &result); static napi_value SetNotificationMultiLineContent( - const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result); + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result); static napi_value SetMessageUser(const napi_env &env, const MessageUser &messageUser, napi_value &result); + static napi_value SetConversationalMessages(const napi_env &env, + const OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &arr); + static napi_value SetConversationalMessage(const napi_env &env, const std::shared_ptr &conversationalMessage, napi_value &result); static napi_value SetNotificationActionButton( const napi_env &env, const std::shared_ptr &actionButton, napi_value &result); + static napi_value SetNotificationActionButtonByExtras( + const napi_env &env, const std::shared_ptr &actionButton, napi_value &result); + static napi_value SetNotificationActionButtonByUserInput( + const napi_env &env, const std::shared_ptr &userInput, napi_value &result); + + static napi_value SetDoNotDisturbDate( + const napi_env &env, const NotificationDoNotDisturbDate &date, napi_value &result); static napi_value GetNotificationSubscriberInfo( const napi_env &env, const napi_value &value, NotificationSubscribeInfo &result); static napi_value GetNotificationRequest( const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationRequestByNumber( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationRequestByString( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationRequestByBool( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationRequestByCustom( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationId(const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationSlotType( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsOngoing( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsUnremovable( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationtapDismissed( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationExtraInfo( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationGroupName( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationRemovalWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationMaxScreenWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationAutoDeletedTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationClassification( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationColorEnabled( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsAlertOnce( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsStopwatch( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsCountDown( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationStatusBarText( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationBadgeIconStyle( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationShowDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request); static napi_value GetNotificationContent( const napi_env &env, const napi_value &value, NotificationRequest &request); @@ -188,19 +292,117 @@ public: static napi_value GetNotificationWantAgent( const napi_env &env, const napi_value &value, NotificationRequest &request); - static napi_value GetNotificationSlot(const napi_env &env, const napi_value &value, NotificationSlot &slot); + static napi_value GetNotificationSlot( + const napi_env &env, const napi_value &value, NotificationSlot &slot); + static napi_value GetNotificationSlotByString( + const napi_env &env, const napi_value &value, NotificationSlot &slot); + static napi_value GetNotificationSlotByBool( + const napi_env &env, const napi_value &value, NotificationSlot &slot); + static napi_value GetNotificationSlotByNumber( + const napi_env &env, const napi_value &value, NotificationSlot &slot); + static napi_value GetNotificationSlotByVibration( + const napi_env &env, const napi_value &value, NotificationSlot &slot); + + static napi_value GetNotificationActionButtons( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationActionButtonsDetailed( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + static napi_value GetNotificationActionButtonsDetailedBasicInfo( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + static napi_value GetNotificationActionButtonsDetailedByExtras( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + static napi_value GetNotificationUserInput( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton); + static napi_value GetNotificationUserInputByInputKey( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByTag( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByOptions( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByPermitMimeTypes( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByPermitFreeFormInput( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByEditType( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + static napi_value GetNotificationUserInputByAdditionalData( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput); + + static napi_value GetNotificationSmallIcon( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationLargeIcon( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationRequestDistributedOptions( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationIsDistributed( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationSupportDisplayDevices( + const napi_env &env, const napi_value &value, NotificationRequest &request); + static napi_value GetNotificationSupportOperateDevices( + const napi_env &env, const napi_value &value, NotificationRequest &request); - static napi_value GetBundleOption(const napi_env &env, const napi_value &value, BundleOption &option); + static napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type); + static napi_value GetNotificationBasicContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); + static napi_value GetNotificationBasicContentDetailed( + const napi_env &env, const napi_value &contentResult, std::shared_ptr basicContent); + + static napi_value GetNotificationLongTextContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); + static napi_value GetNotificationLongTextContentDetailed( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &longContent); + + static napi_value GetNotificationPictureContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); + static napi_value GetNotificationPictureContentDetailed( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &pictureContent); + + static napi_value GetNotificationConversationalContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); + static napi_value GetNotificationConversationalContentByUser( + const napi_env &env, const napi_value &contentResult, MessageUser &user); + static napi_value GetNotificationConversationalContentTitle( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent); + static napi_value GetNotificationConversationalContentGroup( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent); + static napi_value GetNotificationConversationalContentMessages( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent); + static napi_value GetConversationalMessage( + const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message); + static napi_value GetConversationalMessageBasicInfo( + const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message); + static napi_value GetConversationalMessageOtherInfo( + const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message); + static napi_value GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser); + static napi_value GetMessageUserByString(const napi_env &env, const napi_value &result, MessageUser &messageUser); + static napi_value GetMessageUserByBool(const napi_env &env, const napi_value &result, MessageUser &messageUser); + static napi_value GetMessageUserByCustom(const napi_env &env, const napi_value &result, MessageUser &messageUser); + + static napi_value GetNotificationMultiLineContent( + const napi_env &env, const napi_value &result, NotificationRequest &request); + static napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, + std::shared_ptr &multiLineContent); + + static napi_value GetBundleOption(const napi_env &env, const napi_value &value, NotificationBundleOption &option); static napi_value GetNotificationKey(const napi_env &env, const napi_value &value, NotificationKey &key); - static bool ContentTypeJSToC(const enum ContentType &inType, enum NotificationContent::Type &outType); + static bool ContentTypeJSToC(const ContentType &inType, NotificationContent::Type &outType); - static bool ContentTypeCToJS(const enum NotificationContent::Type &inType, enum ContentType &outType); + static bool ContentTypeCToJS(const NotificationContent::Type &inType, ContentType &outType); - static bool SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstant::SlotType &outType); + static bool SlotTypeJSToC(const SlotType &inType, NotificationConstant::SlotType &outType); - static bool SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, enum SlotType &outType); + static bool SlotTypeCToJS(const NotificationConstant::SlotType &inType, SlotType &outType); static bool SlotLevelJSToC(const SlotLevel &inLevel, NotificationSlot::NotificationLevel &outLevel); @@ -208,17 +410,35 @@ public: static bool ReasonCToJS(const int &inType, int &outType); - static bool DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationConstant::DisturbMode &outType); + static bool DoNotDisturbTypeJSToC(const DoNotDisturbType &inType, NotificationConstant::DoNotDisturbType &outType); + + static bool DoNotDisturbTypeCToJS(const NotificationConstant::DoNotDisturbType &inType, DoNotDisturbType &outType); + + static bool DeviceRemindTypeCToJS(const NotificationConstant::RemindType &inType, DeviceRemindType &outType); + + static bool SourceTypeCToJS(const NotificationConstant::SourceType &inType, SourceType &outType); static napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); + static napi_value GetNotificationTemplate( + const napi_env &env, const napi_value &value, NotificationRequest &request); + + static napi_value GetNotificationTemplateInfo(const napi_env &env, const napi_value &value, + std::shared_ptr &templ); + + static napi_value SetNotificationTemplateInfo( + const napi_env &env, const std::shared_ptr &templ, napi_value &result); + + static napi_value SetNotificationFlags( + const napi_env &env, const std::shared_ptr &flags, napi_value &result); + private: + static const int ARGS_ONE = 1; static const int ARGS_TWO = 2; - static const int PARAM0 = 0; - static const int PARAM1 = 1; + static const int ONLY_CALLBACK_MAX_PARA = 1; + static const int ONLY_CALLBACK_MIN_PARA = 0; static std::set> wantAgent_; }; - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/constant.h b/interfaces/kits/napi/ans/include/constant.h index 249864af98f992e3c9c266e015bff04dde9183b3..d5f8f3e99df42455c861bab0ac2de4f145689d05 100644 --- a/interfaces/kits/napi/ans/include/constant.h +++ b/interfaces/kits/napi/ans/include/constant.h @@ -15,10 +15,7 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CONSTANT_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_CONSTANT_H -#include "ans_log_wrapper.h" -#include "napi/native_api.h" -#include "napi/native_node_api.h" -#include "notification_helper.h" +#include "common.h" namespace OHOS { namespace NotificationNapi { @@ -30,8 +27,9 @@ napi_value InputsSourceInit(napi_env env, napi_value exports); napi_value DoNotDisturbMode(napi_env env, napi_value exports); napi_value InputEditTypeInit(napi_env env, napi_value exports); napi_value ContentTypeInit(napi_env env, napi_value exports); +napi_value DoNotDisturbTypeInit(napi_env env, napi_value exports); +napi_value DeviceRemindTypeInit(napi_env env, napi_value exports); napi_value ConstantInit(napi_env env, napi_value exports); - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/display_badge.h b/interfaces/kits/napi/ans/include/display_badge.h index 945543193b1a9beb9cd79442466f9f2f60546992..992a41deefeb54bd9a820430669fe1cbf86e050c 100644 --- a/interfaces/kits/napi/ans/include/display_badge.h +++ b/interfaces/kits/napi/ans/include/display_badge.h @@ -23,7 +23,6 @@ using namespace OHOS::Notification; napi_value DisplayBadge(napi_env env, napi_callback_info info); napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISPLAY_BADGE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/distributed.h b/interfaces/kits/napi/ans/include/distributed.h new file mode 100644 index 0000000000000000000000000000000000000000..ad379f9d3e86b8cc2fce02d191230d11438e8a77 --- /dev/null +++ b/interfaces/kits/napi/ans/include/distributed.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_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTRIBUTED_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTRIBUTED_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +napi_value IsDistributedEnabled(napi_env env, napi_callback_info info); +napi_value EnableDistributed(napi_env env, napi_callback_info info); +napi_value EnableDistributedByBundle(napi_env env, napi_callback_info info); +napi_value EnableDistributedSelf(napi_env env, napi_callback_info info); +napi_value IsDistributedEnableByBundle(napi_env env, napi_callback_info info); +napi_value GetDeviceRemindType(napi_env env, napi_callback_info info); +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTRIBUTED_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/disturb_mode.h b/interfaces/kits/napi/ans/include/disturb_mode.h index 9a199f9a7345d1f8389096589412d82f39ae8105..3a2d668bbf06c6576f18678c8c74c93334f0f0f7 100644 --- a/interfaces/kits/napi/ans/include/disturb_mode.h +++ b/interfaces/kits/napi/ans/include/disturb_mode.h @@ -21,8 +21,9 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; -napi_value SetDoNotDisturbMode(napi_env env, napi_callback_info info); - +napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info); +napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info); +napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_DISTURB_MODE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/enable_notification.h b/interfaces/kits/napi/ans/include/enable_notification.h index e7ae306486c5be506303458a24f219c07b754f23..d96094539a89f199ba1cb470c9f2df6f2b5ef006 100644 --- a/interfaces/kits/napi/ans/include/enable_notification.h +++ b/interfaces/kits/napi/ans/include/enable_notification.h @@ -23,7 +23,6 @@ using namespace OHOS::Notification; napi_value EnableNotification(napi_env env, napi_callback_info info); napi_value IsNotificationEnabled(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_ENABLE_NOTIFICATION_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/get_active.h b/interfaces/kits/napi/ans/include/get_active.h index 867eef8b07962545cf189cc51722c3dde9eb80ea..37865304ad27123aa2b837242fbc1ee34de85599 100644 --- a/interfaces/kits/napi/ans/include/get_active.h +++ b/interfaces/kits/napi/ans/include/get_active.h @@ -25,7 +25,6 @@ using namespace OHOS::Notification; napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info); napi_value GetActiveNotifications(napi_env env, napi_callback_info info); napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/init.h b/interfaces/kits/napi/ans/include/init.h index fabae8a06626e8624dda17b9c8fe957cca20971a..d8306a6643e2342d93e2bffa6ee0611658321d70 100644 --- a/interfaces/kits/napi/ans/include/init.h +++ b/interfaces/kits/napi/ans/include/init.h @@ -46,7 +46,6 @@ napi_module _module = { .reserved = {0} }; - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_INIT_H diff --git a/interfaces/kits/napi/ans/include/publish.h b/interfaces/kits/napi/ans/include/publish.h index a288687b928cf2cbc8282ac5bd102810abca23da..6d8405209b1d24bdfadfd4ef6ffc2c8a5d776204 100644 --- a/interfaces/kits/napi/ans/include/publish.h +++ b/interfaces/kits/napi/ans/include/publish.h @@ -15,15 +15,12 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H -#include #include "common.h" namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; - napi_value Publish(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_PUBLISH_H \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/ans_mt_constant.h b/interfaces/kits/napi/ans/include/reminder/native_module.h similarity index 47% rename from frameworks/ans/test/moduletest/ans_mt_constant.h rename to interfaces/kits/napi/ans/include/reminder/native_module.h index 99d2a2796c785265f89070fdb27fa00c94273d0d..b720a915fad114195f70ccf15cbafd02b4a741f1 100644 --- a/frameworks/ans/test/moduletest/ans_mt_constant.h +++ b/interfaces/kits/napi/ans/include/reminder/native_module.h @@ -12,30 +12,28 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_NATIVE_MODULE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_NATIVE_MODULE_H -#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H -#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H - -#include +#include "napi/native_api.h" +#include "napi/native_node_api.h" namespace OHOS { -namespace Notification { +namespace ReminderAgentNapi { +#ifdef __cplusplus +extern "C" { +#endif -namespace { -const std::string APP_NAME = "bundleName"; -const std::string NOTIFICATION_LABEL_0 = "Label0"; -const std::string NOTIFICATION_LABEL_1 = "Label1"; -const std::string NOTIFICATION_LABEL_2 = "Label2"; -const std::string AN_NOT_EXIST_KEY = "AN_NOT_EXIST_KEY"; -const std::string KEY_SPLITER = "_"; +__attribute__((constructor)) void RegisterModule(void); +napi_value ConstantInit(napi_env env, napi_value exports); +napi_value ReminderAgentInit(napi_env env, napi_value exports); -constexpr int UID = 1; -constexpr int CANCEL_REASON_DELETE = 2; -constexpr int APP_CANCEL_REASON_DELETE = 8; -constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; -} // namespace +static napi_value Init(napi_env env, napi_value exports); -} // namespace Notification +#ifdef __cplusplus +} +#endif } // namespace OHOS +} // namespace ReminderAgentNapi -#endif +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_NATIVE_MODULE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/reminder/publish.h b/interfaces/kits/napi/ans/include/reminder/publish.h new file mode 100644 index 0000000000000000000000000000000000000000..bb312474615cbf8a898af5f8983d892fa18bf37d --- /dev/null +++ b/interfaces/kits/napi/ans/include/reminder/publish.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_PUBLISH_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_PUBLISH_H + +#include "reminder/reminder_common.h" + +namespace OHOS { +namespace ReminderAgentNapi { +/** + * @brief Cancels a reminder. + * + * @param env Indicates the context. + * @param info Indicates the opaque datatype about the context. + * @return opaque pointer that is used to represent a JavaScript value + */ +napi_value CancelReminder(napi_env env, napi_callback_info info); + +/** + * @brief Cancels all reminders of current bundle. + * + * @param env Indicates the context. + * @param info Indicates the opaque datatype about the context. + * @return opaque pointer that is used to represent a JavaScript value + */ +napi_value CancelAllReminders(napi_env env, napi_callback_info info); + +/** + * @brief Obtains all reminders of current bundle. + * + * @param env Indicates the context. + * @param info Indicates the opaque datatype about the context. + * @return opaque pointer that is used to represent a JavaScript value + */ +napi_value GetValidReminders(napi_env env, napi_callback_info info); + +/** + * @brief Publishes a reminder. + * + * @param env Indicates the context. + * @param info Indicates the opaque datatype about the context. + * @return opaque pointer that is used to represent a JavaScript value + */ +napi_value PublishReminder(napi_env env, napi_callback_info info); +} // namespace ReminderAgentNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_PUBLISH_H diff --git a/interfaces/kits/napi/ans/include/reminder/reminder_common.h b/interfaces/kits/napi/ans/include/reminder/reminder_common.h new file mode 100644 index 0000000000000000000000000000000000000000..63b1d0f796e16be16994fb08cf4814b07b22c48d --- /dev/null +++ b/interfaces/kits/napi/ans/include/reminder/reminder_common.h @@ -0,0 +1,122 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_COMMON_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_COMMON_H + +#include "ans_log_wrapper.h" +#include "napi/native_api.h" +#include "napi/native_node_api.h" +#include "reminder_helper.h" +#include "reminder_request.h" + +namespace OHOS { +namespace ReminderAgentNapi { +using namespace OHOS::Notification; + +namespace { +const char* ACTION_BUTTON = "actionButton"; +const char* ACTION_BUTTON_TITLE = "title"; +const char* ACTION_BUTTON_TYPE = "type"; +const char* ALARM_HOUR = "hour"; +const char* ALARM_DAYS_OF_WEEK = "daysOfWeek"; +const char* ALARM_MINUTE = "minute"; +const char* CALENDAR_DATE_TIME = "dateTime"; +const char* CALENDAR_YEAR = "year"; +const char* CALENDAR_MONTH = "month"; +const char* CALENDAR_DAY = "day"; +const char* CALENDAR_HOUR = "hour"; +const char* CALENDAR_MINUTE = "minute"; +const char* CALENDAR_SECOND = "second"; +const char* CALENDAR_REPEAT_MONTHS = "repeatMonths"; +const char* CALENDAR_REPEAT_DAYS = "repeatDays"; +const char* CONTENT = "content"; +const char* EXPIRED_CONTENT = "expiredContent"; +const char* MAX_SCREEN_WANT_AGENT = "maxScreenWantAgent"; +const char* MAX_SCREEN_WANT_AGENT_PKG = "pkgName"; +const char* MAX_SCREEN_WANT_AGENT_ABILITY = "abilityName"; +const char* NOTIFICATION_ID = "notificationId"; +const char* REMINDER_TYPE = "reminderType"; +const char* RING_DURATION = "ringDuration"; +const char* SLOT_TYPE = "slotType"; +const char* SNOOZE_CONTENT = "snoozeContent"; +const char* SNOOZE_TIMES = "snoozeTimes"; +const char* TIME_INTERVAL = "timeInterval"; +const char* TITLE = "title"; +const char* TIMER_COUNT_DOWN_TIME = "triggerTimeInSeconds"; +const char* WANT_AGENT = "wantAgent"; +const char* WANT_AGENT_PKG = "pkgName"; +const char* WANT_AGENT_ABILITY = "abilityName"; +} + +class ReminderCommon { + ReminderCommon(); + ~ReminderCommon(); + ReminderCommon(ReminderCommon &other) = delete; + ReminderCommon& operator = (const ReminderCommon &other) = delete; + +public: + static napi_value GetReminderRequest( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static bool GetStringUtf8(const napi_env &env, const napi_value &value, + const char* propertyName, char* propertyVal, const int32_t size); + + static bool GetInt32(const napi_env &env, const napi_value &value, + const char* propertyName, int32_t& propertyVal, bool isNecessary); + + static bool GetInt64(const napi_env &env, const napi_value &value, + const char* propertyName, int64_t& propertyVal); + + static bool GetObject(const napi_env &env, const napi_value &value, + const char* propertyName, napi_value& propertyVal); + +private: + static bool CheckCalendarParams(const int32_t &year, const int32_t &month, const int32_t &day, + const int32_t &hour, const int32_t &min); + + static napi_value CreateReminderTimer( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static napi_value CreateReminderAlarm( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static napi_value CreateReminderCalendar( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static bool CreateReminder( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static bool GetPropertyValIfExist(const napi_env &env, const napi_value &value, + const char* propertyName, napi_value& propertyVal); + + static void GenWantAgent( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static void GenMaxScreenWantAgent( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static bool GenActionButtons( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static napi_value GenReminder( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static napi_value ParseInt32Array(const napi_env &env, const napi_value &value, + const char* propertyName, std::vector &propertyVal, uint8_t maxLen); +}; +} // namespace OHOS +} // namespace ReminderAgentNapi + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_COMMON_H diff --git a/interfaces/kits/napi/ans/include/remove.h b/interfaces/kits/napi/ans/include/remove.h index 2e03ac5acd1be8d3ab223debda04c0dcb450c82b..56bc61c2c226d3cdd8b8c0eba01f6839ca9d7309 100644 --- a/interfaces/kits/napi/ans/include/remove.h +++ b/interfaces/kits/napi/ans/include/remove.h @@ -25,7 +25,7 @@ using namespace OHOS::Notification; napi_value Remove(napi_env env, napi_callback_info info); napi_value RemoveAsBundle(napi_env env, napi_callback_info info); napi_value RemoveAll(napi_env env, napi_callback_info info); - +napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info); } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMOVE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/slot.h b/interfaces/kits/napi/ans/include/slot.h index e4e03749a6a641f4fe5cfd39ff193d5af548d46c..d7aaca4d26f0b899668c6e616abe185e0f4223a0 100644 --- a/interfaces/kits/napi/ans/include/slot.h +++ b/interfaces/kits/napi/ans/include/slot.h @@ -30,7 +30,6 @@ napi_value GetSlots(napi_env env, napi_callback_info info); napi_value GetSlotsByBundle(napi_env env, napi_callback_info info); napi_value RemoveSlot(napi_env env, napi_callback_info info); napi_value RemoveAllSlots(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h index 5046928a0aec27bf2f03e92eac04b0e508a5608c..b18e1de4b0bc547caf963db874b64bed9d702eae 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -39,13 +39,13 @@ public: virtual void OnUpdate(const std::shared_ptr &sortingMap) override; - virtual void OnSubscribeResult(NotificationConstant::SubscribeResult result) override; + virtual void OnConnected() override; - virtual void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override; + virtual void OnDisconnected() override; virtual void OnDied() override; - virtual void OnDisturbModeChanged(int disturbMode) override; + virtual void OnDoNotDisturbDateChange(const std::shared_ptr &date) override; void SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref); @@ -64,6 +64,8 @@ private: void SetDisturbModeCallbackInfo(const napi_env &env, const napi_ref &ref); + void SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref); + private: struct CallbackInfo { napi_env env = nullptr; @@ -77,6 +79,7 @@ private: CallbackInfo unsubscribeCallbackInfo_; CallbackInfo dieCallbackInfo_; CallbackInfo disturbModeCallbackInfo_; + CallbackInfo disturbDateCallbackInfo_; }; struct SubscriberInstancesInfo { @@ -92,7 +95,6 @@ bool AddSubscriberInstancesInfo(const napi_env &env, const SubscriberInstancesIn bool DelSubscriberInstancesInfo(const napi_env &env, SubscriberInstance *subscriber); napi_value Subscribe(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_SUBSCRIBE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/unsubscribe.h b/interfaces/kits/napi/ans/include/unsubscribe.h index 595de743b7f07909e92fd0bbbe89227524f2f3af..670b257aecd3e64887211eef15151a25e0d6bb5d 100644 --- a/interfaces/kits/napi/ans/include/unsubscribe.h +++ b/interfaces/kits/napi/ans/include/unsubscribe.h @@ -21,9 +21,7 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; - napi_value Unsubscribe(napi_env env, napi_callback_info info); - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/ans_template.cpp b/interfaces/kits/napi/ans/src/ans_template.cpp new file mode 100644 index 0000000000000000000000000000000000000000..8c33a73f75dda73d4f59f4474657d91cdff55736 --- /dev/null +++ b/interfaces/kits/napi/ans/src/ans_template.cpp @@ -0,0 +1,125 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_template.h" +#include "cancel.h" + +namespace OHOS { +namespace NotificationNapi { +const int IS_TEMPLATE_MAX_PARA = 2; + +struct TemplateName { + std::string templateName = ""; + bool support = false; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoTemplate { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + TemplateName params; + CallbackPromiseInfo info; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, TemplateName& params) +{ + ANS_LOGI("enter"); + + size_t argc = IS_TEMPLATE_MAX_PARA; + napi_value argv[IS_TEMPLATE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc <= IS_TEMPLATE_MAX_PARA, "Wrong number of arguments"); + + napi_valuetype valuetype = napi_undefined; + // argv[0]: name: string + NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + params.templateName = str; + + // argv[1]: callback + if (argc >= IS_TEMPLATE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[1], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value IsSupportTemplate(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + TemplateName params; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoTemplate *asyncCallbackinfo = new (std::nothrow) + AsyncCallbackInfoTemplate {.env = env, .asyncWork = nullptr, .params = params}; + if (!asyncCallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asyncCallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "IsSupportTemplate", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsSupportTemplate napi_create_async_work start"); + AsyncCallbackInfoTemplate *asyncCallbackinfo = (AsyncCallbackInfoTemplate *)data; + + asyncCallbackinfo->info.errorCode = NotificationHelper::IsSupportTemplate( + asyncCallbackinfo->params.templateName, asyncCallbackinfo->params.support); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("IsSupportTemplate napi_create_async_work end"); + AsyncCallbackInfoTemplate *asyncCallbackinfo = (AsyncCallbackInfoTemplate *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asyncCallbackinfo->params.support, &result); + Common::ReturnCallbackPromise(env, asyncCallbackinfo->info, result); + + if (asyncCallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asyncCallbackinfo->info.callback); + } + + napi_delete_async_work(env, asyncCallbackinfo->asyncWork); + if (asyncCallbackinfo != nullptr) { + delete asyncCallbackinfo; + asyncCallbackinfo = nullptr; + } + }, + (void *)asyncCallbackinfo, + &asyncCallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asyncCallbackinfo->asyncWork)); + + if (asyncCallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 71ea420be9f92fd8b9f260852d8a32438d8626bf..799bc5cd8fd6861ccc5600d76cd9c17589af786f 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -17,9 +17,9 @@ namespace OHOS { namespace NotificationNapi { - const int CANCEL_MAX_PARA = 3; -const int CANCEL_ALL_MAX_PARA = 1; +const int CANCEL_GROUP_MAX_PARA = 2; +const int CANCEL_GROUP_MIN_PARA = 1; struct ParametersInfoCancel { int id = 0; @@ -35,6 +35,18 @@ struct AsyncCallbackInfoCancel { CallbackPromiseInfo info; }; +struct ParametersInfoCancelGroup { + std::string groupName = ""; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoCancelGroup { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + ParametersInfoCancelGroup params {}; +}; + napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancel ¶s) { ANS_LOGI("enter"); @@ -47,52 +59,62 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_valuetype valuetype = napi_undefined; // argv[0]: id: number - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - NAPI_CALL(env, napi_get_value_int32(env, argv[0], ¶s.id)); + NAPI_CALL(env, napi_get_value_int32(env, argv[PARAM0], ¶s.id)); // argv[1]: label: string / callback if (argc >= CANCEL_MAX_PARA - 1) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, (valuetype == napi_string || valuetype == napi_function), "Wrong argument type. String or function expected."); if (valuetype == napi_string) { char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - NAPI_CALL(env, napi_get_value_string_utf8(env, argv[1], str, STR_MAX_SIZE - 1, &strLen)); + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM1], str, STR_MAX_SIZE - 1, &strLen)); paras.label = str; } else { - napi_create_reference(env, argv[1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } } // argv[2]: callback if (argc >= CANCEL_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[CANCEL_MAX_PARA - 1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[CANCEL_MAX_PARA - 1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM2], 1, ¶s.callback); } return Common::NapiGetNull(env); } -napi_value ParseParametersByCancelAll(const napi_env &env, const napi_callback_info &info, napi_ref &callback) +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancelGroup ¶s) { ANS_LOGI("enter"); - size_t argc = CANCEL_ALL_MAX_PARA; - napi_value argv[CANCEL_ALL_MAX_PARA] = {nullptr}; + size_t argc = CANCEL_GROUP_MAX_PARA; + napi_value argv[CANCEL_GROUP_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= CANCEL_GROUP_MIN_PARA, "Wrong number of arguments"); - if (argc >= CANCEL_ALL_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + napi_valuetype valuetype = napi_undefined; + // argv[0]: groupName: string + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM0], str, STR_MAX_SIZE - 1, &strLen)); + paras.groupName = str; + + // argv[1]: callback + if (argc >= CANCEL_GROUP_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } + return Common::NapiGetNull(env); } @@ -159,7 +181,7 @@ napi_value CancelAll(napi_env env, napi_callback_info info) ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByCancelAll(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -210,5 +232,62 @@ napi_value CancelAll(napi_env env, napi_callback_info info) } } +napi_value CancelGroup(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + ParametersInfoCancelGroup params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoCancelGroup *asynccallbackinfo = new (std::nothrow) + AsyncCallbackInfoCancelGroup {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "cancelGroup", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("CancelGroup napi_create_async_work start"); + AsyncCallbackInfoCancelGroup *asynccallbackinfo = (AsyncCallbackInfoCancelGroup *)data; + ANS_LOGI("asynccallbackinfo->params.groupName = %{public}s", asynccallbackinfo->params.groupName.c_str()); + asynccallbackinfo->info.errorCode = + NotificationHelper::CancelGroup(asynccallbackinfo->params.groupName); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("CancelGroup napi_create_async_work end"); + AsyncCallbackInfoCancelGroup *asynccallbackinfo = (AsyncCallbackInfoCancelGroup *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 45f69f2e8a33e14495e5cf8ced977de093cee4c2..d8d8a57c1d1a8d72acd31f6dde6eca60df13a5bb 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -14,69 +14,12 @@ */ #include "common.h" -#include #include "napi_common.h" -#include "notification_long_text_content.h" -#include "notification_multiline_content.h" -#include "notification_slot.h" #include "pixel_map_napi.h" -#include "publish.h" -#include "want_agent.h" namespace OHOS { namespace NotificationNapi { std::set> Common::wantAgent_; -static napi_value GetIdByPublish(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationIsUnremovable( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationDeliveryTime( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationtapDismissed( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationRemovalWantAgent( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationMaxScreenWantAgent( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationAutoDeletedTime( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationClassification( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationColorEnabled( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationIsAlertOnce( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationIsStopwatch( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationIsCountDown( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationStatusBarText( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationBadgeIconStyle( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationShowDeliveryTime( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationNotificationActionButtons( - const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationSmallIcon(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationLargeIcon(const napi_env &env, const napi_value &value, NotificationRequest &request); -static napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type); -static napi_value GetNotificationBasicContent( - const napi_env &env, const napi_value &result, NotificationRequest &request); -static napi_value GetNotificationLongTextContent( - const napi_env &env, const napi_value &result, NotificationRequest &request); -static napi_value GetNotificationPictureContent( - const napi_env &env, const napi_value &result, NotificationRequest &request); -static napi_value GetNotificationConversationalContent( - const napi_env &env, const napi_value &result, NotificationRequest &request); -static napi_value GetNotificationMultiLineContent( - const napi_env &env, const napi_value &result, NotificationRequest &request); -static napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, - std::shared_ptr &multiLineContent); -static napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value, NotificationRequest &request); Common::Common() {} @@ -84,7 +27,7 @@ Common::Common() Common::~Common() {} -napi_value Common::NapiGetboolean(napi_env env, const bool &isValue) +napi_value Common::NapiGetBoolean(napi_env env, const bool &isValue) { napi_value result = nullptr; napi_get_boolean(env, isValue, &result); @@ -133,14 +76,13 @@ void Common::PaddingCallbackPromiseInfo( void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInfo &info, const napi_value &result) { - ANS_LOGI("enter"); - + ANS_LOGI("enter errorCode=%{public}d", info.errorCode); if (info.isCallback) { SetCallback(env, info.callback, info.errorCode, result); } else { - SetPromise(env, info.deferred, result); + SetPromise(env, info.deferred, info.errorCode, result); } - ANS_LOGI("ReturnCallbackPromise end"); + ANS_LOGI("end"); } void Common::SetCallback( @@ -160,10 +102,29 @@ void Common::SetCallback( ANS_LOGI("end"); } -void Common::SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +void Common::SetCallback( + const napi_env &env, const napi_ref &callbackIn, const napi_value &result) +{ + ANS_LOGI("enter"); + napi_value undefined = nullptr; + napi_get_undefined(env, &undefined); + + napi_value callback = nullptr; + napi_value resultout = nullptr; + napi_get_reference_value(env, callbackIn, &callback); + NAPI_CALL_RETURN_VOID(env, napi_call_function(env, undefined, callback, ARGS_ONE, &result, &resultout)); + ANS_LOGI("end"); +} + +void Common::SetPromise( + const napi_env &env, const napi_deferred &deferred, const int &errorCode, const napi_value &result) { ANS_LOGI("enter"); - napi_resolve_deferred(env, deferred, result); + if (errorCode == ERR_OK) { + napi_resolve_deferred(env, deferred, result); + } else { + napi_reject_deferred(env, deferred, GetCallbackErrorValue(env, errorCode)); + } ANS_LOGI("end"); } @@ -175,24 +136,99 @@ napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) napi_value promise = nullptr; napi_deferred deferred = nullptr; napi_create_promise(env, &deferred, &promise); - SetPromise(env, deferred, Common::NapiGetNull(env)); + SetPromise(env, deferred, ERROR, Common::NapiGetNull(env)); return promise; } } +napi_value Common::ParseParaOnlyCallback(const napi_env &env, const napi_callback_info &info, napi_ref &callback) +{ + ANS_LOGI("enter"); + + size_t argc = ONLY_CALLBACK_MAX_PARA; + napi_value argv[ONLY_CALLBACK_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ONLY_CALLBACK_MIN_PARA, "Wrong number of arguments"); + + // argv[0]:callback + napi_valuetype valuetype = napi_undefined; + if (argc >= ONLY_CALLBACK_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[PARAM0], 1, &callback); + } + + return Common::NapiGetNull(env); +} + +napi_value Common::SetNotificationByDistributedOptions( + const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result) +{ + ANS_LOGI("enter"); + if (notification == nullptr) { + ANS_LOGE("notification is nullptr"); + return NapiGetBoolean(env, false); + } + + NotificationDistributedOptions options = notification->GetNotificationRequest().GetNotificationDistributedOptions(); + napi_value value = nullptr; + // isDistributed?: boolean + napi_get_boolean(env, options.IsDistributed(), &value); + napi_set_named_property(env, result, "isDistributed", value); + + // supportDisplayDevices?: Array + int count = 0; + napi_value arrSupportDisplayDevices = nullptr; + napi_create_array(env, &arrSupportDisplayDevices); + std::vector displayDevices = options.GetDevicesSupportDisplay(); + for (auto vec : displayDevices) { + napi_value vecValue = nullptr; + ANS_LOGI("supportDisplayDevices = %{public}s", vec.c_str()); + napi_create_string_utf8(env, vec.c_str(), NAPI_AUTO_LENGTH, &vecValue); + napi_set_element(env, arrSupportDisplayDevices, count, vecValue); + count ++; + } + napi_set_named_property(env, result, "supportDisplayDevices", arrSupportDisplayDevices); + + // supportOperateDevices?: Array + count = 0; + napi_value arrSupportOperateDevices = nullptr; + napi_create_array(env, &arrSupportOperateDevices); + std::vector operateDevices = options.GetDevicesSupportOperate(); + for (auto vec : operateDevices) { + napi_value vecValue = nullptr; + ANS_LOGI("supportOperateDevices = %{public}s", vec.c_str()); + napi_create_string_utf8(env, vec.c_str(), NAPI_AUTO_LENGTH, &vecValue); + napi_set_element(env, arrSupportOperateDevices, count, vecValue); + count ++; + } + napi_set_named_property(env, result, "supportOperateDevices", arrSupportOperateDevices); + + // readonly remindType?: number + enum DeviceRemindType outType = DeviceRemindType::IDLE_DONOT_REMIND; + if (!DeviceRemindTypeCToJS(notification->GetRemindType(), outType)) { + return NapiGetBoolean(env, false); + } + napi_create_int32(env, (int32_t)outType, &value); + napi_set_named_property(env, result, "remindType", value); + + return NapiGetBoolean(env, true); +} + napi_value Common::SetNotification( - const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result) + const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result) { ANS_LOGI("enter"); if (notification == nullptr) { ANS_LOGE("notification is nullptr"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } napi_value value = nullptr; NotificationRequest request = notification->GetNotificationRequest(); if (!SetNotificationRequest(env, &request, result)) { - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } // hashCode?: string @@ -215,34 +251,78 @@ napi_value Common::SetNotification( napi_create_int32(env, notification->GetPid(), &value); napi_set_named_property(env, result, "creatorPid", value); - return NapiGetboolean(env, true); + // distributedOption?:DistributedOptions + napi_value distributedResult = nullptr; + napi_create_object(env, &distributedResult); + if (!SetNotificationByDistributedOptions(env, notification, distributedResult)) { + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "distributedOption", distributedResult); + + // readonly isRemoveAllowed?: boolean + napi_get_boolean(env, notification->IsRemoveAllowed(), &value); + napi_set_named_property(env, result, "isRemoveAllowed", value); + + // readonly source?: number + SourceType sourceType = SourceType::TYPE_NORMAL; + if (!SourceTypeCToJS(notification->GetSourceType(), sourceType)) { + return NapiGetBoolean(env, false); + } + napi_create_int32(env, (int32_t)sourceType, &value); + napi_set_named_property(env, result, "source", value); + + // readonly deviceId?: string + napi_create_string_utf8(env, notification->GetDeviceId().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "deviceId", value); + + return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationRequest( - const napi_env &env, OHOS::Notification::NotificationRequest *request, napi_value &result) +napi_value Common::SetNotificationRequestByString( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) { - ANS_LOGI("SetNotificationRequest start"); + ANS_LOGI("enter"); napi_value value = nullptr; if (request == nullptr) { ANS_LOGE("request is nullptr"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - // content: NotificationContent - std::shared_ptr content = request->GetContent(); - if (content) { - napi_value contentResult = nullptr; - napi_create_object(env, &contentResult); - if (!SetNotificationContent(env, content, contentResult)) { - ANS_LOGE("SetNotificationContent call failed"); - return NapiGetboolean(env, false); - } - napi_set_named_property(env, result, "content", contentResult); - } else { - ANS_LOGE("content is nullptr"); - return NapiGetboolean(env, false); + // classification?: string + napi_create_string_utf8(env, request->GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "classification", value); + + // statusBarText?: string + napi_create_string_utf8(env, request->GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "statusBarText", value); + + // label?: string + napi_create_string_utf8(env, request->GetLabel().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "label", value); + + // groupName?: string + napi_create_string_utf8(env, request->GetGroupName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "groupName", value); + + // readonly creatorBundleName?: string + napi_create_string_utf8(env, request->GetCreatorBundleName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "creatorBundleName", value); + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationRequestByNumber( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); + + napi_value value = nullptr; + + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); } // id?: number @@ -250,13 +330,52 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "id", value); // slotType?: SlotType - enum SlotType outType = SlotType::UNKNOWN_TYPE; + SlotType outType = SlotType::UNKNOWN_TYPE; if (!SlotTypeCToJS(request->GetSlotType(), outType)) { - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_create_int32(env, outType, &value); + napi_create_int32(env, (int32_t)outType, &value); napi_set_named_property(env, result, "slotType", value); + // deliveryTime?: number + napi_create_int64(env, request->GetDeliveryTime(), &value); + napi_set_named_property(env, result, "deliveryTime", value); + + // autoDeletedTime?: number + napi_create_int64(env, request->GetAutoDeletedTime(), &value); + napi_set_named_property(env, result, "autoDeletedTime", value); + + // color ?: number + napi_create_uint32(env, request->GetColor(), &value); + napi_set_named_property(env, result, "color", value); + + // badgeIconStyle ?: number + int badgeIconStyle = (int)request->GetBadgeIconStyle(); + napi_create_int32(env, badgeIconStyle, &value); + napi_set_named_property(env, result, "badgeIconStyle", value); + + // readonly creatorUid?: number + napi_create_int32(env, request->GetCreatorUid(), &value); + napi_set_named_property(env, result, "creatorUid", value); + + // readonly creatorPid?: number + napi_create_int32(env, request->GetCreatorPid(), &value); + napi_set_named_property(env, result, "creatorPid", value); + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationRequestByBool( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); + + napi_value value = nullptr; + + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); + } // isOngoing?: boolean napi_get_boolean(env, request->IsInProgress(), &value); napi_set_named_property(env, result, "isOngoing", value); @@ -265,18 +384,45 @@ napi_value Common::SetNotificationRequest( napi_get_boolean(env, request->IsUnremovable(), &value); napi_set_named_property(env, result, "isUnremovable", value); - // deliveryTime?: number - napi_create_int64(env, request->GetDeliveryTime(), &value); - napi_set_named_property(env, result, "deliveryTime", value); - // tapDismissed?: boolean napi_get_boolean(env, request->IsTapDismissed(), &value); napi_set_named_property(env, result, "tapDismissed", value); - // autoDeletedTime?: number - napi_create_int64(env, request->GetAutoDeletedTime(), &value); - napi_set_named_property(env, result, "autoDeletedTime", value); + // colorEnabled?: boolean + napi_get_boolean(env, request->IsColorEnabled(), &value); + napi_set_named_property(env, result, "colorEnabled", value); + + // isAlertOnce?: boolean + napi_get_boolean(env, request->IsAlertOneTime(), &value); + napi_set_named_property(env, result, "isAlertOnce", value); + + // isStopwatch?: boolean + napi_get_boolean(env, request->IsShowStopwatch(), &value); + napi_set_named_property(env, result, "isStopwatch", value); + + // isCountDown?: boolean + napi_get_boolean(env, request->IsCountdownTimer(), &value); + napi_set_named_property(env, result, "isCountDown", value); + // isFloatingIcon?: boolean + napi_get_boolean(env, request->IsFloatingIcon(), &value); + napi_set_named_property(env, result, "isFloatingIcon", value); + + // showDeliveryTime?: boolean + napi_get_boolean(env, request->IsShowDeliveryTime(), &value); + napi_set_named_property(env, result, "showDeliveryTime", value); + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationRequestByWantAgent( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); + } // wantAgent?: WantAgent std::shared_ptr agent = request->GetWantAgent(); if (agent) { @@ -287,15 +433,7 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); } - // extraInfo ?: {[key:string] : any} - std::shared_ptr additionalData = request->GetAdditionalData(); - if (additionalData) { - napi_value extraInfo = nullptr; - extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); - napi_set_named_property(env, result, "extraInfo", extraInfo); - } - - // removalWantAgent ?: WantAgent + // removalWantAgent?: WantAgent std::shared_ptr removalAgent = request->GetRemovalWantAgent(); if (removalAgent) { napi_value wantAgent = nullptr; @@ -305,7 +443,7 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "removalWantAgent", NapiGetNull(env)); } - // maxScreenWantAgent ? WantAgent + // maxScreenWantAgent?: WantAgent std::shared_ptr maxScreenAgent = request->GetMaxScreenWantAgent(); if (maxScreenAgent) { napi_value wantAgent = nullptr; @@ -315,68 +453,20 @@ napi_value Common::SetNotificationRequest( napi_set_named_property(env, result, "maxScreenWantAgent", NapiGetNull(env)); } - // classification ?: string - napi_create_string_utf8(env, request->GetClassification().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "classification", value); - - // color ?: number - napi_create_uint32(env, request->GetColor(), &value); - napi_set_named_property(env, result, "color", value); - - // colorEnabled ?: boolean - napi_get_boolean(env, request->IsColorEnabled(), &value); - napi_set_named_property(env, result, "colorEnabled", value); - - // isAlertOnce ?: boolean - napi_get_boolean(env, request->IsAlertOneTime(), &value); - napi_set_named_property(env, result, "isAlertOnce", value); - - // isStopwatch ?: boolean - napi_get_boolean(env, request->IsShowStopwatch(), &value); - napi_set_named_property(env, result, "isStopwatch", value); - - // isCountDown ?: boolean - napi_get_boolean(env, request->IsCountdownTimer(), &value); - napi_set_named_property(env, result, "isCountDown", value); - - // statusBarText ?: string - napi_create_string_utf8(env, request->GetStatusBarText().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "statusBarText", value); - - // isFloatingIcon ?: boolean - napi_get_boolean(env, request->IsFloatingIcon(), &value); - napi_set_named_property(env, result, "isFloatingIcon", value); - - // label ?: string - napi_create_string_utf8(env, request->GetLabel().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "label", value); - - // badgeIconStyle ?: number - int badgeIconStyle = (int)request->GetBadgeIconStyle(); - napi_create_int32(env, badgeIconStyle, &value); - napi_set_named_property(env, result, "badgeIconStyle", value); + return NapiGetBoolean(env, true); +} - // showDeliveryTime ?: boolean - napi_get_boolean(env, request->IsShowDeliveryTime(), &value); - napi_set_named_property(env, result, "showDeliveryTime", value); +napi_value Common::SetNotificationRequestByPixelMap( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); - // actionButtons?: Array - napi_value arr = nullptr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : request->GetActionButtons()) { - if (vec) { - napi_value actionButtonResult = nullptr; - napi_create_object(env, &actionButtonResult); - if (SetNotificationActionButton(env, vec, actionButtonResult)) { - napi_set_element(env, arr, count, actionButtonResult); - count++; - } - } + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); } - napi_set_named_property(env, result, "actionButtons", arr); - // smallIcon ?: image.PixelMap + // smallIcon?: image.PixelMap std::shared_ptr littleIcon = request->GetLittleIcon(); if (littleIcon) { napi_value smallIconResult = nullptr; @@ -391,7 +481,7 @@ napi_value Common::SetNotificationRequest( } } - // largeIcon ?: image.PixelMap + // largeIcon?: image.PixelMap std::shared_ptr largeIcon = request->GetBigIcon(); if (largeIcon) { napi_value largeIconResult = nullptr; @@ -406,44 +496,140 @@ napi_value Common::SetNotificationRequest( } } - // readonly creatorBundleName?: string - napi_create_string_utf8(env, request->GetCreatorBundleName().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "creatorBundleName", value); - - // readonly creatorUid?: number - napi_create_int32(env, request->GetCreatorUid(), &value); - napi_set_named_property(env, result, "creatorUid", value); - - // readonly creatorPid?: number - napi_create_int32(env, request->GetCreatorPid(), &value); - napi_set_named_property(env, result, "creatorPid", value); - - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationSortingMap( - const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result) +napi_value Common::SetNotificationRequestByCustom( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) { - ANS_LOGI("SetNotificationSortingMap start"); - if (sortingMap == nullptr) { - ANS_LOGE("sortingMap is null"); - return NapiGetboolean(env, false); - } - if (sortingMap->GetKey().size() == 0) { - ANS_LOGE("sortingMap GetKey().size is empty"); - return NapiGetboolean(env, false); + ANS_LOGI("enter"); + + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); } - size_t count = 0; - napi_value arrSortedHashCode = nullptr; - napi_create_array(env, &arrSortedHashCode); - napi_value sortingsResult = nullptr; - napi_create_object(env, &sortingsResult); - for (auto key : sortingMap->GetKey()) { - NotificationSorting sorting; - if (sortingMap->GetNotificationSorting(key, sorting)) { - // sortedHashCode: Array - napi_value keyValue = nullptr; + // content: NotificationContent + std::shared_ptr content = request->GetContent(); + if (content) { + napi_value contentResult = nullptr; + napi_create_object(env, &contentResult); + if (!SetNotificationContent(env, content, contentResult)) { + ANS_LOGE("SetNotificationContent call failed"); + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "content", contentResult); + } else { + ANS_LOGE("content is nullptr"); + return NapiGetBoolean(env, false); + } + + // extraInfo?: {[key:string] : any} + std::shared_ptr additionalData = request->GetAdditionalData(); + if (additionalData) { + napi_value extraInfo = nullptr; + extraInfo = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + napi_set_named_property(env, result, "extraInfo", extraInfo); + } + + // actionButtons?: Array + napi_value arr = nullptr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : request->GetActionButtons()) { + if (vec) { + napi_value actionButtonResult = nullptr; + napi_create_object(env, &actionButtonResult); + if (SetNotificationActionButton(env, vec, actionButtonResult)) { + napi_set_element(env, arr, count, actionButtonResult); + count++; + } + } + } + napi_set_named_property(env, result, "actionButtons", arr); + + // template?: NotificationTemplate + std::shared_ptr templ = request->GetTemplate(); + if (templ) { + napi_value templateResult = nullptr; + napi_create_object(env, &templateResult); + if (!SetNotificationTemplateInfo(env, templ, templateResult)) { + ANS_LOGE("SetNotificationTemplate call failed"); + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "template", templateResult); + } + + // readonly notificationFlags?: NotificationFlags + std::shared_ptr flags = request->GetFlags(); + if (flags) { + napi_value flagsResult = nullptr; + napi_create_object(env, &flagsResult); + if (!SetNotificationFlags(env, flags, flagsResult)) { + ANS_LOGE("SetNotificationFlags call failed"); + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "notificationFlags", flagsResult); + } + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationRequest( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); + + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); + } + + if (!SetNotificationRequestByString(env, request, result)) { + return NapiGetBoolean(env, false); + } + if (!SetNotificationRequestByNumber(env, request, result)) { + return NapiGetBoolean(env, false); + } + if (!SetNotificationRequestByBool(env, request, result)) { + return NapiGetBoolean(env, false); + } + if (!SetNotificationRequestByWantAgent(env, request, result)) { + return NapiGetBoolean(env, false); + } + if (!SetNotificationRequestByPixelMap(env, request, result)) { + return NapiGetBoolean(env, false); + } + if (!SetNotificationRequestByCustom(env, request, result)) { + return NapiGetBoolean(env, false); + } + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationSortingMap( + const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result) +{ + ANS_LOGI("enter"); + if (sortingMap == nullptr) { + ANS_LOGE("sortingMap is null"); + return NapiGetBoolean(env, false); + } + if (sortingMap->GetKey().size() == 0) { + ANS_LOGE("sortingMap GetKey().size is empty"); + return NapiGetBoolean(env, false); + } + + size_t count = 0; + napi_value arrSortedHashCode = nullptr; + napi_create_array(env, &arrSortedHashCode); + napi_value sortingsResult = nullptr; + napi_create_object(env, &sortingsResult); + for (auto key : sortingMap->GetKey()) { + NotificationSorting sorting; + if (sortingMap->GetNotificationSorting(key, sorting)) { + // sortedHashCode: Array + napi_value keyValue = nullptr; ANS_LOGI("sortingMap key = %{public}s", key.c_str()); napi_create_string_utf8(env, key.c_str(), NAPI_AUTO_LENGTH, &keyValue); napi_set_element(env, arrSortedHashCode, count, keyValue); @@ -453,7 +639,7 @@ napi_value Common::SetNotificationSortingMap( napi_create_object(env, &sortingResult); if (!SetNotificationSorting(env, sorting, sortingResult)) { ANS_LOGE("SetNotificationSorting call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } napi_set_named_property(env, sortingsResult, key.c_str(), sortingResult); count++; @@ -464,12 +650,12 @@ napi_value Common::SetNotificationSortingMap( napi_set_named_property(env, result, "sortedHashCode", arrSortedHashCode); napi_set_named_property(env, result, "sortings", sortingsResult); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationSorting(const napi_env &env, const NotificationSorting &sorting, napi_value &result) { - ANS_LOGI("SetNotificationSorting start"); + ANS_LOGI("enter"); // slot: NotificationSlot napi_value slotResult = nullptr; @@ -477,7 +663,7 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_create_object(env, &slotResult); if (!SetNotificationSlot(env, sorting.GetSlot(), slotResult)) { ANS_LOGE("SetNotificationSlot call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } napi_set_named_property(env, result, "slot", slotResult); @@ -509,7 +695,7 @@ napi_value Common::SetNotificationSorting(const napi_env &env, const Notificatio napi_create_int32(env, sorting.GetVisiblenessOverride(), &value); napi_set_named_property(env, result, "visiblenessOverride", value); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSlot &slot, napi_value &result) @@ -518,19 +704,19 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl napi_value value = nullptr; // type: SlotType - enum SlotType outType = SlotType::UNKNOWN_TYPE; + SlotType outType = SlotType::UNKNOWN_TYPE; if (!SlotTypeCToJS(slot.GetType(), outType)) { - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_create_int32(env, outType, &value); + napi_create_int32(env, (int32_t)outType, &value); napi_set_named_property(env, result, "type", value); // level?: number - enum SlotLevel outLevel { SlotLevel::LEVEL_NONE }; + SlotLevel outLevel = SlotLevel::LEVEL_NONE; if (!SlotLevelCToJS(slot.GetLevel(), outLevel)) { - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_create_int32(env, outLevel, &value); + napi_create_int32(env, (int32_t)outLevel, &value); napi_set_named_property(env, result, "level", value); // desc?: string @@ -577,107 +763,99 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl } napi_set_named_property(env, result, "vibrationValues", arr); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationContent( - const napi_env &env, const std::shared_ptr &content, napi_value &result) +napi_value Common::SetNotificationContentDetailed(const napi_env &env, const ContentType &type, + const std::shared_ptr &content, napi_value &result) { - ANS_LOGI("SetNotificationContent start"); - if (content == nullptr) { + ANS_LOGI("enter"); + napi_value ret = NapiGetBoolean(env, false); + if (!content) { ANS_LOGE("content is null"); - return NapiGetboolean(env, false); + return ret; } - napi_value value = nullptr; - // contentType: ContentType - NotificationContent::Type type = content->GetContentType(); - ContentType outType = ContentType::NOTIFICATION_CONTENT_BASIC_TEXT; - if (!ContentTypeCToJS(type, outType)) { - return NapiGetboolean(env, false); - } - - napi_create_int32(env, (int32_t)outType, &value); - napi_set_named_property(env, result, "contentType", value); - std::shared_ptr basicContent = content->GetNotificationContent(); if (basicContent == nullptr) { - ANS_LOGI("content is null"); - return NapiGetboolean(env, false); + ANS_LOGE("content is null"); + return ret; } - if (outType == ContentType::NOTIFICATION_CONTENT_BASIC_TEXT) { + + napi_value contentResult = nullptr; + napi_create_object(env, &contentResult); + if (type == ContentType::NOTIFICATION_CONTENT_BASIC_TEXT) { // normal?: NotificationBasicContent - napi_value basicContentResult = nullptr; - napi_create_object(env, &basicContentResult); - if (SetNotificationBasicContent(env, basicContent.get(), basicContentResult)) { - napi_set_named_property(env, result, "normal", basicContentResult); - } else { - return NapiGetboolean(env, false); + ret = SetNotificationBasicContent(env, basicContent.get(), contentResult); + if (ret) { + napi_set_named_property(env, result, "normal", contentResult); } - - } else if (outType == ContentType::NOTIFICATION_CONTENT_LONG_TEXT) { + } else if (type == ContentType::NOTIFICATION_CONTENT_LONG_TEXT) { // longText?: NotificationLongTextContent - OHOS::Notification::NotificationLongTextContent *longTextContent = - static_cast(basicContent.get()); - napi_value longTextContentResult = nullptr; - napi_create_object(env, &longTextContentResult); - if (SetNotificationLongTextContent(env, longTextContent, longTextContentResult)) { - napi_set_named_property(env, result, "longText", longTextContentResult); - } else { - return NapiGetboolean(env, false); + ret = SetNotificationLongTextContent(env, basicContent.get(), contentResult); + if (ret) { + napi_set_named_property(env, result, "longText", contentResult); } - - } else if (outType == ContentType::NOTIFICATION_CONTENT_PICTURE) { + } else if (type == ContentType::NOTIFICATION_CONTENT_PICTURE) { // picture?: NotificationPictureContent - OHOS::Notification::NotificationPictureContent *pictureContent = - static_cast(basicContent.get()); - napi_value pictureContentResult = nullptr; - napi_create_object(env, &pictureContentResult); - if (SetNotificationPictureContent(env, pictureContent, pictureContentResult)) { - napi_set_named_property(env, result, "picture", pictureContentResult); - } else { - return NapiGetboolean(env, false); + ret = SetNotificationPictureContent(env, basicContent.get(), contentResult); + if (ret) { + napi_set_named_property(env, result, "picture", contentResult); } - } else if (outType == ContentType::NOTIFICATION_CONTENT_CONVERSATION) { - // conversational?: NotificationConversationalContent - OHOS::Notification::NotificationConversationalContent *conversationalContent = - static_cast(basicContent.get()); - napi_value conversationalContentResult = nullptr; - napi_create_object(env, &conversationalContentResult); - if (SetNotificationConversationalContent(env, conversationalContent, conversationalContentResult)) { - napi_set_named_property(env, result, "conversational", conversationalContentResult); - } else { - return NapiGetboolean(env, false); + } else if (type == ContentType::NOTIFICATION_CONTENT_CONVERSATION) { + // conversation?: NotificationConversationalContent + ret = SetNotificationConversationalContent(env, basicContent.get(), contentResult); + if (ret) { + napi_set_named_property(env, result, "conversation", contentResult); } - } else if (outType == ContentType::NOTIFICATION_CONTENT_MULTILINE) { + } else if (type == ContentType::NOTIFICATION_CONTENT_MULTILINE) { // multiLine?: NotificationMultiLineContent - OHOS::Notification::NotificationMultiLineContent *multiLineContent = - static_cast(basicContent.get()); - napi_value multiLineContentResult = nullptr; - napi_create_object(env, &multiLineContentResult); - if (SetNotificationMultiLineContent(env, multiLineContent, multiLineContentResult)) { - napi_set_named_property(env, result, "multiLine", multiLineContentResult); - } else { - return NapiGetboolean(env, false); + ret = SetNotificationMultiLineContent(env, basicContent.get(), contentResult); + if (ret) { + napi_set_named_property(env, result, "multiLine", contentResult); } } else { ANS_LOGE("ContentType is does not exist"); - return NapiGetboolean(env, false); } - return NapiGetboolean(env, true); + return ret; +} + +napi_value Common::SetNotificationContent( + const napi_env &env, const std::shared_ptr &content, napi_value &result) +{ + ANS_LOGI("enter"); + napi_value value = nullptr; + if (content == nullptr) { + ANS_LOGE("content is null"); + return NapiGetBoolean(env, false); + } + + // contentType: ContentType + NotificationContent::Type type = content->GetContentType(); + ContentType outType = ContentType::NOTIFICATION_CONTENT_BASIC_TEXT; + if (!ContentTypeCToJS(type, outType)) { + return NapiGetBoolean(env, false); + } + napi_create_int32(env, (int32_t)outType, &value); + napi_set_named_property(env, result, "contentType", value); + + if (!SetNotificationContentDetailed(env, outType, content, result)) { + return NapiGetBoolean(env, false); + } + + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationBasicContent( - const napi_env &env, NotificationBasicContent *basicContent, napi_value &result) + const napi_env &env, const NotificationBasicContent *basicContent, napi_value &result) { - ANS_LOGI("SetNotificationBasicContent start"); + ANS_LOGI("enter"); + napi_value value = nullptr; if (basicContent == nullptr) { ANS_LOGE("basicContent is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; - // title: string napi_create_string_utf8(env, basicContent->GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "title", value); @@ -690,25 +868,31 @@ napi_value Common::SetNotificationBasicContent( napi_create_string_utf8(env, basicContent->GetAdditionalText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "additionalText", value); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationLongTextContent( - const napi_env &env, OHOS::Notification::NotificationLongTextContent *longTextContent, napi_value &result) + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result) { - ANS_LOGI("SetNotificationLongTextContent start"); + ANS_LOGI("enter"); + napi_value value = nullptr; + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return NapiGetBoolean(env, false); + } + + OHOS::Notification::NotificationLongTextContent *longTextContent = + static_cast(basicContent); if (longTextContent == nullptr) { ANS_LOGE("longTextContent is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } if (!SetNotificationBasicContent(env, longTextContent, result)) { ANS_LOGE("SetNotificationBasicContent call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; - // longText: string napi_create_string_utf8(env, longTextContent->GetLongText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "longText", value); @@ -721,25 +905,30 @@ napi_value Common::SetNotificationLongTextContent( napi_create_string_utf8(env, longTextContent->GetExpandedTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "expandedTitle", value); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationPictureContent( - const napi_env &env, OHOS::Notification::NotificationPictureContent *pictureContent, napi_value &result) + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result) { - ANS_LOGI("SetNotificationPictureContent start"); + ANS_LOGI("enter"); + napi_value value = nullptr; + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return NapiGetBoolean(env, false); + } + OHOS::Notification::NotificationPictureContent *pictureContent = + static_cast(basicContent); if (pictureContent == nullptr) { ANS_LOGE("pictureContent is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } if (!SetNotificationBasicContent(env, pictureContent, result)) { ANS_LOGE("SetNotificationBasicContent call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; - // briefText: string napi_create_string_utf8(env, pictureContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "briefText", value); @@ -756,30 +945,36 @@ napi_value Common::SetNotificationPictureContent( pictureResult = Media::PixelMapNapi::CreatePixelMap(env, picture); NAPI_CALL(env, napi_typeof(env, pictureResult, &valuetype)); if (valuetype == napi_undefined) { - ANS_LOGI("pictureResult is undefined"); + ANS_LOGW("pictureResult is undefined"); napi_set_named_property(env, result, "picture", NapiGetNull(env)); } else { napi_set_named_property(env, result, "picture", pictureResult); } } - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationConversationalContent(const napi_env &env, - OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &result) + NotificationBasicContent *basicContent, napi_value &result) { - ANS_LOGI("SetNotificationConversationalContent start"); + ANS_LOGI("enter"); + napi_value value = nullptr; + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return NapiGetBoolean(env, false); + } + OHOS::Notification::NotificationConversationalContent *conversationalContent = + static_cast(basicContent); if (conversationalContent == nullptr) { ANS_LOGE("conversationalContent is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } if (!SetNotificationBasicContent(env, conversationalContent, result)) { ANS_LOGE("SetNotificationBasicContent call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; // conversationTitle: string napi_create_string_utf8(env, conversationalContent->GetConversationTitle().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "conversationTitle", value); @@ -790,20 +985,9 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, // messages: Array napi_value arr = nullptr; - int count = 0; - napi_create_array(env, &arr); - std::vector> messages = - conversationalContent->GetAllConversationalMessages(); - for (auto vec : messages) { - if (!vec) { - continue; - } - napi_value conversationalMessageResult = nullptr; - napi_create_object(env, &conversationalMessageResult); - if (SetConversationalMessage(env, vec, conversationalMessageResult)) { - napi_set_element(env, arr, count, conversationalMessageResult); - count++; - } + if (!SetConversationalMessages(env, conversationalContent, arr)) { + ANS_LOGE("SetConversationalMessages call failed"); + return NapiGetBoolean(env, false); } napi_set_named_property(env, result, "messages", arr); @@ -811,28 +995,35 @@ napi_value Common::SetNotificationConversationalContent(const napi_env &env, napi_value messageUserResult = nullptr; napi_create_object(env, &messageUserResult); if (!SetMessageUser(env, conversationalContent->GetMessageUser(), messageUserResult)) { - messageUserResult = NapiGetNull(env); + ANS_LOGE("SetMessageUser call failed"); + return NapiGetBoolean(env, false); } napi_set_named_property(env, result, "user", messageUserResult); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationMultiLineContent( - const napi_env &env, OHOS::Notification::NotificationMultiLineContent *multiLineContent, napi_value &result) + const napi_env &env, NotificationBasicContent *basicContent, napi_value &result) { - ANS_LOGI("SetNotificationMultiLineContent start"); + ANS_LOGI("enter"); + napi_value value = nullptr; + if (basicContent == nullptr) { + ANS_LOGE("basicContent is null"); + return NapiGetBoolean(env, false); + } + OHOS::Notification::NotificationMultiLineContent *multiLineContent = + static_cast(basicContent); if (multiLineContent == nullptr) { ANS_LOGE("multiLineContent is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } if (!SetNotificationBasicContent(env, multiLineContent, result)) { ANS_LOGE("SetNotificationBasicContent call failed"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; // briefText: string napi_create_string_utf8(env, multiLineContent->GetBriefText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "briefText", value); @@ -852,47 +1043,90 @@ napi_value Common::SetNotificationMultiLineContent( } napi_set_named_property(env, result, "lines", arr); - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetMessageUser(const napi_env &env, const MessageUser &messageUser, napi_value &result) { - ANS_LOGI("SetMessageUser start"); + ANS_LOGI("enter"); napi_value value = nullptr; // name: string napi_create_string_utf8(env, messageUser.GetName().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "name", value); + // key: string + napi_create_string_utf8(env, messageUser.GetKey().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "key", value); + // uri: string napi_create_string_utf8(env, messageUser.GetUri().ToString().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "uri", value); - // important: boolean + // isMachine: boolean + napi_get_boolean(env, messageUser.IsMachine(), &value); + napi_set_named_property(env, result, "isMachine", value); + + // isUserImportant: boolean napi_get_boolean(env, messageUser.IsUserImportant(), &value); - napi_set_named_property(env, result, "important", value); + napi_set_named_property(env, result, "isUserImportant", value); - // machine: boolean - napi_get_boolean(env, messageUser.IsMachine(), &value); - napi_set_named_property(env, result, "machine", value); + // icon?: image.PixelMap + std::shared_ptr icon = messageUser.GetPixelMap(); + if (icon) { + napi_value iconResult = nullptr; + napi_valuetype valuetype = napi_undefined; + iconResult = Media::PixelMapNapi::CreatePixelMap(env, icon); + NAPI_CALL(env, napi_typeof(env, iconResult, &valuetype)); + if (valuetype == napi_undefined) { + ANS_LOGW("iconResult is undefined"); + napi_set_named_property(env, result, "icon", NapiGetNull(env)); + } else { + napi_set_named_property(env, result, "icon", iconResult); + } + } + return NapiGetBoolean(env, true); +} - // key: string - napi_create_string_utf8(env, messageUser.GetKey().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "key", value); +napi_value Common::SetConversationalMessages(const napi_env &env, + const OHOS::Notification::NotificationConversationalContent *conversationalContent, napi_value &arr) +{ + ANS_LOGI("enter"); + if (!conversationalContent) { + ANS_LOGE("conversationalContent is null"); + return NapiGetBoolean(env, false); + } - return NapiGetboolean(env, true); + int count = 0; + napi_create_array(env, &arr); + std::vector> messages = + conversationalContent->GetAllConversationalMessages(); + for (auto vec : messages) { + if (!vec) { + continue; + } + napi_value conversationalMessageResult = nullptr; + napi_create_object(env, &conversationalMessageResult); + if (!SetConversationalMessage(env, vec, conversationalMessageResult)) { + ANS_LOGE("SetConversationalMessage call failed"); + return NapiGetBoolean(env, false); + } + napi_set_element(env, arr, count, conversationalMessageResult); + count++; + } + return NapiGetBoolean(env, true); } napi_value Common::SetConversationalMessage(const napi_env &env, const std::shared_ptr &conversationalMessage, napi_value &result) { - ANS_LOGI("SetConversationalMessage start"); + ANS_LOGI("enter"); + napi_value value = nullptr; if (conversationalMessage == nullptr) { - ANS_LOGE("SetConversationalMessage is null"); - return NapiGetboolean(env, false); + ANS_LOGE("conversationalMessage is null"); + return NapiGetBoolean(env, false); } - napi_value value = nullptr; // text: string napi_create_string_utf8(env, conversationalMessage->GetText().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "text", value); @@ -901,6 +1135,15 @@ napi_value Common::SetConversationalMessage(const napi_env &env, napi_create_int64(env, conversationalMessage->GetArrivedTime(), &value); napi_set_named_property(env, result, "timestamp", value); + // sender: MessageUser + napi_value messageUserResult = nullptr; + napi_create_object(env, &messageUserResult); + if (!SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { + ANS_LOGE("SetMessageUser call failed"); + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "sender", messageUserResult); + // mimeType: string napi_create_string_utf8(env, conversationalMessage->GetMimeType().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "mimeType", value); @@ -909,24 +1152,16 @@ napi_value Common::SetConversationalMessage(const napi_env &env, napi_create_string_utf8(env, conversationalMessage->GetUri()->ToString().c_str(), NAPI_AUTO_LENGTH, &value); napi_set_named_property(env, result, "uri", value); - // sender: MessageUser - napi_value messageUserResult = nullptr; - napi_create_object(env, &messageUserResult); - if (SetMessageUser(env, conversationalMessage->GetSender(), messageUserResult)) { - messageUserResult = NapiGetNull(env); - } - napi_set_named_property(env, result, "sender", messageUserResult); - - return NapiGetboolean(env, true); + return NapiGetBoolean(env, true); } napi_value Common::SetNotificationActionButton( const napi_env &env, const std::shared_ptr &actionButton, napi_value &result) { - ANS_LOGI("SetNotificationActionButton start"); + ANS_LOGI("enter"); if (actionButton == nullptr) { ANS_LOGE("actionButton is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } napi_value value = nullptr; @@ -940,7 +1175,7 @@ napi_value Common::SetNotificationActionButton( if (agent == nullptr) { ANS_LOGI("wantAgent is null"); napi_set_named_property(env, result, "wantAgent", NapiGetNull(env)); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } napi_value wantAgent = nullptr; wantAgent = CreateWantAgentByJS(env, agent); @@ -954,28 +1189,155 @@ napi_value Common::SetNotificationActionButton( iconResult = Media::PixelMapNapi::CreatePixelMap(env, icon); NAPI_CALL(env, napi_typeof(env, iconResult, &valuetype)); if (valuetype == napi_undefined) { - ANS_LOGI("iconResult is undefined"); + ANS_LOGW("iconResult is undefined"); napi_set_named_property(env, result, "icon", NapiGetNull(env)); } else { napi_set_named_property(env, result, "icon", iconResult); } } - return NapiGetboolean(env, true); + + if (!SetNotificationActionButtonByExtras(env, actionButton, result)) { + return NapiGetBoolean(env, false); + } + + // userInput?: NotificationUserInput + if (actionButton->GetUserInputs().size() > 0) { + napi_value userInputResult = nullptr; + napi_create_object(env, &userInputResult); + if (!SetNotificationActionButtonByUserInput(env, actionButton->GetUserInputs().front(), userInputResult)) { + return NapiGetBoolean(env, false); + } + napi_set_named_property(env, result, "userInput", userInputResult); + } + + return NapiGetBoolean(env, true); } -napi_value Common::GetNotificationSubscriberInfo( - const napi_env &env, const napi_value &value, NotificationSubscribeInfo &subscriberInfo) +napi_value Common::SetNotificationActionButtonByExtras( + const napi_env &env, const std::shared_ptr &actionButton, napi_value &result) { - uint32_t length = 0; - size_t strLen = 0; - bool hasProperty = false; - bool isArray = false; - napi_valuetype valuetype = napi_undefined; + ANS_LOGI("enter"); + if (!actionButton) { + ANS_LOGE("actionButton is null"); + return NapiGetBoolean(env, false); + } + // extras?: {[key: string]: any} + auto extras = actionButton->GetAdditionalData(); + if (extras) { + napi_value nExtras = nullptr; + nExtras = OHOS::AppExecFwk::WrapWantParams(env, *extras); + napi_set_named_property(env, result, "extras", nExtras); + } + return NapiGetBoolean(env, true); +} - // bundleNames?: Array - NAPI_CALL(env, napi_has_named_property(env, value, "bundleNames", &hasProperty)); - if (hasProperty) { - napi_value nBundleNames = nullptr; +napi_value Common::SetNotificationActionButtonByUserInput( + const napi_env &env, const std::shared_ptr &userInput, napi_value &result) +{ + ANS_LOGI("enter"); + + if (!userInput) { + ANS_LOGE("userInput is null"); + return NapiGetBoolean(env, false); + } + + napi_value value = nullptr; + napi_value arr = nullptr; + int count = 0; + + // inputKey: string + napi_create_string_utf8(env, userInput->GetInputKey().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "inputKey", value); + + // tag: string + napi_create_string_utf8(env, userInput->GetTag().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "tag", value); + + // options: Array + napi_create_array(env, &arr); + for (auto vec : userInput->GetOptions()) { + napi_create_string_utf8(env, vec.c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_element(env, arr, count, value); + count++; + } + if (count > 0) { + napi_set_named_property(env, result, "options", arr); + } + + // permitFreeFormInput?: boolean + napi_get_boolean(env, userInput->IsPermitFreeFormInput(), &value); + napi_set_named_property(env, result, "permitFreeFormInput", value); + + // permitMimeTypes?: Array + count = 0; + napi_create_array(env, &arr); + for (auto vec : userInput->GetPermitMimeTypes()) { + napi_create_string_utf8(env, vec.c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_element(env, arr, count, value); + count++; + } + if (count > 0) { + napi_set_named_property(env, result, "permitMimeTypes", arr); + } + + // editType?: number + napi_create_int64(env, userInput->GetEditType(), &value); + napi_set_named_property(env, result, "editType", value); + + // additionalData?: {[key: string]: Object} + auto additionalData = userInput->GetAdditionalData(); + if (additionalData) { + napi_value nAdditionalData = nullptr; + nAdditionalData = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); + napi_set_named_property(env, result, "additionalData", nAdditionalData); + } + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetDoNotDisturbDate( + const napi_env &env, const NotificationDoNotDisturbDate &date, napi_value &result) +{ + ANS_LOGI("enter"); + DoNotDisturbType outType = DoNotDisturbType::TYPE_NONE; + if (!DoNotDisturbTypeCToJS(date.GetDoNotDisturbType(), outType)) { + return NapiGetBoolean(env, false); + } + + // type:DoNotDisturbType + napi_value typeNapi = nullptr; + napi_create_int32(env, (int32_t)outType, &typeNapi); + napi_set_named_property(env, result, "type", typeNapi); + + // begin:Date + double begind = double(date.GetBeginDate()); + napi_value beginNapi = nullptr; + napi_create_date(env, begind, &beginNapi); + napi_set_named_property(env, result, "begin", beginNapi); + + // end:Date + double endd = double(date.GetEndDate()); + napi_value endNapi = nullptr; + napi_create_date(env, endd, &endNapi); + napi_set_named_property(env, result, "end", endNapi); + + return NapiGetBoolean(env, true); +} + +napi_value Common::GetNotificationSubscriberInfo( + const napi_env &env, const napi_value &value, NotificationSubscribeInfo &subscriberInfo) +{ + ANS_LOGI("enter"); + uint32_t length = 0; + size_t strLen = 0; + bool hasProperty = false; + bool isArray = false; + napi_valuetype valuetype = napi_undefined; + + // bundleNames?: Array + NAPI_CALL(env, napi_has_named_property(env, value, "bundleNames", &hasProperty)); + if (hasProperty) { + napi_value nBundleNames = nullptr; napi_get_named_property(env, value, "bundleNames", &nBundleNames); napi_is_array(env, nBundleNames, &isArray); NAPI_ASSERT(env, isArray, "Property bundleNames is expected to be an array."); @@ -1007,139 +1369,165 @@ napi_value Common::GetNotificationSubscriberInfo( return NapiGetNull(env); } -napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationRequestByNumber( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); - - // content: NotificationContent - if (GetNotificationContent(env, value, request) == nullptr) { - return nullptr; - } - // id?: number - if (GetIdByPublish(env, value, request) == nullptr) { - return nullptr; - } - - // slotType?: notification.SlotType - if (GetSlotType(env, value, request) == nullptr) { + if (GetNotificationId(env, value, request) == nullptr) { return nullptr; } - - // isOngoing?: boolean - if (GetNotificationIsOngoing(env, value, request) == nullptr) { + // deliveryTime?: number + if (GetNotificationDeliveryTime(env, value, request) == nullptr) { return nullptr; } - - // isUnremovable?: boolean - if (GetNotificationIsUnremovable(env, value, request) == nullptr) { + // autoDeletedTime?: number + if (GetNotificationAutoDeletedTime(env, value, request) == nullptr) { return nullptr; } - - // deliveryTime?: number - if (GetNotificationDeliveryTime(env, value, request) == nullptr) { + // color?: number + if (GetNotificationColor(env, value, request) == nullptr) { return nullptr; } - - // tapDismissed?: boolean - if (GetNotificationtapDismissed(env, value, request) == nullptr) { + // badgeIconStyle?: number + if (GetNotificationBadgeIconStyle(env, value, request) == nullptr) { return nullptr; } + return NapiGetNull(env); +} - // wantAgent?: WantAgent - if (GetNotificationWantAgent(env, value, request) == nullptr) { +napi_value Common::GetNotificationRequestByString( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + // classification?: string + if (GetNotificationClassification(env, value, request) == nullptr) { return nullptr; } - - // extraInfo?: {[key: string]: any} - if (GetNotificationExtraInfo(env, value, request) == nullptr) { + // statusBarText?: string + if (GetNotificationStatusBarText(env, value, request) == nullptr) { return nullptr; } - - // removalWantAgent?: WantAgent - if (GetNotificationRemovalWantAgent(env, value, request) == nullptr) { + // label?: string + if (GetNotificationLabel(env, value, request) == nullptr) { return nullptr; } - - // maxScreenWantAgent?: WantAgent - if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { + // groupName?: string + if (GetNotificationGroupName(env, value, request) == nullptr) { return nullptr; } + return NapiGetNull(env); +} - // autoDeletedTime?: number - if (GetNotificationAutoDeletedTime(env, value, request) == nullptr) { +napi_value Common::GetNotificationRequestByBool( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + // isOngoing?: boolean + if (GetNotificationIsOngoing(env, value, request) == nullptr) { return nullptr; } - - // classification?: string - if (GetNotificationClassification(env, value, request) == nullptr) { + // isUnremovable?: boolean + if (GetNotificationIsUnremovable(env, value, request) == nullptr) { return nullptr; } - - // color?: number - if (GetNotificationColor(env, value, request) == nullptr) { + // tapDismissed?: boolean + if (GetNotificationtapDismissed(env, value, request) == nullptr) { return nullptr; } - // colorEnabled?: boolean if (GetNotificationColorEnabled(env, value, request) == nullptr) { return nullptr; } - // isAlertOnce?: boolean if (GetNotificationIsAlertOnce(env, value, request) == nullptr) { return nullptr; } - // isStopwatch?: boolean if (GetNotificationIsStopwatch(env, value, request) == nullptr) { return nullptr; } - // isCountDown?: boolean if (GetNotificationIsCountDown(env, value, request) == nullptr) { return nullptr; } - - // statusBarText?: string - if (GetNotificationStatusBarText(env, value, request) == nullptr) { + // showDeliveryTime?: boolean + if (GetNotificationShowDeliveryTime(env, value, request) == nullptr) { return nullptr; } + return NapiGetNull(env); +} - // label?: string - if (GetNotificationLabel(env, value, request) == nullptr) { +napi_value Common::GetNotificationRequestByCustom( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + // content: NotificationContent + if (GetNotificationContent(env, value, request) == nullptr) { return nullptr; } - - // badgeIconStyle?: number - if (GetNotificationBadgeIconStyle(env, value, request) == nullptr) { + // slotType?: notification.SlotType + if (GetNotificationSlotType(env, value, request) == nullptr) { return nullptr; } - - // showDeliveryTime?: boolean - if (GetNotificationShowDeliveryTime(env, value, request) == nullptr) { + // wantAgent?: WantAgent + if (GetNotificationWantAgent(env, value, request) == nullptr) { + return nullptr; + } + // extraInfo?: {[key: string]: any} + if (GetNotificationExtraInfo(env, value, request) == nullptr) { + return nullptr; + } + // removalWantAgent?: WantAgent + if (GetNotificationRemovalWantAgent(env, value, request) == nullptr) { + return nullptr; + } + // maxScreenWantAgent?: WantAgent + if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { return nullptr; } - // actionButtons?: Array - if (GetNotificationNotificationActionButtons(env, value, request) == nullptr) { + if (GetNotificationActionButtons(env, value, request) == nullptr) { return nullptr; } - // smallIcon?: image.PixelMap if (GetNotificationSmallIcon(env, value, request) == nullptr) { return nullptr; } - // largeIcon?: image.PixelMap if (GetNotificationLargeIcon(env, value, request) == nullptr) { return nullptr; } + // distributedOption?:DistributedOptions + if (GetNotificationRequestDistributedOptions(env, value, request) == nullptr) { + return nullptr; + } + // template?: NotificationTemplate + if (GetNotificationTemplate(env, value, request) == nullptr) { + return nullptr; + } + return NapiGetNull(env); +} - return Common::NapiGetNull(env); +napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + if (!GetNotificationRequestByNumber(env, value, request)) { + return nullptr; + } + if (!GetNotificationRequestByString(env, value, request)) { + return nullptr; + } + if (!GetNotificationRequestByBool(env, value, request)) { + return nullptr; + } + if (!GetNotificationRequestByCustom(env, value, request)) { + return nullptr; + } + return NapiGetNull(env); } -napi_value GetIdByPublish(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationId(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1155,16 +1543,16 @@ napi_value GetIdByPublish(const napi_env &env, const napi_value &value, Notifica NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, result, ¬ificationId); request.SetNotificationId(notificationId); - ANS_LOGI("============GetIdByPublish notificationId = %{public}d", notificationId); + ANS_LOGI("notificationId = %{public}d", notificationId); } else { + ANS_LOGI("default notificationId = 0"); request.SetNotificationId(0); } - ANS_LOGI("end"); - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationSlotType(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1180,17 +1568,18 @@ napi_value GetSlotType(const napi_env &env, const napi_value &value, Notificatio NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, result, &slotType); - enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + if (!SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } request.SetSlotType(outType); - ANS_LOGI("============GetSlotType slotType = %{public}d", slotType); + ANS_LOGI("slotType = %{public}d", slotType); } else { + ANS_LOGI("default slotType = OTHER"); request.SetSlotType(NotificationConstant::OTHER); } - ANS_LOGI("end"); - return Common::NapiGetNull(env); + + return NapiGetNull(env); } napi_value Common::GetNotificationContent(const napi_env &env, const napi_value &value, NotificationRequest &request) @@ -1203,10 +1592,7 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value int32_t type = 0; NAPI_CALL(env, napi_has_named_property(env, value, "content", &hasProperty)); - if (!hasProperty) { - ANS_LOGE("Property content expected."); - return nullptr; - } + NAPI_ASSERT(env, hasProperty, "Property content expected."); napi_get_named_property(env, value, "content", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); @@ -1244,18 +1630,14 @@ napi_value Common::GetNotificationContent(const napi_env &env, const napi_value return nullptr; } break; - case NotificationContent::Type::MEDIA: - break; default: return nullptr; - break; } - ANS_LOGI("end"); - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationIsOngoing(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1273,10 +1655,11 @@ napi_value GetNotificationIsOngoing(const napi_env &env, const napi_value &value request.SetInProgress(isOngoing); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationIsUnremovable(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationIsUnremovable( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1294,10 +1677,11 @@ napi_value GetNotificationIsUnremovable(const napi_env &env, const napi_value &v request.SetUnremovable(isUnremovable); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationDeliveryTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1315,10 +1699,11 @@ napi_value GetNotificationDeliveryTime(const napi_env &env, const napi_value &va request.SetDeliveryTime(deliveryTime); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationtapDismissed(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationtapDismissed( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1336,7 +1721,7 @@ napi_value GetNotificationtapDismissed(const napi_env &env, const napi_value &va request.SetTapDismissed(tapDismissed); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) @@ -1362,10 +1747,10 @@ napi_value Common::GetNotificationWantAgent(const napi_env &env, const napi_valu request.SetWantAgent(sWantAgent); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationExtraInfo(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1387,10 +1772,33 @@ napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value request.SetAdditionalData(extras); } - return Common::NapiGetNull(env); + return NapiGetNull(env); +} + +napi_value Common::GetNotificationGroupName(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, value, "groupName", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "groupName", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + request.SetGroupName(str); + } + + return NapiGetNull(env); } -napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationRemovalWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1413,10 +1821,11 @@ napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value request.SetRemovalWantAgent(removeWantAgent); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationMaxScreenWantAgent( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1439,10 +1848,11 @@ napi_value GetNotificationMaxScreenWantAgent(const napi_env &env, const napi_val request.SetMaxScreenWantAgent(maxScreenWantAgent); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationAutoDeletedTime( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1460,10 +1870,11 @@ napi_value GetNotificationAutoDeletedTime(const napi_env &env, const napi_value request.SetAutoDeletedTime(autoDeletedTime); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationClassification(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationClassification( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1482,10 +1893,10 @@ napi_value GetNotificationClassification(const napi_env &env, const napi_value & request.SetClassification(str); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationColor(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1504,10 +1915,11 @@ napi_value GetNotificationColor(const napi_env &env, const napi_value &value, No request.SetColor(color); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationColorEnabled(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationColorEnabled( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1525,10 +1937,11 @@ napi_value GetNotificationColorEnabled(const napi_env &env, const napi_value &va request.SetColorEnabled(colorEnabled); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationIsAlertOnce(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationIsAlertOnce( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1546,10 +1959,11 @@ napi_value GetNotificationIsAlertOnce(const napi_env &env, const napi_value &val request.SetAlertOneTime(isAlertOnce); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationIsStopwatch(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationIsStopwatch( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1567,10 +1981,11 @@ napi_value GetNotificationIsStopwatch(const napi_env &env, const napi_value &val request.SetShowStopwatch(isStopwatch); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationIsCountDown( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1588,10 +2003,11 @@ napi_value GetNotificationIsCountDown(const napi_env &env, const napi_value &val request.SetCountdownTimer(isCountDown); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationStatusBarText( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1610,10 +2026,10 @@ napi_value GetNotificationStatusBarText(const napi_env &env, const napi_value &v request.SetStatusBarText(str); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationLabel(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1632,10 +2048,11 @@ napi_value GetNotificationLabel(const napi_env &env, const napi_value &value, No request.SetLabel(str); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationBadgeIconStyle( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1653,10 +2070,11 @@ napi_value GetNotificationBadgeIconStyle(const napi_env &env, const napi_value & request.SetBadgeIconStyle(static_cast(badgeIconStyle)); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationShowDeliveryTime( + const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1674,10 +2092,10 @@ napi_value GetNotificationShowDeliveryTime(const napi_env &env, const napi_value request.SetShowDeliveryTime(showDeliveryTime); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationNotificationActionButtons( +napi_value Common::GetNotificationActionButtons( const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1685,17 +2103,8 @@ napi_value GetNotificationNotificationActionButtons( bool isArray = false; napi_valuetype valuetype = napi_undefined; napi_value actionButtons = nullptr; - char str[STR_MAX_SIZE] = {0}; - size_t strLen = 0; uint32_t length = 0; bool hasProperty = false; - napi_value titelActionButton = nullptr; - napi_value wantAgentActionButton = nullptr; - napi_value iconActionButton = nullptr; - std::string title; - WantAgent::WantAgent *wantAgentPtr = nullptr; - std::shared_ptr pixelMap = nullptr; - std::shared_ptr wantAgent; napi_has_named_property(env, value, "actionButtons", &hasProperty); if (!hasProperty) { @@ -1713,82 +2122,88 @@ napi_value GetNotificationNotificationActionButtons( NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - // title: string - NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, actionButton, "title", &titelActionButton); - NAPI_CALL(env, napi_typeof(env, titelActionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, titelActionButton, str, STR_MAX_SIZE - 1, &strLen)); - title = str; - } else { - ANS_LOGE("Property title expected."); - return nullptr; - } - - // wantAgent: WantAgent - NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, actionButton, "wantAgent", &wantAgentActionButton); - NAPI_CALL(env, napi_typeof(env, wantAgentActionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - napi_unwrap(env, wantAgentActionButton, (void **)&wantAgentPtr); - if (wantAgentPtr == nullptr) { - ANS_LOGE("Invalid object wantAgent"); - return nullptr; - } - wantAgent = std::make_shared(*wantAgentPtr); - } else { - ANS_LOGE("Property wantAgent expected."); + std::shared_ptr pActionButton = nullptr; + if (GetNotificationActionButtonsDetailed(env, actionButton, pActionButton) == nullptr) { return nullptr; } - - // icon?: image.PixelMap - NAPI_CALL(env, napi_has_named_property(env, actionButton, "icon", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, actionButton, "icon", &iconActionButton); - NAPI_CALL(env, napi_typeof(env, iconActionButton, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - pixelMap = Media::PixelMapNapi::GetPixelMap(env, iconActionButton); - if (pixelMap == nullptr) { - ANS_LOGE("Invalid object pixelMap"); - return nullptr; - } - } - - auto pActionButton = NotificationActionButton::Create(pixelMap, title, wantAgent); request.AddActionButton(pActionButton); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationSmallIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationActionButtonsDetailed( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton) { ANS_LOGI("enter"); + if (!GetNotificationActionButtonsDetailedBasicInfo(env, actionButton, pActionButton)) { + return nullptr; + } + if (!GetNotificationActionButtonsDetailedByExtras(env, actionButton, pActionButton)) { + return nullptr; + } + if (!GetNotificationUserInput(env, actionButton, pActionButton)) { + return nullptr; + } + return NapiGetNull(env); +} + +napi_value Common::GetNotificationActionButtonsDetailedBasicInfo( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton) +{ + ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; - napi_value result = nullptr; bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + napi_value value = nullptr; + std::string title; + WantAgent::WantAgent *wantAgentPtr = nullptr; + std::shared_ptr pixelMap = nullptr; + std::shared_ptr wantAgent; - NAPI_CALL(env, napi_has_named_property(env, value, "smallIcon", &hasProperty)); + // title: string + NAPI_CALL(env, napi_has_named_property(env, actionButton, "title", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property title expected."); + napi_get_named_property(env, actionButton, "title", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + title = str; + + // wantAgent: WantAgent + NAPI_CALL(env, napi_has_named_property(env, actionButton, "wantAgent", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property wantAgent expected."); + napi_get_named_property(env, actionButton, "wantAgent", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + napi_unwrap(env, value, (void **)&wantAgentPtr); + if (wantAgentPtr == nullptr) { + ANS_LOGE("Invalid object wantAgent"); + return nullptr; + } + wantAgent = std::make_shared(*wantAgentPtr); + + // icon?: image.PixelMap + NAPI_CALL(env, napi_has_named_property(env, actionButton, "icon", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, value, "smallIcon", &result); - NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + napi_get_named_property(env, actionButton, "icon", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr pixelMap = nullptr; - pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); + pixelMap = Media::PixelMapNapi::GetPixelMap(env, value); if (pixelMap == nullptr) { ANS_LOGE("Invalid object pixelMap"); return nullptr; } - request.SetLittleIcon(pixelMap); } + pActionButton = NotificationActionButton::Create(pixelMap, title, wantAgent); - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationLargeIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationActionButtonsDetailedByExtras( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton) { ANS_LOGI("enter"); @@ -1796,484 +2211,962 @@ napi_value GetNotificationLargeIcon(const napi_env &env, const napi_value &value napi_value result = nullptr; bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, value, "largeIcon", &hasProperty)); + if (!pActionButton) { + ANS_LOGE("pActionButton is nullptr"); + return nullptr; + } + + // extras?: {[key: string]: any} + NAPI_CALL(env, napi_has_named_property(env, actionButton, "extras", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, value, "largeIcon", &result); + napi_get_named_property(env, actionButton, "extras", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr pixelMap = nullptr; - pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); - if (pixelMap == nullptr) { - ANS_LOGE("Invalid object pixelMap"); + AAFwk::WantParams wantParams; + if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { return nullptr; } - request.SetBigIcon(pixelMap); + pActionButton->AddAdditionalData(wantParams); } - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type) +napi_value Common::GetNotificationUserInput( + const napi_env &env, const napi_value &actionButton, std::shared_ptr &pActionButton) { ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; + napi_value userInputResult = nullptr; + bool hasProperty = false; - napi_value contentResult = nullptr; + // userInput?: NotificationUserInput + NAPI_CALL(env, napi_has_named_property(env, actionButton, "userInput", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, actionButton, "userInput", &userInputResult); + NAPI_CALL(env, napi_typeof(env, userInputResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr userInput = nullptr; + + if (!GetNotificationUserInputByInputKey(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByTag(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByOptions(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByPermitFreeFormInput(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByPermitMimeTypes(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByEditType(env, userInputResult, userInput)) { + return nullptr; + } + if (!GetNotificationUserInputByAdditionalData(env, userInputResult, userInput)) { + return nullptr; + } + pActionButton->AddNotificationUserInput(userInput); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationUserInputByInputKey( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) +{ + ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; + napi_value value = nullptr; bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; - NAPI_CALL(env, napi_has_named_property(env, result, "contentType", &hasProperty)); - if (!hasProperty) { - ANS_LOGE("Property contentType expected."); + // inputKey: string + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "inputKey", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property inputKey expected."); + napi_get_named_property(env, userInputResult, "inputKey", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + ANS_LOGI("NotificationUserInput::inputKey = %{public}s", str); + userInput = NotificationUserInput::Create(str); + if (!userInput) { + ANS_LOGI("Failed to create NotificationUserInput by inputKey=%{public}s", str); return nullptr; } - napi_get_named_property(env, result, "contentType", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, contentResult, &type); - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +napi_value Common::GetNotificationUserInputByTag( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; - napi_value contentResult = nullptr; - napi_value basicContentResult = nullptr; + napi_value value = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - NAPI_CALL(env, napi_has_named_property(env, result, "normal", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property normal expected."); - napi_get_named_property(env, result, "normal", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - - std::shared_ptr normalContent = std::make_shared(); - if (normalContent == nullptr) { - ANS_LOGE("normalContent is null"); + if (!userInput) { + ANS_LOGE("userInput is nullptr"); return nullptr; } - // title: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - normalContent->SetTitle(str); - ANS_LOGI("normal::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); - return nullptr; - } + // tag: string + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "tag", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property tag expected."); + napi_get_named_property(env, userInputResult, "tag", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + userInput->SetTag(str); + ANS_LOGI("NotificationUserInput::tag = %{public}s", str); - // text: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - normalContent->SetText(str); - ANS_LOGI("normal::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); + return NapiGetNull(env); +} + +napi_value Common::GetNotificationUserInputByOptions( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value value = nullptr; + bool hasProperty = false; + size_t strLen = 0; + uint32_t length = 0; + bool isArray = false; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); return nullptr; } - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + // options: Array + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "options", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property options expected."); + napi_get_named_property(env, userInputResult, "options", &value); + napi_is_array(env, value, &isArray); + NAPI_ASSERT(env, isArray, "Property options is expected to be an array."); + napi_get_array_length(env, value, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + std::vector options; + for (uint32_t i = 0; i < length; ++i) { + napi_value option = nullptr; + char str[STR_MAX_SIZE] = {0}; + napi_get_element(env, value, i, &option); + NAPI_CALL(env, napi_typeof(env, option, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - normalContent->SetAdditionalText(str); - ANS_LOGI("normal::additionalText = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, option, str, STR_MAX_SIZE - 1, &strLen)); + options.emplace_back(str); } + userInput->SetOptions(options); - request.SetContent(std::make_shared(normalContent)); - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationLongTextContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +napi_value Common::GetNotificationUserInputByPermitMimeTypes( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; - napi_value contentResult = nullptr; - napi_value longContentResult = nullptr; - napi_value basicContentResult = nullptr; + napi_value value = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; - char long_str[LONG_STR_MAX_SIZE + 1] = {0}; size_t strLen = 0; + uint32_t length = 0; + bool isArray = false; - NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property longText expected."); - - napi_get_named_property(env, result, "longText", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - - std::shared_ptr longContent = - std::make_shared(); - if (longContent == nullptr) { - ANS_LOGE("longContent is null"); + if (!userInput) { + ANS_LOGE("userInput is nullptr"); return nullptr; } - // title: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + // permitMimeTypes?: Array + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "permitMimeTypes", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetTitle(str); - ANS_LOGI("longText::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); - return nullptr; + napi_get_named_property(env, userInputResult, "permitMimeTypes", &value); + napi_is_array(env, value, &isArray); + NAPI_ASSERT(env, isArray, "Property options is expected to be an array."); + napi_get_array_length(env, value, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (uint32_t i = 0; i < length; ++i) { + napi_value permitMimeType = nullptr; + char str[STR_MAX_SIZE] = {0}; + napi_get_element(env, value, i, &permitMimeType); + NAPI_CALL(env, napi_typeof(env, permitMimeType, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, permitMimeType, str, STR_MAX_SIZE - 1, &strLen)); + userInput->SetPermitMimeTypes(str, true); + } } - // text: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetText(str); - ANS_LOGI("longText::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); + return NapiGetNull(env); +} + +napi_value Common::GetNotificationUserInputByPermitFreeFormInput( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) +{ + ANS_LOGI("enter"); + napi_value value = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); return nullptr; } - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); + // permitFreeFormInput?: boolean + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "permitFreeFormInput", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetAdditionalText(str); - ANS_LOGI("longText::additionalText = %{public}s", str); + bool permitFreeFormInput = false; + napi_get_named_property(env, userInputResult, "permitFreeFormInput", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, value, &permitFreeFormInput); + ANS_LOGI("permitFreeFormInput is: %{public}d", permitFreeFormInput); + userInput->SetPermitFreeFormInput(permitFreeFormInput); } - // longText: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "longText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "longText", &longContentResult); - NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, long_str, LONG_STR_MAX_SIZE, &strLen)); - longContent->SetLongText(long_str); - ANS_LOGI("longText::longText = %{public}s", long_str); - } else { - ANS_LOGE("Property longText expected."); - return nullptr; - } + return NapiGetNull(env); +} - // briefText: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &longContentResult); - NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetBriefText(str); - ANS_LOGI("longText::briefText = %{public}s", str); - } else { - ANS_LOGE("Property briefText expected."); +napi_value Common::GetNotificationUserInputByEditType( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) +{ + ANS_LOGI("enter"); + napi_value value = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + int32_t editType = 0; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); return nullptr; } - // expandedTitle: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); + // editType?: number + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "editType", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, contentResult, "expandedTitle", &longContentResult); - NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetExpandedTitle(str); - ANS_LOGI("longText::expandedTitle = %{public}s", str); - } else { - ANS_LOGE("Property expandedTitle expected."); - return nullptr; + napi_get_named_property(env, userInputResult, "editType", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, value, &editType); + userInput->SetEditType(NotificationConstant::InputEditType(editType)); } - - request.SetContent(std::make_shared(longContent)); - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationPictureContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +napi_value Common::GetNotificationUserInputByAdditionalData( + const napi_env &env, const napi_value &userInputResult, std::shared_ptr &userInput) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; - napi_value contentResult = nullptr; - napi_value pictureContentResult = nullptr; - napi_value basicContentResult = nullptr; + napi_value result = nullptr; + bool hasProperty = false; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); + return nullptr; + } + + // additionalData?: {[key: string]: Object} + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "additionalData", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, userInputResult, "additionalData", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + AAFwk::WantParams wantParams; + if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { + return nullptr; + } + userInput->AddAdditionalData(wantParams); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSmallIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "smallIcon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "smallIcon", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + request.SetLittleIcon(pixelMap); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationLargeIcon(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "largeIcon", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "largeIcon", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, result); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + request.SetBigIcon(pixelMap); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationRequestDistributedOptions(const napi_env &env, + const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + // distributedOption?: DistributedOptions + NAPI_CALL(env, napi_has_named_property(env, value, "distributedOption", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "distributedOption", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + // isDistributed?: boolean + if (GetNotificationIsDistributed(env, result, request) == nullptr) { + return nullptr; + } + + // supportDisplayDevices?: Array + if (GetNotificationSupportDisplayDevices(env, result, request) == nullptr) { + return nullptr; + } + + // supportOperateDevices?: Array + if (GetNotificationSupportOperateDevices(env, result, request) == nullptr) { + return nullptr; + } + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationIsDistributed( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + bool isDistributed = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "isDistributed", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "isDistributed", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, result, &isDistributed); + request.SetDistributed(isDistributed); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSupportDisplayDevices( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool isArray = false; bool hasProperty = false; + napi_valuetype valuetype = napi_undefined; + napi_value supportDisplayDevices = nullptr; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; + uint32_t length = 0; - NAPI_CALL(env, napi_has_named_property(env, result, "picture", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property picture expected."); - napi_get_named_property(env, result, "picture", &contentResult); + NAPI_CALL(env, napi_has_named_property(env, value, "supportDisplayDevices", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "supportDisplayDevices", &supportDisplayDevices); + napi_is_array(env, supportDisplayDevices, &isArray); + NAPI_ASSERT(env, isArray, "Property supportDisplayDevices is expected to be an array."); + + napi_get_array_length(env, supportDisplayDevices, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + std::vector devices; + for (size_t i = 0; i < length; i++) { + napi_value line = nullptr; + napi_get_element(env, supportDisplayDevices, i, &line); + NAPI_CALL(env, napi_typeof(env, line, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, line, str, STR_MAX_SIZE - 1, &strLen)); + devices.emplace_back(str); + ANS_LOGI("supportDisplayDevices = %{public}s", str); + } + request.SetDevicesSupportDisplay(devices); + } + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSupportOperateDevices( + const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + bool isArray = false; + bool hasProperty = false; + napi_valuetype valuetype = napi_undefined; + napi_value supportOperateDevices = nullptr; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + uint32_t length = 0; + + NAPI_CALL(env, napi_has_named_property(env, value, "supportOperateDevices", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "supportOperateDevices", &supportOperateDevices); + napi_is_array(env, supportOperateDevices, &isArray); + NAPI_ASSERT(env, isArray, "Property supportOperateDevices is expected to be an array."); + + napi_get_array_length(env, supportOperateDevices, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + std::vector devices; + for (size_t i = 0; i < length; i++) { + napi_value line = nullptr; + napi_get_element(env, supportOperateDevices, i, &line); + NAPI_CALL(env, napi_typeof(env, line, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, line, str, STR_MAX_SIZE - 1, &strLen)); + devices.emplace_back(str); + ANS_LOGI("supportOperateDevices = %{public}s", str); + } + request.SetDevicesSupportOperate(devices); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationContentType(const napi_env &env, const napi_value &result, int32_t &type) +{ + ANS_LOGI("enter"); + + napi_value contentResult = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, result, "contentType", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property contentType expected."); + + napi_get_named_property(env, result, "contentType", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, contentResult, &type); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationBasicContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, result, "normal", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property normal expected."); + napi_get_named_property(env, result, "normal", &contentResult); NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr pictureContent = - std::make_shared(); - if (pictureContent == nullptr) { - ANS_LOGE("pictureContent is null"); + std::shared_ptr normalContent = std::make_shared(); + if (normalContent == nullptr) { + ANS_LOGE("normalContent is null"); return nullptr; } - // title: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetTitle(str); - ANS_LOGI("pictureText::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); + if (GetNotificationBasicContentDetailed(env, contentResult, normalContent) == nullptr) { return nullptr; } + request.SetContent(std::make_shared(normalContent)); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationBasicContentDetailed( + const napi_env &env, const napi_value &contentResult, std::shared_ptr basicContent) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value value = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + // title: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property title expected."); + napi_get_named_property(env, contentResult, "title", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + basicContent->SetTitle(str); + ANS_LOGI("normal::title = %{public}s", str); + // text: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetText(str); - ANS_LOGI("pictureText::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); - return nullptr; - } + NAPI_ASSERT(env, hasProperty, "Property text expected."); + napi_get_named_property(env, contentResult, "text", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + basicContent->SetText(str); + ANS_LOGI("normal::text = %{public}s", str); // additionalText?: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); + napi_get_named_property(env, contentResult, "additionalText", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetAdditionalText(str); - ANS_LOGI("pictureText::additionalText = %{public}s", str); + NAPI_CALL(env, napi_get_value_string_utf8(env, value, str, STR_MAX_SIZE - 1, &strLen)); + basicContent->SetAdditionalText(str); + ANS_LOGI("normal::additionalText = %{public}s", str); } - // briefText: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetBriefText(str); - ANS_LOGI("pictureText::briefText = %{public}s", str); - } else { - ANS_LOGE("Property briefText expected."); + return NapiGetNull(env); +} + +napi_value Common::GetNotificationLongTextContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property longText expected."); + + napi_get_named_property(env, result, "longText", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + std::shared_ptr longContent = + std::make_shared(); + if (longContent == nullptr) { + ANS_LOGE("longContent is null"); + return nullptr; + } + + if (GetNotificationLongTextContentDetailed(env, contentResult, longContent) == nullptr) { return nullptr; } + request.SetContent(std::make_shared(longContent)); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationLongTextContentDetailed( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &longContent) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value longContentResult = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + char long_str[LONG_STR_MAX_SIZE + 1] = {0}; + size_t strLen = 0; + + if (GetNotificationBasicContentDetailed(env, contentResult, longContent) == nullptr) { + return nullptr; + } + + // longText: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "longText", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property longText expected."); + napi_get_named_property(env, contentResult, "longText", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, long_str, LONG_STR_MAX_SIZE, &strLen)); + longContent->SetLongText(long_str); + ANS_LOGI("longText::longText = %{public}s", long_str); + + // briefText: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property briefText expected."); + napi_get_named_property(env, contentResult, "briefText", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetBriefText(str); + ANS_LOGI("longText::briefText = %{public}s", str); + // expandedTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetExpandedTitle(str); - ANS_LOGI("pictureText::expandedTitle = %{public}s", str); - } else { - ANS_LOGE("Property expandedTitle expected."); + NAPI_ASSERT(env, hasProperty, "Property expandedTitle expected."); + napi_get_named_property(env, contentResult, "expandedTitle", &longContentResult); + NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); + longContent->SetExpandedTitle(str); + ANS_LOGI("longText::expandedTitle = %{public}s", str); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationPictureContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, result, "picture", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property picture expected."); + napi_get_named_property(env, result, "picture", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + std::shared_ptr pictureContent = + std::make_shared(); + if (pictureContent == nullptr) { + ANS_LOGE("pictureContent is null"); + return nullptr; + } + if (GetNotificationPictureContentDetailed(env, contentResult, pictureContent) == nullptr) { return nullptr; } + request.SetContent(std::make_shared(pictureContent)); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationPictureContentDetailed(const napi_env &env, + const napi_value &contentResult, std::shared_ptr &pictureContent) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value pictureContentResult = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + if (GetNotificationBasicContentDetailed(env, contentResult, pictureContent) == nullptr) { + return nullptr; + } + + // briefText: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property briefText expected."); + napi_get_named_property(env, contentResult, "briefText", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); + pictureContent->SetBriefText(str); + + // expandedTitle: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "expandedTitle", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property briefText expected."); + napi_get_named_property(env, contentResult, "expandedTitle", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, pictureContentResult, str, STR_MAX_SIZE - 1, &strLen)); + pictureContent->SetExpandedTitle(str); + // picture: image.PixelMap NAPI_CALL(env, napi_has_named_property(env, contentResult, "picture", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "picture", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, hasProperty, "Property picture expected."); + napi_get_named_property(env, contentResult, "picture", &pictureContentResult); + NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, pictureContentResult); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; + } + pictureContent->SetBigPicture(pixelMap); + + return Common::NapiGetNull(env); +} + +napi_value Common::GetNotificationConversationalContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value contentResult = nullptr; + bool hasProperty = false; + MessageUser user; + + NAPI_CALL(env, napi_has_named_property(env, result, "conversation", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property conversation expected."); + napi_get_named_property(env, result, "conversation", &contentResult); + NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + if (GetNotificationConversationalContentByUser(env, contentResult, user) == nullptr) { + return nullptr; + } + + std::shared_ptr conversationalContent = + std::make_shared(user); + if (conversationalContent == nullptr) { + ANS_LOGE("conversationalContent is null"); + return nullptr; + } + + if (GetNotificationBasicContentDetailed(env, contentResult, conversationalContent) == nullptr) { + return nullptr; + } + if (GetNotificationConversationalContentTitle(env, contentResult, conversationalContent) == nullptr) { + return nullptr; + } + if (GetNotificationConversationalContentGroup(env, contentResult, conversationalContent) == nullptr) { + return nullptr; + } + if (GetNotificationConversationalContentMessages(env, contentResult, conversationalContent) == nullptr) { + return nullptr; + } + + request.SetContent(std::make_shared(conversationalContent)); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationConversationalContentByUser( + const napi_env &env, const napi_value &contentResult, MessageUser &user) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + // user: MessageUser + NAPI_CALL(env, napi_has_named_property(env, contentResult, "user", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property user expected."); + napi_value userResult = nullptr; + napi_get_named_property(env, contentResult, "user", &userResult); + NAPI_CALL(env, napi_typeof(env, userResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (!GetMessageUser(env, userResult, user)) { + return nullptr; + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationConversationalContentTitle( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; + napi_value conversationalContentResult = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + // conversationTitle: string + NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property conversationTitle expected."); + napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); + NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); + conversationalContent->SetConversationTitle(str); + ANS_LOGI("conversationTitle = %{public}s", str); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationConversationalContentGroup( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; + napi_value conversationalContentResult = nullptr; + bool hasProperty = false; + + // conversationGroup: boolean + NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationGroup", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property conversationGroup expected."); + napi_get_named_property(env, contentResult, "conversationGroup", &conversationalContentResult); + NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + bool conversationGroup = false; + napi_get_value_bool(env, conversationalContentResult, &conversationGroup); + conversationalContent->SetConversationGroup(conversationGroup); + ANS_LOGI("conversationalText::conversationGroup = %{public}d", conversationGroup); + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationConversationalContentMessages( + const napi_env &env, const napi_value &contentResult, + std::shared_ptr &conversationalContent) +{ + ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; + napi_value conversationalContentResult = nullptr; + bool hasProperty = false; + + // messages: Array + NAPI_CALL(env, napi_has_named_property(env, contentResult, "messages", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property messages expected."); + napi_get_named_property(env, contentResult, "messages", &conversationalContentResult); + bool isArray = false; + napi_is_array(env, conversationalContentResult, &isArray); + NAPI_ASSERT(env, isArray, "Property messages is expected to be an array."); + uint32_t length = 0; + napi_get_array_length(env, conversationalContentResult, &length); + NAPI_ASSERT(env, length > 0, "The array is empty."); + for (size_t i = 0; i < length; i++) { + napi_value conversationalMessage = nullptr; + napi_get_element(env, conversationalContentResult, i, &conversationalMessage); + NAPI_CALL(env, napi_typeof(env, conversationalMessage, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr pixelMap = nullptr; - pixelMap = Media::PixelMapNapi::GetPixelMap(env, pictureContentResult); - if (pixelMap == nullptr) { - ANS_LOGE("Invalid object pixelMap"); + std::shared_ptr message = nullptr; + if (!GetConversationalMessage(env, conversationalMessage, message)) { return nullptr; } - pictureContent->SetBigPicture(pixelMap); - } else { - ANS_LOGE("Property picture expected."); - return nullptr; + conversationalContent->AddConversationalMessage(message); } - request.SetContent(std::make_shared(pictureContent)); - return Common::NapiGetNull(env); + return NapiGetNull(env); +} + +napi_value Common::GetConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message) +{ + ANS_LOGI("enter"); + + if (GetConversationalMessageBasicInfo(env, conversationalMessage, message) == nullptr) { + return nullptr; + } + if (GetConversationalMessageOtherInfo(env, conversationalMessage, message) == nullptr) { + return nullptr; + } + return NapiGetNull(env); } -napi_value GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser) +napi_value Common::GetConversationalMessageBasicInfo(const napi_env &env, const napi_value &conversationalMessage, + std::shared_ptr &message) { ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; + std::string text; + int64_t timestamp = 0; + MessageUser sender; - // name: string - NAPI_CALL(env, napi_has_named_property(env, result, "name", &hasProperty)); - if (hasProperty) { - napi_value nameResult = nullptr; - napi_get_named_property(env, result, "name", &nameResult); - NAPI_CALL(env, napi_typeof(env, nameResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, nameResult, str, STR_MAX_SIZE - 1, &strLen)); - messageUser.SetName(str); - ANS_LOGI("MessageUser::name = %{public}s", str); - } else { - ANS_LOGE("Property name expected."); - return nullptr; - } - - // uri: string - NAPI_CALL(env, napi_has_named_property(env, result, "uri", &hasProperty)); - if (hasProperty) { - napi_value uriResult = nullptr; - napi_get_named_property(env, result, "uri", &uriResult); - NAPI_CALL(env, napi_typeof(env, uriResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); - Uri uri(str); - messageUser.SetUri(uri); - ANS_LOGI("MessageUser::uri = %{public}s", str); - } else { - ANS_LOGE("Property uri expected."); - return nullptr; - } + // text: string + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "text", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property text expected."); + napi_value textResult = nullptr; + napi_get_named_property(env, conversationalMessage, "text", &textResult); + NAPI_CALL(env, napi_typeof(env, textResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, textResult, str, STR_MAX_SIZE - 1, &strLen)); + text = str; + ANS_LOGI("conversationalMessage::text = %{public}s", str); - // important: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "important", &hasProperty)); - if (hasProperty) { - napi_value importantResult = nullptr; - napi_get_named_property(env, result, "important", &importantResult); - NAPI_CALL(env, napi_typeof(env, importantResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - bool important = false; - napi_get_value_bool(env, importantResult, &important); - messageUser.SetUserAsImportant(important); - ANS_LOGI("MessageUser::important = %{public}d", important); - } else { - ANS_LOGE("Property important expected."); - return nullptr; - } + // timestamp: number + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property timestamp expected."); + napi_value timestampResult = nullptr; + napi_get_named_property(env, conversationalMessage, "timestamp", ×tampResult); + NAPI_CALL(env, napi_typeof(env, timestampResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int64(env, timestampResult, ×tamp); + ANS_LOGI("conversationalMessage::timestamp = %{public}" PRId64, timestamp); - // machine: boolean - NAPI_CALL(env, napi_has_named_property(env, result, "machine", &hasProperty)); - if (hasProperty) { - napi_value machineResult = nullptr; - napi_get_named_property(env, result, "machine", &machineResult); - NAPI_CALL(env, napi_typeof(env, machineResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - bool machine = false; - napi_get_value_bool(env, machineResult, &machine); - messageUser.SetMachine(machine); - ANS_LOGI("MessageUser::machine = %{public}d", machine); - } else { - ANS_LOGE("Property machine expected."); + // sender: MessageUser + NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "sender", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property sender expected."); + napi_value senderResult = nullptr; + napi_get_named_property(env, conversationalMessage, "sender", &senderResult); + NAPI_CALL(env, napi_typeof(env, senderResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (!GetMessageUser(env, senderResult, sender)) { return nullptr; } - // key: string - NAPI_CALL(env, napi_has_named_property(env, result, "key", &hasProperty)); - if (hasProperty) { - napi_value keyResult = nullptr; - napi_get_named_property(env, result, "key", &keyResult); - NAPI_CALL(env, napi_typeof(env, keyResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, keyResult, str, STR_MAX_SIZE - 1, &strLen)); - messageUser.SetKey(str); - ANS_LOGI("MessageUser::key = %{public}s", str); - } else { - ANS_LOGE("Property key expected."); + message = std::make_shared(text, timestamp, sender); + if (!message) { + ANS_LOGE("Failed to create NotificationConversationalMessage object"); return nullptr; } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, +napi_value Common::GetConversationalMessageOtherInfo(const napi_env &env, const napi_value &conversationalMessage, std::shared_ptr &message) { ANS_LOGI("enter"); + napi_valuetype valuetype = napi_undefined; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - std::string text; - int64_t timestamp = 0; std::string mimeType; std::string uri; - MessageUser sender; - - // text: string - NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "text", &hasProperty)); - if (hasProperty) { - napi_value textResult = nullptr; - napi_get_named_property(env, conversationalMessage, "text", &textResult); - NAPI_CALL(env, napi_typeof(env, textResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, textResult, str, STR_MAX_SIZE - 1, &strLen)); - text = str; - ANS_LOGI("conversationalMessage::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); - } - - // timestamp: number - NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "timestamp", &hasProperty)); - if (hasProperty) { - napi_value timestampResult = nullptr; - napi_get_named_property(env, conversationalMessage, "timestamp", ×tampResult); - NAPI_CALL(env, napi_typeof(env, timestampResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int64(env, timestampResult, ×tamp); - ANS_LOGI("conversationalMessage::timestamp = %{public}" PRId64, timestamp); - } else { - ANS_LOGE("Property timestamp expected."); - } // mimeType: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "mimeType", &hasProperty)); - if (hasProperty) { - napi_value mimeTypeResult = nullptr; - napi_get_named_property(env, conversationalMessage, "mimeType", &mimeTypeResult); - NAPI_CALL(env, napi_typeof(env, mimeTypeResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, mimeTypeResult, str, STR_MAX_SIZE - 1, &strLen)); - mimeType = str; - ANS_LOGI("conversationalMessage::mimeType = %{public}s", str); - } else { - ANS_LOGE("Property mimeType expected."); - } + NAPI_ASSERT(env, hasProperty, "Property mimeType expected."); + napi_value mimeTypeResult = nullptr; + napi_get_named_property(env, conversationalMessage, "mimeType", &mimeTypeResult); + NAPI_CALL(env, napi_typeof(env, mimeTypeResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, mimeTypeResult, str, STR_MAX_SIZE - 1, &strLen)); + mimeType = str; + ANS_LOGI("conversationalMessage::mimeType = %{public}s", str); - // uri: string + // uri?: string NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "uri", &hasProperty)); if (hasProperty) { napi_value uriResult = nullptr; @@ -2283,184 +3176,147 @@ napi_value GetConversationalMessage(const napi_env &env, const napi_value &conve NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); uri = str; ANS_LOGI("conversationalMessage::uri = %{public}s", str); - } else { - ANS_LOGE("Property uri expected."); } - // sender: MessageUser - NAPI_CALL(env, napi_has_named_property(env, conversationalMessage, "sender", &hasProperty)); - if (hasProperty) { - napi_value senderResult = nullptr; - napi_get_named_property(env, conversationalMessage, "sender", &senderResult); - NAPI_CALL(env, napi_typeof(env, senderResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (!GetMessageUser(env, senderResult, sender)) { - return nullptr; - } - } else { - ANS_LOGE("Property sender expected."); + std::shared_ptr uriPtr = std::make_shared(uri); + message->SetData(mimeType, uriPtr); + + return NapiGetNull(env); +} + +napi_value Common::GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser) +{ + ANS_LOGI("enter"); + + if (GetMessageUserByString(env, result, messageUser) == nullptr) { + return nullptr; } - message = std::make_shared(text, timestamp, sender); - if (message == nullptr) { - ANS_LOGE("Failed to create NotificationConversationalMessage object."); + if (GetMessageUserByBool(env, result, messageUser) == nullptr) { return nullptr; } - std::shared_ptr uriPtr = std::make_shared(uri); - message->SetData(mimeType, uriPtr); - return Common::NapiGetNull(env); + if (GetMessageUserByCustom(env, result, messageUser) == nullptr) { + return nullptr; + } + + return NapiGetNull(env); } -napi_value GetNotificationConversationalContent( - const napi_env &env, const napi_value &result, NotificationRequest &request) +napi_value Common::GetMessageUserByString(const napi_env &env, const napi_value &result, MessageUser &messageUser) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; - napi_value contentResult = nullptr; - napi_value conversationalContentResult = nullptr; - napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; - MessageUser user; - NAPI_CALL(env, napi_has_named_property(env, result, "conversational", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property conversational expected."); - napi_get_named_property(env, result, "conversational", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + // name: string + NAPI_CALL(env, napi_has_named_property(env, result, "name", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property name expected."); + napi_value nameResult = nullptr; + napi_get_named_property(env, result, "name", &nameResult); + NAPI_CALL(env, napi_typeof(env, nameResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nameResult, str, STR_MAX_SIZE - 1, &strLen)); + messageUser.SetName(str); + ANS_LOGI("MessageUser::name = %{public}s", str); - // user: MessageUser - NAPI_CALL(env, napi_has_named_property(env, contentResult, "user", &hasProperty)); - if (hasProperty) { - napi_value userResult = nullptr; - napi_get_named_property(env, contentResult, "user", &userResult); - NAPI_CALL(env, napi_typeof(env, userResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - if (!GetMessageUser(env, userResult, user)) { - return nullptr; - } - } else { - ANS_LOGE("Property user expected."); - return nullptr; - } + // key: string + NAPI_CALL(env, napi_has_named_property(env, result, "key", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property key expected."); + napi_value keyResult = nullptr; + napi_get_named_property(env, result, "key", &keyResult); + NAPI_CALL(env, napi_typeof(env, keyResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, keyResult, str, STR_MAX_SIZE - 1, &strLen)); + messageUser.SetKey(str); + ANS_LOGI("MessageUser::key = %{public}s", str); - std::shared_ptr conversationalContent = - std::make_shared(user); - if (conversationalContent == nullptr) { - ANS_LOGE("conversationalContent is null"); - return nullptr; - } + // uri: string + NAPI_CALL(env, napi_has_named_property(env, result, "uri", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property uri expected."); + napi_value uriResult = nullptr; + napi_get_named_property(env, result, "uri", &uriResult); + NAPI_CALL(env, napi_typeof(env, uriResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, uriResult, str, STR_MAX_SIZE - 1, &strLen)); + Uri uri(str); + messageUser.SetUri(uri); + ANS_LOGI("MessageUser::uri = %{public}s", str); - // title: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetTitle(str); - ANS_LOGI("conversationalText::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); - return nullptr; - } + return NapiGetNull(env); +} - // text: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetText(str); - ANS_LOGI("conversationalText::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); - return nullptr; - } +napi_value Common::GetMessageUserByBool(const napi_env &env, const napi_value &result, MessageUser &messageUser) +{ + ANS_LOGI("enter"); - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetAdditionalText(str); - ANS_LOGI("conversationalText::additionalText = %{public}s", str); - } + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; - // conversationTitle: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "conversationTitle", &conversationalContentResult); - NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, conversationalContentResult, str, STR_MAX_SIZE - 1, &strLen)); - conversationalContent->SetConversationTitle(str); - ANS_LOGI("conversationalText::conversationTitle = %{public}s", str); - } else { - ANS_LOGE("Property conversationTitle expected."); - return nullptr; - } + // isMachine: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "isMachine", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property isMachine expected."); + napi_value machineResult = nullptr; + napi_get_named_property(env, result, "isMachine", &machineResult); + NAPI_CALL(env, napi_typeof(env, machineResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + bool machine = false; + napi_get_value_bool(env, machineResult, &machine); + messageUser.SetMachine(machine); + ANS_LOGI("MessageUser::isMachine = %{public}d", machine); + + // isUserImportant: boolean + NAPI_CALL(env, napi_has_named_property(env, result, "isUserImportant", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property isUserImportant expected."); + napi_value importantResult = nullptr; + napi_get_named_property(env, result, "isUserImportant", &importantResult); + NAPI_CALL(env, napi_typeof(env, importantResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + bool important = false; + napi_get_value_bool(env, importantResult, &important); + messageUser.SetUserAsImportant(important); + ANS_LOGI("MessageUser::isUserImportant = %{public}d", important); - // conversationGroup: boolean - NAPI_CALL(env, napi_has_named_property(env, contentResult, "conversationGroup", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "conversationGroup", &conversationalContentResult); - NAPI_CALL(env, napi_typeof(env, conversationalContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - bool conversationGroup = false; - napi_get_value_bool(env, conversationalContentResult, &conversationGroup); - conversationalContent->SetConversationGroup(conversationGroup); - ANS_LOGI("conversationalText::conversationGroup = %{public}d", conversationGroup); - } else { - ANS_LOGE("Property conversationGroup expected."); - return nullptr; - } + return NapiGetNull(env); +} - // messages: Array - NAPI_CALL(env, napi_has_named_property(env, contentResult, "messages", &hasProperty)); +napi_value Common::GetMessageUserByCustom(const napi_env &env, const napi_value &result, MessageUser &messageUser) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + // icon?: image.PixelMap + NAPI_CALL(env, napi_has_named_property(env, result, "icon", &hasProperty)); if (hasProperty) { - napi_get_named_property(env, contentResult, "messages", &conversationalContentResult); - bool isArray = false; - napi_is_array(env, conversationalContentResult, &isArray); - NAPI_ASSERT(env, isArray, "Property messages is expected to be an array."); - uint32_t length = 0; - napi_get_array_length(env, conversationalContentResult, &length); - NAPI_ASSERT(env, length > 0, "The array is empty."); - for (size_t i = 0; i < length; i++) { - napi_value conversationalMessage = nullptr; - napi_get_element(env, conversationalContentResult, i, &conversationalMessage); - NAPI_CALL(env, napi_typeof(env, conversationalMessage, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr message = nullptr; - if (!GetConversationalMessage(env, conversationalMessage, message)) { - return nullptr; - } - conversationalContent->AddConversationalMessage(message); + napi_value iconResult = nullptr; + napi_get_named_property(env, result, "icon", &iconResult); + NAPI_CALL(env, napi_typeof(env, iconResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + std::shared_ptr pixelMap = nullptr; + pixelMap = Media::PixelMapNapi::GetPixelMap(env, iconResult); + if (pixelMap == nullptr) { + ANS_LOGE("Invalid object pixelMap"); + return nullptr; } - } else { - ANS_LOGE("Property messages expected."); - return nullptr; + messageUser.SetPixelMap(pixelMap); } - request.SetContent(std::make_shared(conversationalContent)); - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +napi_value Common::GetNotificationMultiLineContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; napi_value contentResult = nullptr; napi_value multiLineContentResult = nullptr; - napi_value basicContentResult = nullptr; bool hasProperty = false; char str[STR_MAX_SIZE] = {0}; size_t strLen = 0; @@ -2478,90 +3334,43 @@ napi_value GetNotificationMultiLineContent(const napi_env &env, const napi_value return nullptr; } - // title: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "title", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "title", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetTitle(str); - ANS_LOGI("multiLine::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); - return nullptr; - } - - // text: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "text", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "text", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetText(str); - ANS_LOGI("multiLine::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); + if (GetNotificationBasicContentDetailed(env, contentResult, multiLineContent) == nullptr) { return nullptr; } - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetAdditionalText(str); - ANS_LOGI("multiLine::additionalText = %{public}s", str); - } - // briefText: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "briefText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); - NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetBriefText(str); - ANS_LOGI("multiLine: briefText = %{public}s", str); - } else { - ANS_LOGE("Property briefText expected."); - return nullptr; - } + NAPI_ASSERT(env, hasProperty, "Property briefText expected."); + napi_get_named_property(env, contentResult, "briefText", &multiLineContentResult); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetBriefText(str); + ANS_LOGI("multiLine: briefText = %{public}s", str); // longTitle: string NAPI_CALL(env, napi_has_named_property(env, contentResult, "longTitle", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); - NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); - multiLineContent->SetExpandedTitle(str); - ANS_LOGI("multiLine: longTitle = %{public}s", str); - } else { - ANS_LOGE("Property longTitle expected."); - return nullptr; - } + NAPI_ASSERT(env, hasProperty, "Property longTitle expected."); + napi_get_named_property(env, contentResult, "longTitle", &multiLineContentResult); + NAPI_CALL(env, napi_typeof(env, multiLineContentResult, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, multiLineContentResult, str, STR_MAX_SIZE - 1, &strLen)); + multiLineContent->SetExpandedTitle(str); + ANS_LOGI("multiLine: longTitle = %{public}s", str); // lines: Array NAPI_CALL(env, napi_has_named_property(env, contentResult, "lines", &hasProperty)); - if (hasProperty) { - if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { - return nullptr; - } - } else { - ANS_LOGE("Property lines expected."); + NAPI_ASSERT(env, hasProperty, "Property lines expected."); + if (GetNotificationMultiLineContentLines(env, contentResult, multiLineContent) == nullptr) { return nullptr; } request.SetContent(std::make_shared(multiLineContent)); - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, +napi_value Common::GetNotificationMultiLineContentLines(const napi_env &env, const napi_value &result, std::shared_ptr &multiLineContent) { ANS_LOGI("enter"); @@ -2589,17 +3398,16 @@ napi_value GetNotificationMultiLineContentLines(const napi_env &env, const napi_ ANS_LOGI("multiLine: lines : addSingleLine = %{public}s", str); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &value, NotificationSlot &slot) { ANS_LOGI("enter"); + napi_value nobj = nullptr; napi_valuetype valuetype = napi_undefined; bool hasProperty = false; - size_t strLen = 0; - uint32_t length = 0; // type: notification.SlotType int slotType = 0; @@ -2609,28 +3417,35 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); napi_get_value_int32(env, nobj, &slotType); - enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - if (!SlotTypeJSToC(SlotType(slotType), outType)) { + NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } slot.SetType(outType); - - // level?: number - NAPI_CALL(env, napi_has_named_property(env, value, "level", &hasProperty)); - if (hasProperty) { - int inLevel = 0; - napi_get_named_property(env, value, "level", &nobj); - NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, nobj, &inLevel); - ANS_LOGI("level is: %{public}d", inLevel); - - NotificationSlot::NotificationLevel outLevel {NotificationSlot::NotificationLevel::LEVEL_NONE}; - if (!SlotLevelJSToC(SlotLevel(inLevel), outLevel)) { - return nullptr; - } - slot.SetLevel(outLevel); + + if (GetNotificationSlotByString(env, value, slot) == nullptr) { + return nullptr; + } + if (GetNotificationSlotByNumber(env, value, slot) == nullptr) { + return nullptr; + } + if (GetNotificationSlotByVibration(env, value, slot) == nullptr) { + return nullptr; + } + if (GetNotificationSlotByBool(env, value, slot) == nullptr) { + return nullptr; } + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSlotByString(const napi_env &env, const napi_value &value, NotificationSlot &slot) +{ + ANS_LOGI("enter"); + + napi_value nobj = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + size_t strLen = 0; // desc?: string NAPI_CALL(env, napi_has_named_property(env, value, "desc", &hasProperty)); @@ -2646,6 +3461,30 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va slot.SetDescription(desc); } + // sound?: string + NAPI_CALL(env, napi_has_named_property(env, value, "sound", &hasProperty)); + if (hasProperty) { + std::string sound; + char str[STR_MAX_SIZE] = {0}; + napi_get_named_property(env, value, "sound", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); + sound = str; + ANS_LOGI("sound is: %{public}s", sound.c_str()); + slot.SetSound(Uri(sound)); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSlotByBool(const napi_env &env, const napi_value &value, NotificationSlot &slot) +{ + ANS_LOGI("enter"); + napi_value nobj = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + // badgeFlag?: boolean NAPI_CALL(env, napi_has_named_property(env, value, "badgeFlag", &hasProperty)); if (hasProperty) { @@ -2670,54 +3509,56 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va slot.EnableBypassDnd(bypassDnd); } - // lockscreenVisibility?: number - NAPI_CALL(env, napi_has_named_property(env, value, "lockscreenVisibility", &hasProperty)); - if (hasProperty) { - int lockscreenVisibility = 0; - napi_get_named_property(env, value, "lockscreenVisibility", &nobj); - NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, nobj, &lockscreenVisibility); - ANS_LOGI("lockscreenVisibility is: %{public}d", lockscreenVisibility); - slot.SetLockscreenVisibleness(NotificationConstant::VisiblenessType(lockscreenVisibility)); - } - - // vibrationEnabled?: boolean - NAPI_CALL(env, napi_has_named_property(env, value, "vibrationEnabled", &hasProperty)); + // lightEnabled?: boolean + NAPI_CALL(env, napi_has_named_property(env, value, "lightEnabled", &hasProperty)); if (hasProperty) { - bool vibrationEnabled = false; - napi_get_named_property(env, value, "vibrationEnabled", &nobj); + bool lightEnabled = false; + napi_get_named_property(env, value, "lightEnabled", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - napi_get_value_bool(env, nobj, &vibrationEnabled); - ANS_LOGI("vibrationEnabled is: %{public}d", vibrationEnabled); - slot.SetEnableVibration(vibrationEnabled); + napi_get_value_bool(env, nobj, &lightEnabled); + ANS_LOGI("lightEnabled is: %{public}d", lightEnabled); + slot.SetEnableLight(lightEnabled); } - // sound?: string - NAPI_CALL(env, napi_has_named_property(env, value, "sound", &hasProperty)); + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSlotByNumber(const napi_env &env, const napi_value &value, NotificationSlot &slot) +{ + ANS_LOGI("enter"); + + napi_value nobj = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + // level?: number + NAPI_CALL(env, napi_has_named_property(env, value, "level", &hasProperty)); if (hasProperty) { - std::string sound; - char str[STR_MAX_SIZE] = {0}; - napi_get_named_property(env, value, "sound", &nobj); + int inLevel = 0; + napi_get_named_property(env, value, "level", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, nobj, str, STR_MAX_SIZE - 1, &strLen)); - sound = str; - ANS_LOGI("sound is: %{public}s", sound.c_str()); - slot.SetSound(Uri(sound)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &inLevel); + ANS_LOGI("level is: %{public}d", inLevel); + + NotificationSlot::NotificationLevel outLevel {NotificationSlot::NotificationLevel::LEVEL_NONE}; + if (!Common::SlotLevelJSToC(SlotLevel(inLevel), outLevel)) { + return nullptr; + } + slot.SetLevel(outLevel); } - // lightEnabled?: boolean - NAPI_CALL(env, napi_has_named_property(env, value, "lightEnabled", &hasProperty)); + // lockscreenVisibility?: number + NAPI_CALL(env, napi_has_named_property(env, value, "lockscreenVisibility", &hasProperty)); if (hasProperty) { - bool lightEnabled = false; - napi_get_named_property(env, value, "lightEnabled", &nobj); + int lockscreenVisibility = 0; + napi_get_named_property(env, value, "lockscreenVisibility", &nobj); NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - napi_get_value_bool(env, nobj, &lightEnabled); - ANS_LOGI("lightEnabled is: %{public}d", lightEnabled); - slot.SetEnableLight(lightEnabled); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &lockscreenVisibility); + ANS_LOGI("lockscreenVisibility is: %{public}d", lockscreenVisibility); + slot.SetLockscreenVisibleness(NotificationConstant::VisiblenessType(lockscreenVisibility)); } // lightColor?: number @@ -2731,6 +3572,16 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va ANS_LOGI("lightColor is: %{public}d", lightColor); slot.SetLedLightColor(lightColor); } + return NapiGetNull(env); +} + +napi_value Common::GetNotificationSlotByVibration(const napi_env &env, const napi_value &value, NotificationSlot &slot) +{ + ANS_LOGI("enter"); + napi_value nobj = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + uint32_t length = 0; // vibrationValues?: Array NAPI_CALL(env, napi_has_named_property(env, value, "vibrationValues", &hasProperty)); @@ -2754,10 +3605,23 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va } slot.SetVibrationStyle(vibrationValues); } + + // vibrationEnabled?: boolean + NAPI_CALL(env, napi_has_named_property(env, value, "vibrationEnabled", &hasProperty)); + if (hasProperty) { + bool vibrationEnabled = false; + napi_get_named_property(env, value, "vibrationEnabled", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, nobj, &vibrationEnabled); + ANS_LOGI("vibrationEnabled is: %{public}d", vibrationEnabled); + slot.SetEnableVibration(vibrationEnabled); + } + return NapiGetNull(env); } -napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, BundleOption &option) +napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, NotificationBundleOption &option) { ANS_LOGI("enter"); @@ -2769,20 +3633,31 @@ napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, size_t strLen = 0; // bundle: string NAPI_CALL(env, napi_has_named_property(env, value, "bundle", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property bundle expected."); + if (!hasProperty) { + ANS_LOGE("Property bundle expected."); + return nullptr; + } napi_get_named_property(env, value, "bundle", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + if (valuetype != napi_string) { + ANS_LOGE("Wrong argument type. String expected."); + return nullptr; + } NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); - option.bundle = str; + option.SetBundleName(str); // uid?: number NAPI_CALL(env, napi_has_named_property(env, value, "uid", &hasProperty)); if (hasProperty) { + int32_t uid = 0; napi_get_named_property(env, value, "uid", &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, result, &option.uid); + if (valuetype != napi_number) { + ANS_LOGE("Wrong argument type. Number expected."); + return nullptr; + } + napi_get_value_int32(env, result, &uid); + option.SetUid(uid); } return NapiGetNull(env); @@ -2819,7 +3694,7 @@ napi_value Common::GetNotificationKey(const napi_env &env, const napi_value &val return NapiGetNull(env); } -bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationContent::Type &outType) +bool Common::ContentTypeJSToC(const ContentType &inType, NotificationContent::Type &outType) { switch (inType) { case ContentType::NOTIFICATION_CONTENT_BASIC_TEXT: @@ -2834,6 +3709,9 @@ bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationC case ContentType::NOTIFICATION_CONTENT_PICTURE: outType = NotificationContent::Type::PICTURE; break; + case ContentType::NOTIFICATION_CONTENT_CONVERSATION: + outType = NotificationContent::Type::CONVERSATION; + break; default: ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; @@ -2841,7 +3719,7 @@ bool Common::ContentTypeJSToC(const enum ContentType &inType, enum NotificationC return true; } -bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum ContentType &outType) +bool Common::ContentTypeCToJS(const NotificationContent::Type &inType, ContentType &outType) { switch (inType) { case NotificationContent::Type::BASIC_TEXT: @@ -2856,6 +3734,9 @@ bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum case NotificationContent::Type::PICTURE: outType = ContentType::NOTIFICATION_CONTENT_PICTURE; break; + case NotificationContent::Type::CONVERSATION: + outType = ContentType::NOTIFICATION_CONTENT_CONVERSATION; + break; default: ANS_LOGE("ContentType %{public}d is an invalid value", inType); return false; @@ -2863,7 +3744,7 @@ bool Common::ContentTypeCToJS(const enum NotificationContent::Type &inType, enum return true; } -bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstant::SlotType &outType) +bool Common::SlotTypeJSToC(const SlotType &inType, NotificationConstant::SlotType &outType) { switch (inType) { case SlotType::SOCIAL_COMMUNICATION: @@ -2886,7 +3767,7 @@ bool Common::SlotTypeJSToC(const enum SlotType &inType, enum NotificationConstan return true; } -bool Common::SlotTypeCToJS(const enum NotificationConstant::SlotType &inType, enum SlotType &outType) +bool Common::SlotTypeCToJS(const NotificationConstant::SlotType &inType, SlotType &outType) { switch (inType) { case NotificationConstant::SlotType::CUSTOM: @@ -2966,31 +3847,31 @@ bool Common::ReasonCToJS(const int &inType, int &outType) { switch (inType) { case NotificationConstant::CLICK_REASON_DELETE: - outType = NotificationReason::CLICK_REASON_DELETE; + outType = (int)NotificationReason::CLICK_REASON_DELETE; break; case NotificationConstant::CANCEL_REASON_DELETE: - outType = NotificationReason::CANCEL_REASON_DELETE; + outType = (int)NotificationReason::CANCEL_REASON_DELETE; break; case NotificationConstant::CANCEL_ALL_REASON_DELETE: - outType = NotificationReason::CANCEL_ALL_REASON_DELETE; + outType = (int)NotificationReason::CANCEL_ALL_REASON_DELETE; break; case NotificationConstant::ERROR_REASON_DELETE: - outType = NotificationReason::ERROR_REASON_DELETE; + outType = (int)NotificationReason::ERROR_REASON_DELETE; break; case NotificationConstant::PACKAGE_CHANGED_REASON_DELETE: - outType = NotificationReason::PACKAGE_CHANGED_REASON_DELETE; + outType = (int)NotificationReason::PACKAGE_CHANGED_REASON_DELETE; break; case NotificationConstant::USER_STOPPED_REASON_DELETE: - outType = NotificationReason::USER_STOPPED_REASON_DELETE; + outType = (int)NotificationReason::USER_STOPPED_REASON_DELETE; break; case NotificationConstant::APP_CANCEL_REASON_DELETE: - outType = NotificationReason::APP_CANCEL_REASON_DELETE; + outType = (int)NotificationReason::APP_CANCEL_REASON_DELETE; break; case NotificationConstant::APP_CANCEL_ALL_REASON_DELETE: - outType = NotificationReason::APP_CANCEL_ALL_REASON_DELETE; + outType = (int)NotificationReason::APP_CANCEL_ALL_REASON_DELETE; break; case NotificationConstant::APP_CANCEL_REASON_OTHER: - outType = NotificationReason::APP_CANCEL_REASON_OTHER; + outType = (int)NotificationReason::APP_CANCEL_REASON_OTHER; break; default: ANS_LOGE("Reason %{public}d is an invalid value", inType); @@ -2999,26 +3880,86 @@ bool Common::ReasonCToJS(const int &inType, int &outType) return true; } -bool Common::DisturbModeJSToC(const enum DisturbMode &inType, enum NotificationConstant::DisturbMode &outType) +bool Common::DoNotDisturbTypeJSToC(const DoNotDisturbType &inType, NotificationConstant::DoNotDisturbType &outType) +{ + switch (inType) { + case DoNotDisturbType::TYPE_NONE: + outType = NotificationConstant::DoNotDisturbType::NONE; + break; + case DoNotDisturbType::TYPE_ONCE: + outType = NotificationConstant::DoNotDisturbType::ONCE; + break; + case DoNotDisturbType::TYPE_DAILY: + outType = NotificationConstant::DoNotDisturbType::DAILY; + break; + case DoNotDisturbType::TYPE_CLEARLY: + outType = NotificationConstant::DoNotDisturbType::CLEARLY; + break; + default: + ANS_LOGE("DoNotDisturbType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool Common::DoNotDisturbTypeCToJS(const NotificationConstant::DoNotDisturbType &inType, DoNotDisturbType &outType) +{ + switch (inType) { + case NotificationConstant::DoNotDisturbType::NONE: + outType = DoNotDisturbType::TYPE_NONE; + break; + case NotificationConstant::DoNotDisturbType::ONCE: + outType = DoNotDisturbType::TYPE_ONCE; + break; + case NotificationConstant::DoNotDisturbType::DAILY: + outType = DoNotDisturbType::TYPE_DAILY; + break; + case NotificationConstant::DoNotDisturbType::CLEARLY: + outType = DoNotDisturbType::TYPE_CLEARLY; + break; + default: + ANS_LOGE("DoNotDisturbType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool Common::DeviceRemindTypeCToJS(const NotificationConstant::RemindType &inType, DeviceRemindType &outType) { switch (inType) { - case DisturbMode::ALLOW_UNKNOWN: - outType = NotificationConstant::DisturbMode::ALLOW_UNKNOWN; + case NotificationConstant::RemindType::DEVICE_IDLE_DONOT_REMIND: + outType = DeviceRemindType::IDLE_DONOT_REMIND; + break; + case NotificationConstant::RemindType::DEVICE_IDLE_REMIND: + outType = DeviceRemindType::IDLE_REMIND; break; - case DisturbMode::ALLOW_ALL: - outType = NotificationConstant::DisturbMode::ALLOW_ALL; + case NotificationConstant::RemindType::DEVICE_ACTIVE_DONOT_REMIND: + outType = DeviceRemindType::ACTIVE_DONOT_REMIND; break; - case DisturbMode::ALLOW_PRIORITY: - outType = NotificationConstant::DisturbMode::ALLOW_PRIORITY; + case NotificationConstant::RemindType::DEVICE_ACTIVE_REMIND: + outType = DeviceRemindType::ACTIVE_REMIND; + break; + default: + ANS_LOGE("DeviceRemindType %{public}d is an invalid value", inType); + return false; + } + return true; +} + +bool Common::SourceTypeCToJS(const NotificationConstant::SourceType &inType, SourceType &outType) +{ + switch (inType) { + case NotificationConstant::SourceType::TYPE_NORMAL: + outType = SourceType::TYPE_NORMAL; break; - case DisturbMode::ALLOW_NONE: - outType = NotificationConstant::DisturbMode::ALLOW_NONE; + case NotificationConstant::SourceType::TYPE_CONTINUOUS: + outType = SourceType::TYPE_CONTINUOUS; break; - case DisturbMode::ALLOW_ALARMS: - outType = NotificationConstant::DisturbMode::ALLOW_ALARMS; + case NotificationConstant::SourceType::TYPE_TIMER: + outType = SourceType::TYPE_TIMER; break; default: - ANS_LOGE("DisturbMode %{public}d is an invalid value", inType); + ANS_LOGE("SourceType %{public}d is an invalid value", inType); return false; } return true; @@ -3068,5 +4009,122 @@ napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_pt return wantAgent; } + +napi_value Common::GetNotificationTemplate(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + + NAPI_CALL(env, napi_has_named_property(env, value, "template", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "template", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + + std::shared_ptr templ = std::make_shared(); + if (templ == nullptr) { + ANS_LOGE("template is null"); + return nullptr; + } + if (GetNotificationTemplateInfo(env, result, templ) == nullptr) { + return nullptr; + } + + request.SetTemplate(templ); + } + + return NapiGetNull(env); +} + +napi_value Common::GetNotificationTemplateInfo(const napi_env &env, const napi_value &value, + std::shared_ptr &templ) +{ + ANS_LOGI("enter"); + + napi_valuetype valuetype = napi_undefined; + napi_value result = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + // name: string + NAPI_CALL(env, napi_has_named_property(env, value, "name", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property text expected."); + napi_get_named_property(env, value, "name", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); + std::string strInput = str; + templ->SetTemplateName(strInput); + + // data?: {[key: string]: object} + NAPI_CALL(env, napi_has_named_property(env, value, "data", &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, "data", &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + AAFwk::WantParams wantParams; + if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { + return nullptr; + } + + std::shared_ptr data = std::make_shared(wantParams); + templ->SetTemplateData(data); + } + + return NapiGetNull(env); +} + +napi_value Common::SetNotificationTemplateInfo( + const napi_env &env, const std::shared_ptr &templ, napi_value &result) +{ + ANS_LOGI("enter"); + + if (templ == nullptr) { + ANS_LOGE("templ is null"); + return NapiGetBoolean(env, false); + } + + napi_value value = nullptr; + + // name: string; + napi_create_string_utf8(env, templ->GetTemplateName().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "name", value); + + // data?: {[key: string]: object}; + std::shared_ptr data = templ->GetTemplateData(); + if (data) { + value = OHOS::AppExecFwk::WrapWantParams(env, *data); + napi_set_named_property(env, result, "data", value); + } + + return NapiGetBoolean(env, true); +} + +napi_value Common::SetNotificationFlags( + const napi_env &env, const std::shared_ptr &flags, napi_value &result) +{ + ANS_LOGI("enter"); + + if (flags == nullptr) { + ANS_LOGE("flags is null"); + return NapiGetBoolean(env, false); + } + + napi_value value = nullptr; + + // readonly soundEnabled?: boolean + napi_get_boolean(env, flags->IsSoundEnabled(), &value); + napi_set_named_property(env, result, "soundEnabled", value); + + // readonly vibrationEnabled?: boolean + napi_get_boolean(env, flags->IsVibrationEnabled(), &value); + napi_set_named_property(env, result, "vibrationEnabled", value); + + return NapiGetBoolean(env, true); +} } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index 3b16f77347adcb60d7624b96efbb6182fe5f233c..96443b732f5e9972455f7e4c2269b7128c409c03 100644 --- a/interfaces/kits/napi/ans/src/constant.cpp +++ b/interfaces/kits/napi/ans/src/constant.cpp @@ -14,7 +14,6 @@ */ #include "constant.h" -#include "common.h" namespace OHOS { namespace NotificationNapi { @@ -35,19 +34,23 @@ napi_value NotificationReasonInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, NotificationReason::CLICK_REASON_DELETE, "CLICK_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::CANCEL_REASON_DELETE, "CANCEL_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::CANCEL_ALL_REASON_DELETE, "CANCEL_ALL_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::ERROR_REASON_DELETE, "ERROR_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, (int32_t)NotificationReason::CLICK_REASON_DELETE, "CLICK_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, (int32_t)NotificationReason::CANCEL_REASON_DELETE, "CANCEL_REASON_DELETE"); SetNamedPropertyByInteger( - env, obj, NotificationReason::PACKAGE_CHANGED_REASON_DELETE, "PACKAGE_CHANGED_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::USER_STOPPED_REASON_DELETE, "USER_STOPPED_REASON_DELETE"); + env, obj, (int32_t)NotificationReason::CANCEL_ALL_REASON_DELETE, "CANCEL_ALL_REASON_DELETE"); + SetNamedPropertyByInteger(env, obj, (int32_t)NotificationReason::ERROR_REASON_DELETE, "ERROR_REASON_DELETE"); SetNamedPropertyByInteger( - env, obj, NotificationReason::PACKAGE_BANNED_REASON_DELETE, "PACKAGE_BANNED_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::APP_CANCEL_REASON_DELETE, "APP_CANCEL_REASON_DELETE"); + env, obj, (int32_t)NotificationReason::PACKAGE_CHANGED_REASON_DELETE, "PACKAGE_CHANGED_REASON_DELETE"); SetNamedPropertyByInteger( - env, obj, NotificationReason::APP_CANCEL_ALL_REASON_DELETE, "APP_CANCEL_ALL_REASON_DELETE"); - SetNamedPropertyByInteger(env, obj, NotificationReason::APP_CANCEL_REASON_OTHER, "APP_CANCEL_REASON_OTHER"); + env, obj, (int32_t)NotificationReason::USER_STOPPED_REASON_DELETE, "USER_STOPPED_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, (int32_t)NotificationReason::PACKAGE_BANNED_REASON_DELETE, "PACKAGE_BANNED_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, (int32_t)NotificationReason::APP_CANCEL_REASON_DELETE, "APP_CANCEL_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, (int32_t)NotificationReason::APP_CANCEL_ALL_REASON_DELETE, "APP_CANCEL_ALL_REASON_DELETE"); + SetNamedPropertyByInteger( + env, obj, (int32_t)NotificationReason::APP_CANCEL_REASON_OTHER, "APP_CANCEL_REASON_OTHER"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("NotificationReason", obj), @@ -64,11 +67,11 @@ napi_value SlotTypeInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, SlotType::UNKNOWN_TYPE, "UNKNOWN_TYPE"); - SetNamedPropertyByInteger(env, obj, SlotType::SOCIAL_COMMUNICATION, "SOCIAL_COMMUNICATION"); - SetNamedPropertyByInteger(env, obj, SlotType::SERVICE_INFORMATION, "SERVICE_INFORMATION"); - SetNamedPropertyByInteger(env, obj, SlotType::CONTENT_INFORMATION, "CONTENT_INFORMATION"); - SetNamedPropertyByInteger(env, obj, SlotType::OTHER_TYPES, "OTHER_TYPES"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotType::UNKNOWN_TYPE, "UNKNOWN_TYPE"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotType::SOCIAL_COMMUNICATION, "SOCIAL_COMMUNICATION"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotType::SERVICE_INFORMATION, "SERVICE_INFORMATION"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotType::CONTENT_INFORMATION, "CONTENT_INFORMATION"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotType::OTHER_TYPES, "OTHER_TYPES"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("SlotType", obj), @@ -85,11 +88,11 @@ napi_value SlotLevelInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_NONE, "LEVEL_NONE"); - SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_MIN, "LEVEL_MIN"); - SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_LOW, "LEVEL_LOW"); - SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_DEFAULT, "LEVEL_DEFAULT"); - SetNamedPropertyByInteger(env, obj, SlotLevel::LEVEL_HIGH, "LEVEL_HIGH"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotLevel::LEVEL_NONE, "LEVEL_NONE"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotLevel::LEVEL_MIN, "LEVEL_MIN"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotLevel::LEVEL_LOW, "LEVEL_LOW"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotLevel::LEVEL_DEFAULT, "LEVEL_DEFAULT"); + SetNamedPropertyByInteger(env, obj, (int32_t)SlotLevel::LEVEL_HIGH, "LEVEL_HIGH"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("SlotLevel", obj), @@ -106,17 +109,24 @@ napi_value SemanticActionButtonInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::NONE_ACTION_BUTTON, "NONE_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::REPLY_ACTION_BUTTON, "REPLY_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::READ_ACTION_BUTTON, "READ_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::UNREAD_ACTION_BUTTON, "UNREAD_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::DELETE_ACTION_BUTTON, "DELETE_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::ARCHIVE_ACTION_BUTTON, "ARCHIVE_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::MUTE_ACTION_BUTTON, "MUTE_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::UNMUTE_ACTION_BUTTON, "UNMUTE_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::THUMBS_UP_ACTION_BUTTON, "THUMBS_UP_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::THUMBS_DOWN_ACTION_BUTTON, "THUMBS_DOWN_ACTION_BUTTON"); - SetNamedPropertyByInteger(env, obj, SemanticActionButton::CALL_ACTION_BUTTON, "CALL_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, (int32_t)SemanticActionButton::NONE_ACTION_BUTTON, "NONE_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, (int32_t)SemanticActionButton::REPLY_ACTION_BUTTON, "REPLY_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, (int32_t)SemanticActionButton::READ_ACTION_BUTTON, "READ_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::UNREAD_ACTION_BUTTON, "UNREAD_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::DELETE_ACTION_BUTTON, "DELETE_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::ARCHIVE_ACTION_BUTTON, "ARCHIVE_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::MUTE_ACTION_BUTTON, "MUTE_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::UNMUTE_ACTION_BUTTON, "UNMUTE_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::THUMBS_UP_ACTION_BUTTON, "THUMBS_UP_ACTION_BUTTON"); + SetNamedPropertyByInteger( + env, obj, (int32_t)SemanticActionButton::THUMBS_DOWN_ACTION_BUTTON, "THUMBS_DOWN_ACTION_BUTTON"); + SetNamedPropertyByInteger(env, obj, (int32_t)SemanticActionButton::CALL_ACTION_BUTTON, "CALL_ACTION_BUTTON"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("SemanticActionButton", obj), @@ -133,8 +143,8 @@ napi_value InputsSourceInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, InputsSource::FREE_FORM_INPUT, "FREE_FORM_INPUT"); - SetNamedPropertyByInteger(env, obj, InputsSource::OPTION, "OPTION"); + SetNamedPropertyByInteger(env, obj, (int32_t)InputsSource::FREE_FORM_INPUT, "FREE_FORM_INPUT"); + SetNamedPropertyByInteger(env, obj, (int32_t)InputsSource::OPTION, "OPTION"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("InputsSource", obj), @@ -151,11 +161,11 @@ napi_value DoNotDisturbMode(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_UNKNOWN, "ALLOW_UNKNOWN"); - SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_ALL, "ALLOW_ALL"); - SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_PRIORITY, "ALLOW_PRIORITY"); - SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_NONE, "ALLOW_NONE"); - SetNamedPropertyByInteger(env, obj, DisturbMode::ALLOW_ALARMS, "ALLOW_ALARMS"); + SetNamedPropertyByInteger(env, obj, (int32_t)DisturbMode::ALLOW_UNKNOWN, "ALLOW_UNKNOWN"); + SetNamedPropertyByInteger(env, obj, (int32_t)DisturbMode::ALLOW_ALL, "ALLOW_ALL"); + SetNamedPropertyByInteger(env, obj, (int32_t)DisturbMode::ALLOW_PRIORITY, "ALLOW_PRIORITY"); + SetNamedPropertyByInteger(env, obj, (int32_t)DisturbMode::ALLOW_NONE, "ALLOW_NONE"); + SetNamedPropertyByInteger(env, obj, (int32_t)DisturbMode::ALLOW_ALARMS, "ALLOW_ALARMS"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("DoNotDisturbMode", obj), @@ -172,9 +182,9 @@ napi_value InputEditTypeInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_AUTO, "EDIT_AUTO"); - SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_DISABLED, "EDIT_DISABLED"); - SetNamedPropertyByInteger(env, obj, InputEditType::EDIT_ENABLED, "EDIT_ENABLED"); + SetNamedPropertyByInteger(env, obj, (int32_t)InputEditType::EDIT_AUTO, "EDIT_AUTO"); + SetNamedPropertyByInteger(env, obj, (int32_t)InputEditType::EDIT_DISABLED, "EDIT_DISABLED"); + SetNamedPropertyByInteger(env, obj, (int32_t)InputEditType::EDIT_ENABLED, "EDIT_ENABLED"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("InputEditType", obj), @@ -192,13 +202,15 @@ napi_value ContentTypeInit(napi_env env, napi_value exports) napi_create_object(env, &obj); SetNamedPropertyByInteger( - env, obj, ContentType::NOTIFICATION_CONTENT_BASIC_TEXT, "NOTIFICATION_CONTENT_BASIC_TEXT"); - SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_LONG_TEXT, "NOTIFICATION_CONTENT_LONG_TEXT"); - SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_PICTURE, "NOTIFICATION_CONTENT_PICTURE"); + env, obj, (int32_t)ContentType::NOTIFICATION_CONTENT_BASIC_TEXT, "NOTIFICATION_CONTENT_BASIC_TEXT"); + SetNamedPropertyByInteger( + env, obj, (int32_t)ContentType::NOTIFICATION_CONTENT_LONG_TEXT, "NOTIFICATION_CONTENT_LONG_TEXT"); SetNamedPropertyByInteger( - env, obj, ContentType::NOTIFICATION_CONTENT_CONVERSATION, "NOTIFICATION_CONTENT_CONVERSATION"); - SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_MULTILINE, "NOTIFICATION_CONTENT_MULTILINE"); - SetNamedPropertyByInteger(env, obj, ContentType::NOTIFICATION_CONTENT_MEDIA, "NOTIFICATION_CONTENT_MEDIA"); + env, obj, (int32_t)ContentType::NOTIFICATION_CONTENT_PICTURE, "NOTIFICATION_CONTENT_PICTURE"); + SetNamedPropertyByInteger( + env, obj, (int32_t)ContentType::NOTIFICATION_CONTENT_CONVERSATION, "NOTIFICATION_CONTENT_CONVERSATION"); + SetNamedPropertyByInteger( + env, obj, (int32_t)ContentType::NOTIFICATION_CONTENT_MULTILINE, "NOTIFICATION_CONTENT_MULTILINE"); napi_property_descriptor exportFuncs[] = { DECLARE_NAPI_PROPERTY("ContentType", obj), @@ -208,6 +220,65 @@ napi_value ContentTypeInit(napi_env env, napi_value exports) return exports; } +napi_value DoNotDisturbTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, (int32_t)DoNotDisturbType::TYPE_NONE, "TYPE_NONE"); + SetNamedPropertyByInteger(env, obj, (int32_t)DoNotDisturbType::TYPE_ONCE, "TYPE_ONCE"); + SetNamedPropertyByInteger(env, obj, (int32_t)DoNotDisturbType::TYPE_DAILY, "TYPE_DAILY"); + SetNamedPropertyByInteger(env, obj, (int32_t)DoNotDisturbType::TYPE_CLEARLY, "TYPE_CLEARLY"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("DoNotDisturbType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value DeviceRemindTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, (int32_t)DeviceRemindType::IDLE_DONOT_REMIND, "IDLE_DONOT_REMIND"); + SetNamedPropertyByInteger(env, obj, (int32_t)DeviceRemindType::IDLE_REMIND, "IDLE_REMIND"); + SetNamedPropertyByInteger(env, obj, (int32_t)DeviceRemindType::ACTIVE_DONOT_REMIND, "ACTIVE_DONOT_REMIND"); + SetNamedPropertyByInteger(env, obj, (int32_t)DeviceRemindType::ACTIVE_REMIND, "ACTIVE_REMIND"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("DeviceRemindType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + +napi_value SourceTypeInit(napi_env env, napi_value exports) +{ + ANS_LOGI("%{public}s, called", __func__); + + napi_value obj = nullptr; + napi_create_object(env, &obj); + + SetNamedPropertyByInteger(env, obj, (int32_t)SourceType::TYPE_NORMAL, "TYPE_NORMAL"); + SetNamedPropertyByInteger(env, obj, (int32_t)SourceType::TYPE_CONTINUOUS, "TYPE_CONTINUOUS"); + SetNamedPropertyByInteger(env, obj, (int32_t)SourceType::TYPE_TIMER, "TYPE_TIMER"); + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("SourceType", obj), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +} + napi_value ConstantInit(napi_env env, napi_value exports) { NotificationReasonInit(env, exports); @@ -218,8 +289,10 @@ napi_value ConstantInit(napi_env env, napi_value exports) DoNotDisturbMode(env, exports); InputEditTypeInit(env, exports); ContentTypeInit(env, exports); + SourceTypeInit(env, exports); + DoNotDisturbTypeInit(env, exports); + DeviceRemindTypeInit(env, exports); return exports; } - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 889fd7842deba7f8cb35af9e9a515133c523a7f1..71da17f3c3aad294f2411dd205a199a68d9c3a08 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -20,9 +20,10 @@ namespace NotificationNapi { const int ENABLE_BADGE_DISPLAYED_MAX_PARA = 3; const int ENABLE_BADGE_DISPLAYED_MIN_PARA = 2; const int IS_DISPLAY_BADGE_MAX_PARA = 2; +const int IS_DISPLAY_BADGE_MIN_PARA = 1; struct EnableBadgeParams { - BundleOption option; + NotificationBundleOption option; bool enable = false; napi_ref callback = nullptr; }; @@ -35,7 +36,7 @@ struct AsyncCallbackInfoEnableBadge { }; struct IsDisplayBadgeParams { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; bool hasBundleOption = false; }; @@ -56,28 +57,41 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[ENABLE_BADGE_DISPLAYED_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= ENABLE_BADGE_DISPLAYED_MIN_PARA, "Wrong number of arguments"); + if (argc < ENABLE_BADGE_DISPLAYED_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } // argv[0]: bundle napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } // argv[1]: enable - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - napi_get_value_bool(env, argv[1], ¶ms.enable); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_boolean) { + ANS_LOGW("Wrong argument type. Bool expected."); + return nullptr; + } + napi_get_value_bool(env, argv[PARAM1], ¶ms.enable); // argv[2]:callback if (argc >= ENABLE_BADGE_DISPLAYED_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[ENABLE_BADGE_DISPLAYED_MAX_PARA - 1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[ENABLE_BADGE_DISPLAYED_MAX_PARA - 1], 1, ¶ms.callback); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -92,32 +106,39 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc == 0) { - return Common::NapiGetNull(env); + if (argc < IS_DISPLAY_BADGE_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; } // argv[0]: bundle / callback napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_function) || (valuetype == napi_object), - "Wrong argument type. Function or object expected."); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + + if ((valuetype != napi_function) && (valuetype != napi_object)) { + ANS_LOGW("Wrong argument type. Function or object expected, %{public}d", valuetype); + return nullptr; + } + if (valuetype == napi_object) { - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } params.hasBundleOption = true; } else { - napi_create_reference(env, argv[0], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); } // argv[1]:callback if (argc >= IS_DISPLAY_BADGE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -149,15 +170,12 @@ napi_value DisplayBadge(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("DisplayBadge napi_create_async_work start"); AsyncCallbackInfoEnableBadge *asynccallbackinfo = (AsyncCallbackInfoEnableBadge *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", - asynccallbackinfo->params.option.bundle.c_str()); - ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); - ANS_LOGI("asynccallbackinfo->params.enable = %{public}d", asynccallbackinfo->params.enable); - asynccallbackinfo->info.errorCode = - NotificationHelper::SetShowBadgeEnabledForBundle(bundleOption, asynccallbackinfo->params.enable); + ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d enable = %{public}d", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid(), + asynccallbackinfo->params.enable); + asynccallbackinfo->info.errorCode = NotificationHelper::SetShowBadgeEnabledForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->params.enable); ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); }, [](napi_env env, napi_status status, void *data) { @@ -188,12 +206,37 @@ napi_value DisplayBadge(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackIsBadgeDisplayed(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->enabled, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); IsDisplayBadgeParams params {}; if (ParseParameters(env, info, params) == nullptr) { + ANS_LOGE("Failed to parse params!"); return Common::NapiGetUndefined(env); } @@ -215,40 +258,19 @@ napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) ANS_LOGI("IsBadgeDisplayed napi_create_async_work start"); AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); if (asynccallbackinfo->params.hasBundleOption) { - ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", - asynccallbackinfo->params.option.bundle.c_str()); - ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); - ANS_LOGI("asynccallbackinfo->enabled = %{public}d", asynccallbackinfo->enabled); - asynccallbackinfo->info.errorCode = - NotificationHelper::GetShowBadgeEnabledForBundle(bundleOption, asynccallbackinfo->enabled); + ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid()); + asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabledForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->enabled); } else { - ANS_LOGI("asynccallbackinfo->enabled = %{public}d", asynccallbackinfo->enabled); asynccallbackinfo->info.errorCode = NotificationHelper::GetShowBadgeEnabled(asynccallbackinfo->enabled); } - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("IsBadgeDisplayed napi_create_async_work end"); - AsyncCallbackInfoIsDisplayBadge *asynccallbackinfo = (AsyncCallbackInfoIsDisplayBadge *)data; - - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->enabled, &result); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d, enabled = %{public}d", + asynccallbackinfo->info.errorCode, asynccallbackinfo->enabled); }, + AsyncCompleteCallbackIsBadgeDisplayed, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -260,6 +282,5 @@ napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) return promise; } } - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/distributed.cpp b/interfaces/kits/napi/ans/src/distributed.cpp new file mode 100644 index 0000000000000000000000000000000000000000..01e1e541de60c51c8e4d87e14da956e4c8789007 --- /dev/null +++ b/interfaces/kits/napi/ans/src/distributed.cpp @@ -0,0 +1,572 @@ +/* + * 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 "distributed.h" + +namespace OHOS { +namespace NotificationNapi { +const int ENABLED_MAX_PARA = 2; +const int ENABLED_MIN_PARA = 1; +const int ENABLED_BUNDLE_MAX_PARA = 3; +const int ENABLED_BUNDLE_MIN_PARA = 2; +const int IS_ENABLED_BUNDLE_MAX_PARA = 2; +const int IS_ENABLED_BUNDLE_MIN_PARA = 1; + +struct AsyncCallbackInfoIsEnabled { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + bool enable = false; +}; + +struct EnabledParams { + napi_ref callback = nullptr; + bool enable = false; +}; + +struct AsyncCallbackInfoEnabled { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + EnabledParams params; +}; + +struct EnabledByBundleParams { + NotificationBundleOption option; + napi_ref callback = nullptr; + bool enable = false; +}; + +struct AsyncCallbackInfoEnabledByBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + EnabledByBundleParams params; +}; + +struct IsEnabledByBundleParams { + NotificationBundleOption option; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoIsEnabledByBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + IsEnabledByBundleParams params; + bool enable = false; +}; + +struct AsyncCallbackInfoGetRemindType { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + CallbackPromiseInfo info; + NotificationConstant::RemindType remindType = NotificationConstant::RemindType::NONE; +}; + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, EnabledParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = ENABLED_MAX_PARA; + napi_value argv[ENABLED_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ENABLED_MIN_PARA, "Wrong number of arguments"); + napi_valuetype valuetype = napi_undefined; + + // argv[0]: enable + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, argv[PARAM0], ¶ms.enable); + + // argv[1]:callback + if (argc >= ENABLED_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, EnabledByBundleParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = ENABLED_BUNDLE_MAX_PARA; + napi_value argv[ENABLED_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= ENABLED_BUNDLE_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: bundle + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: enable + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + napi_get_value_bool(env, argv[PARAM1], ¶ms.enable); + + // argv[2]:callback + if (argc >= ENABLED_BUNDLE_MAX_PARA) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, IsEnabledByBundleParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = IS_ENABLED_BUNDLE_MAX_PARA; + napi_value argv[IS_ENABLED_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= IS_ENABLED_BUNDLE_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: bundle + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]:callback + if (argc >= IS_ENABLED_BUNDLE_MAX_PARA) { + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + +void AsyncCompleteCallbackIsDistributedEnabled(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + ANS_LOGI("IsDistributedEnabled napi_create_async_work end"); + AsyncCallbackInfoIsEnabled *asynccallbackinfo = (AsyncCallbackInfoIsEnabled *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_get_boolean(env, asynccallbackinfo->enable, &result); + } + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + +napi_value IsDistributedEnabled(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + napi_ref callback = nullptr; + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoIsEnabled *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoIsEnabled {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "isDistributedEnabled", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsDistributedEnabled napi_create_async_work start"); + AsyncCallbackInfoIsEnabled *asynccallbackinfo = (AsyncCallbackInfoIsEnabled *)data; + + asynccallbackinfo->info.errorCode = + NotificationHelper::IsDistributedEnabled(asynccallbackinfo->enable); + ANS_LOGI("IsDistributedEnabled enable = %{public}d", asynccallbackinfo->enable); + }, + AsyncCompleteCallbackIsDistributedEnabled, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value EnableDistributed(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + EnabledParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoEnabled *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoEnabled {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "enableDistributed", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("EnableDistributed napi_create_async_work start"); + AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; + + asynccallbackinfo->info.errorCode = + NotificationHelper::EnableDistributed(asynccallbackinfo->params.enable); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("EnableDistributed napi_create_async_work end"); + AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value EnableDistributedByBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + EnabledByBundleParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoEnabledByBundle {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "enableDistributedByBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("EnableDistributedByBundle napi_create_async_work start"); + AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoEnabledByBundle *)data; + + asynccallbackinfo->info.errorCode = NotificationHelper::EnableDistributedByBundle( + asynccallbackinfo->params.option, asynccallbackinfo->params.enable); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("EnableDistributedByBundle napi_create_async_work end"); + AsyncCallbackInfoEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoEnabledByBundle *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value EnableDistributedSelf(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + EnabledParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoEnabled *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoEnabled {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "enableDistributedSelf", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("EnableDistributedSelf napi_create_async_work start"); + AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; + + asynccallbackinfo->info.errorCode = + NotificationHelper::EnableDistributedSelf(asynccallbackinfo->params.enable); + ANS_LOGI("EnableDistributedSelf enable = %{public}d", asynccallbackinfo->params.enable); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("EnableDistributedSelf napi_create_async_work end"); + AsyncCallbackInfoEnabled *asynccallbackinfo = (AsyncCallbackInfoEnabled *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +void AsyncCompleteCallbackIsDistributedEnableByBundle(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + ANS_LOGI("IsDistributedEnableByBundle napi_create_async_work end"); + AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoIsEnabledByBundle *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_get_boolean(env, asynccallbackinfo->enable, &result); + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + +napi_value IsDistributedEnableByBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + IsEnabledByBundleParams params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoIsEnabledByBundle {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "isDistributedEnableByBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("IsDistributedEnableByBundle napi_create_async_work start"); + AsyncCallbackInfoIsEnabledByBundle *asynccallbackinfo = (AsyncCallbackInfoIsEnabledByBundle *)data; + + asynccallbackinfo->info.errorCode = NotificationHelper::IsDistributedEnableByBundle( + asynccallbackinfo->params.option, asynccallbackinfo->enable); + }, + AsyncCompleteCallbackIsDistributedEnableByBundle, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +void AsyncCompleteCallbackGetDeviceRemindType(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + ANS_LOGI("GetDeviceRemindType napi_create_async_work end"); + AsyncCallbackInfoGetRemindType *asynccallbackinfo = (AsyncCallbackInfoGetRemindType *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + DeviceRemindType outType = DeviceRemindType::IDLE_DONOT_REMIND; + if (!Common::DeviceRemindTypeCToJS(asynccallbackinfo->remindType, outType)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + napi_create_int32(env, (int32_t)outType, &result); + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + +napi_value GetDeviceRemindType(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + napi_ref callback = nullptr; + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoGetRemindType *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetRemindType {.env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "getDeviceRemindType", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work( + env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetDeviceRemindType napi_create_async_work start"); + AsyncCallbackInfoGetRemindType *asynccallbackinfo = (AsyncCallbackInfoGetRemindType *)data; + asynccallbackinfo->info.errorCode = + NotificationHelper::GetDeviceRemindType(asynccallbackinfo->remindType); + }, + AsyncCompleteCallbackGetDeviceRemindType, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} +} // namespace NotificationNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index 5bb64c12cba66ee9c987c6c6b9c1077e79cb71b8..8ad364e5de996e8331b39b76c9a7f59745bd8a83 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -17,64 +17,128 @@ namespace OHOS { namespace NotificationNapi { -const int DISTURB_MODE_MAX_PARA = 2; -const int DISTURB_MODE_MIN_PARA = 1; +const int SET_DISTURB_MAX_PARA = 2; +const int SET_DISTURB_MIN_PARA = 1; -struct DisturbModeParams { - NotificationConstant::DisturbMode mode = NotificationConstant::DisturbMode::ALLOW_UNKNOWN; +struct SetDoNotDisturbDateParams { + NotificationDoNotDisturbDate date; napi_ref callback = nullptr; }; -struct AsyncCallbackInfoDisturbMode { +struct AsyncCallbackInfoSetDoNotDisturb { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - DisturbModeParams params; + SetDoNotDisturbDateParams params; CallbackPromiseInfo info; }; -napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, DisturbModeParams ¶ms) +struct AsyncCallbackInfoGetDoNotDisturb { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback = nullptr; + NotificationDoNotDisturbDate date; + CallbackPromiseInfo info; +}; + +struct AsyncCallbackInfoSupportDoNotDisturb { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + napi_ref callback = nullptr; + bool isSupported = false; + CallbackPromiseInfo info; +}; + +napi_value GetDoNotDisturbDate(const napi_env &env, const napi_value &argv, SetDoNotDisturbDateParams ¶ms) { ANS_LOGI("enter"); + napi_value value = nullptr; + bool hasProperty = false; + napi_valuetype valuetype = napi_undefined; + // argv[0]: date:type + NAPI_CALL(env, napi_has_named_property(env, argv, "type", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + napi_get_named_property(env, argv, "type", &value); + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + int type = 0; + NotificationConstant::DoNotDisturbType outType = NotificationConstant::DoNotDisturbType::NONE; + napi_get_value_int32(env, value, &type); + ANS_LOGI("type is: %{public}d", type); + if (!Common::DoNotDisturbTypeJSToC(DoNotDisturbType(type), outType)) { + return nullptr; + } + params.date.SetDoNotDisturbType(outType); + + // argv[0]: date:begin + NAPI_CALL(env, napi_has_named_property(env, argv, "begin", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + double begin = 0; + napi_get_named_property(env, argv, "begin", &value); + bool isDate = false; + napi_is_date(env, value, &isDate); + if (!isDate) { + ANS_LOGE("Wrong argument type. Date expected."); + return nullptr; + } + napi_get_date_value(env, value, &begin); + params.date.SetBeginDate(int64_t(begin)); + + // argv[0]: date:end + NAPI_CALL(env, napi_has_named_property(env, argv, "end", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + double end = 0; + napi_get_named_property(env, argv, "end", &value); + isDate = false; + napi_is_date(env, value, &isDate); + if (!isDate) { + ANS_LOGE("Wrong argument type. Date expected."); + return nullptr; + } + napi_get_date_value(env, value, &end); + params.date.SetEndDate(int64_t(end)); - size_t argc = DISTURB_MODE_MAX_PARA; - napi_value argv[DISTURB_MODE_MAX_PARA] = {nullptr}; + return Common::NapiGetNull(env); +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = SET_DISTURB_MAX_PARA; + napi_value argv[SET_DISTURB_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= DISTURB_MODE_MIN_PARA, "Wrong number of arguments"); + NAPI_ASSERT(env, argc >= SET_DISTURB_MIN_PARA, "Wrong number of arguments"); - // argv[0]: mode + // argv[0]: date napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - int mode = 0; - napi_get_value_int32(env, argv[0], &mode); - ANS_LOGI("mode is: %{public}d", mode); - - if (!Common::DisturbModeJSToC(DisturbMode(mode), params.mode)) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (GetDoNotDisturbDate(env, argv[PARAM0], params) == nullptr) { return nullptr; } // argv[1]:callback - if (argc >= DISTURB_MODE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + if (argc >= SET_DISTURB_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); } -napi_value SetDoNotDisturbMode(napi_env env, napi_callback_info info) +napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - DisturbModeParams params {}; + SetDoNotDisturbDateParams params {}; if (ParseParameters(env, info, params) == nullptr) { return Common::NapiGetUndefined(env); } - AsyncCallbackInfoDisturbMode *asynccallbackinfo = - new (std::nothrow) AsyncCallbackInfoDisturbMode {.env = env, .asyncWork = nullptr, .params = params}; + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoSetDoNotDisturb {.env = env, .asyncWork = nullptr, .params = params}; if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } @@ -82,21 +146,21 @@ napi_value SetDoNotDisturbMode(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "setDoNotDisturbMode", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "setDoNotDisturbDate", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, nullptr, resourceName, [](napi_env env, void *data) { - ANS_LOGI("SetDoNotDisturbMode napi_create_async_work start"); - AsyncCallbackInfoDisturbMode *asynccallbackinfo = (AsyncCallbackInfoDisturbMode *)data; - ANS_LOGI("asynccallbackinfo->params.mode = %{public}d", asynccallbackinfo->params.mode); - asynccallbackinfo->info.errorCode = NotificationHelper::SetDisturbMode(asynccallbackinfo->params.mode); - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + ANS_LOGI("SetDoNotDisturbDate napi_create_async_work start"); + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSetDoNotDisturb *)data; + asynccallbackinfo->info.errorCode = NotificationHelper::SetDoNotDisturbDate(asynccallbackinfo->params.date); + ANS_LOGI("SetDoNotDisturbDate date=%{public}s errorCode=%{public}d", + asynccallbackinfo->params.date.Dump().c_str(), asynccallbackinfo->info.errorCode); }, [](napi_env env, napi_status status, void *data) { - ANS_LOGI("SetDoNotDisturbMode napi_create_async_work end"); - AsyncCallbackInfoDisturbMode *asynccallbackinfo = (AsyncCallbackInfoDisturbMode *)data; + ANS_LOGI("SetDoNotDisturbDate napi_create_async_work end"); + AsyncCallbackInfoSetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSetDoNotDisturb *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -122,5 +186,139 @@ napi_value SetDoNotDisturbMode(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackGetDoNotDisturbDate(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoGetDoNotDisturb *)data; + napi_value result = Common::NapiGetNull(env); + if (asynccallbackinfo->info.errorCode == ERR_OK) { + napi_create_object(env, &result); + if (!Common::SetDoNotDisturbDate(env, asynccallbackinfo->date, result)) { + asynccallbackinfo->info.errorCode = ERROR; + } + } + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + +napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + napi_ref callback = nullptr; + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoGetDoNotDisturb {.env = env, .asyncWork = nullptr, .callback = callback}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "getDoNotDisturbDate", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("GetDoNotDisturbDate napi_create_async_work start"); + AsyncCallbackInfoGetDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoGetDoNotDisturb *)data; + asynccallbackinfo->info.errorCode = NotificationHelper::GetDoNotDisturbDate(asynccallbackinfo->date); + ANS_LOGI("GetDoNotDisturbDate errorCode=%{public}d date=%{public}s", + asynccallbackinfo->info.errorCode, asynccallbackinfo->date.Dump().c_str()); + }, + AsyncCompleteCallbackGetDoNotDisturbDate, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + napi_ref callback = nullptr; + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoSupportDoNotDisturb { + .env = env, .asyncWork = nullptr, .callback = callback}; + + if (!asynccallbackinfo) { + return Common::JSParaError(env, callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "supportDoNotDisturbMode", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("SupportDoNotDisturbMode napi_create_async_work start"); + AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSupportDoNotDisturb *)data; + asynccallbackinfo->info.errorCode = + NotificationHelper::DoesSupportDoNotDisturbMode(asynccallbackinfo->isSupported); + ANS_LOGI("SupportDoNotDisturbMode errorCode=%{public}d isSupported=%{public}d", + asynccallbackinfo->info.errorCode, asynccallbackinfo->isSupported); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("SupportDoNotDisturbMode napi_create_async_work end"); + AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSupportDoNotDisturb *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->isSupported, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index b350df6c0a310bb2e048af081579f416bc7c0d4a..c9b896d17d66f963641ff3bc41cc5b15e799f64d 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -22,7 +22,7 @@ const int ENABLE_NOTIFICATION_MIN_PARA = 2; const int IS_NOTIFICATION_ENABLE_MAX_PARA = 2; struct EnableParams { - BundleOption option; + NotificationBundleOption option; bool enable = false; napi_ref callback = nullptr; }; @@ -35,7 +35,7 @@ struct AsyncCallbackInfoEnable { }; struct IsEnableParams { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; bool hasBundleOption = false; }; @@ -56,28 +56,40 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[ENABLE_NOTIFICATION_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= ENABLE_NOTIFICATION_MIN_PARA, "Wrong number of arguments"); + if (argc < ENABLE_NOTIFICATION_MIN_PARA) { + ANS_LOGW("Wrong number of arguments."); + return nullptr; + } // argv[0]: bundle napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if (valuetype != napi_object) { + ANS_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } // argv[1]: enable - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); - napi_get_value_bool(env, argv[1], ¶ms.enable); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_boolean) { + ANS_LOGW("Wrong argument type. Bool expected."); + return nullptr; + } + napi_get_value_bool(env, argv[PARAM1], ¶ms.enable); // argv[2]:callback if (argc >= ENABLE_NOTIFICATION_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[ENABLE_NOTIFICATION_MAX_PARA - 1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[ENABLE_NOTIFICATION_MAX_PARA - 1], 1, ¶ms.callback); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -98,31 +110,57 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[0]: bundle / callback napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_function) || (valuetype == napi_object), - "Wrong argument type. Function or object expected."); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + if ((valuetype != napi_function) && (valuetype != napi_object)) { + ANS_LOGW("Wrong argument type. Function or object expected."); + return nullptr; + } if (valuetype == napi_object) { - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } params.hasBundleOption = true; } else { - napi_create_reference(env, argv[0], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); } // argv[1]:callback if (argc >= IS_NOTIFICATION_ENABLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); } +void AsyncCompleteCallbackEnableNotification(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value EnableNotification(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -149,30 +187,12 @@ napi_value EnableNotification(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("EnableNotification napi_create_async_work start"); AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - std::string deviceId; + std::string deviceId {""}; asynccallbackinfo->info.errorCode = NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( - bundleOption, deviceId, asynccallbackinfo->params.enable); + asynccallbackinfo->params.option, deviceId, asynccallbackinfo->params.enable); ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("EnableNotification napi_create_async_work end"); - AsyncCallbackInfoEnable *asynccallbackinfo = (AsyncCallbackInfoEnable *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } - }, + AsyncCompleteCallbackEnableNotification, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -185,6 +205,30 @@ napi_value EnableNotification(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackIsNotificationEnabled(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; + + napi_value result = nullptr; + napi_get_boolean(env, asynccallbackinfo->allowed, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -213,39 +257,18 @@ napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; if (asynccallbackinfo->params.hasBundleOption) { - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - ANS_LOGI("asynccallbackinfo->params.option.bundle = %{public}s", - asynccallbackinfo->params.option.bundle.c_str()); - ANS_LOGI("asynccallbackinfo->params.option.uid = %{public}d", asynccallbackinfo->params.option.uid); - ANS_LOGI("asynccallbackinfo->allowed = %{public}d", asynccallbackinfo->allowed); + ANS_LOGI("option.bundle = %{public}s option.uid = %{public}d", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid()); asynccallbackinfo->info.errorCode = - NotificationHelper::IsAllowedNotify(bundleOption, asynccallbackinfo->allowed); + NotificationHelper::IsAllowedNotify(asynccallbackinfo->params.option, asynccallbackinfo->allowed); } else { - ANS_LOGI("asynccallbackinfo->allowed = %{public}d", asynccallbackinfo->allowed); asynccallbackinfo->info.errorCode = NotificationHelper::IsAllowedNotify(asynccallbackinfo->allowed); } - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("IsNotificationEnabled napi_create_async_work end"); - AsyncCallbackInfoIsEnable *asynccallbackinfo = (AsyncCallbackInfoIsEnable *)data; - - napi_value result = nullptr; - napi_get_boolean(env, asynccallbackinfo->allowed, &result); - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d, allowed = %{public}d", + asynccallbackinfo->info.errorCode, asynccallbackinfo->allowed); }, + AsyncCompleteCallbackIsNotificationEnabled, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -257,6 +280,5 @@ napi_value IsNotificationEnabled(napi_env env, napi_callback_info info) return promise; } } - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index 788fdd2f2cefe459f564488d828385fc375a9086..f924d7f8fab40f1f46069a824d92fb8a447a2b96 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -17,54 +17,65 @@ namespace OHOS { namespace NotificationNapi { -const int ALL_ACTIVE_MAX_PARA = 1; -const int ACTIVE_OR_NUMS_MAX_PARA = 1; - struct AsyncCallbackInfoActive { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_value result = nullptr; CallbackPromiseInfo info; + std::vector> notifications; + std::vector> requests; + int32_t num = 0; }; -napi_value ParseParametersByAllActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) +void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status status, void *data) { - ANS_LOGI("enter"); + ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); - size_t argc = ALL_ACTIVE_MAX_PARA; - napi_value argv[ALL_ACTIVE_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= ALL_ACTIVE_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; } - return Common::NapiGetNull(env); -} + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_value arr = nullptr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : asynccallbackinfo->notifications) { + if (!vec) { + ANS_LOGW("Invalid Notification object ptr"); + continue; + } + napi_value notificationResult = nullptr; + napi_create_object(env, ¬ificationResult); + if (!Common::SetNotification(env, vec.GetRefPtr(), notificationResult)) { + ANS_LOGW("Set Notification object failed"); + continue; + } + napi_set_element(env, arr, count, notificationResult); + count++; + } + ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); + result = arr; + if ((count == 0) && (asynccallbackinfo->notifications.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } -napi_value ParseParametersByGetActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); - size_t argc = ACTIVE_OR_NUMS_MAX_PARA; - napi_value argv[ACTIVE_OR_NUMS_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= ACTIVE_OR_NUMS_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); } - return Common::NapiGetNull(env); + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } } napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) @@ -72,7 +83,7 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByAllActive(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -93,54 +104,12 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetAllActiveNotifications napi_create_async_work start"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; - std::vector> notifications; - asynccallbackinfo->info.errorCode = NotificationHelper::GetAllActiveNotifications(notifications); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = Common::NapiGetNull(env); - return; - } - napi_value arr = nullptr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : notifications) { - if (!vec) { - ANS_LOGW("Invalid Notification object ptr"); - continue; - } - napi_value result = nullptr; - napi_create_object(env, &result); - if (!Common::SetNotification(env, vec.GetRefPtr(), result)) { - ANS_LOGW("Set Notification object failed"); - continue; - } - napi_set_element(env, arr, count, result); - count++; - } - ANS_LOGI("GetAllActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; - if ((count == 0) && (notifications.size() > 0)) { - asynccallbackinfo->info.errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + asynccallbackinfo->info.errorCode = + NotificationHelper::GetAllActiveNotifications(asynccallbackinfo->notifications); }, + AsyncCompleteCallbackGetAllActiveNotifications, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -153,12 +122,63 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackGetActiveNotifications(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("GetActiveNotifications napi_create_async_work end"); + + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_value arr = nullptr; + int count = 0; + napi_create_array(env, &arr); + for (auto vec : asynccallbackinfo->requests) { + if (!vec) { + ANS_LOGW("Invalid NotificationRequest object ptr"); + continue; + } + napi_value requestResult = nullptr; + napi_create_object(env, &requestResult); + if (!Common::SetNotificationRequest(env, vec.GetRefPtr(), requestResult)) { + ANS_LOGW("Set NotificationRequest object failed"); + continue; + } + napi_set_element(env, arr, count, requestResult); + count++; + } + ANS_LOGI("GetActiveNotifications count = %{public}d", count); + result = arr; + if ((count == 0) && (asynccallbackinfo->requests.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value GetActiveNotifications(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByGetActive(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -179,54 +199,12 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetActiveNotifications napi_create_async_work start"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - - std::vector> requests; - asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotifications(requests); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = Common::NapiGetNull(env); - return; - } - napi_value arr = nullptr; - int count = 0; - napi_create_array(env, &arr); - for (auto vec : requests) { - if (!vec) { - ANS_LOGW("Invalid NotificationRequest object ptr"); - continue; - } - napi_value result = nullptr; - napi_create_object(env, &result); - if (!Common::SetNotificationRequest(env, vec.GetRefPtr(), result)) { - ANS_LOGW("Set NotificationRequest object failed"); - continue; - } - napi_set_element(env, arr, count, result); - count++; - } - ANS_LOGI("GetActiveNotifications count = %{public}d", count); - asynccallbackinfo->result = arr; - if ((count == 0) && (requests.size() > 0)) { - asynccallbackinfo->info.errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetActiveNotifications napi_create_async_work end"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + asynccallbackinfo->info.errorCode = + NotificationHelper::GetActiveNotifications(asynccallbackinfo->requests); }, + AsyncCompleteCallbackGetActiveNotifications, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -239,12 +217,42 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackGetActiveNotificationCount(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("GetActiveNotificationCount napi_create_async_work end"); + + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; + napi_value result = nullptr; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_create_int32(env, asynccallbackinfo->num, &result); + } + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByGetActive(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -265,33 +273,12 @@ napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetActiveNotificationCount napi_create_async_work start"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; - - int32_t num = 0; - asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(num); - ANS_LOGI("GetActiveNotificationCount count = %{public}d", num); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = Common::NapiGetNull(env); - return; - } - napi_create_int32(env, num, &asynccallbackinfo->result); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetActiveNotificationCount napi_create_async_work end"); - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(asynccallbackinfo->num); + ANS_LOGI("GetActiveNotificationCount count = %{public}d", asynccallbackinfo->num); }, + AsyncCompleteCallbackGetActiveNotificationCount, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 864e4a7753901b7fb0bdb210821b1e5ee89b9108..bbb3df5a3b0ad8ea9efe940e548c7f24646c4a40 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -14,12 +14,15 @@ */ #include "init.h" +#include "ans_template.h" #include "cancel.h" #include "constant.h" #include "display_badge.h" +#include "distributed.h" #include "disturb_mode.h" #include "enable_notification.h" #include "get_active.h" +#include "pixel_map_napi.h" #include "publish.h" #include "remove.h" #include "slot.h" @@ -47,6 +50,7 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getActiveNotificationCount", GetActiveNotificationCount), DECLARE_NAPI_FUNCTION("cancel", Cancel), DECLARE_NAPI_FUNCTION("cancelAll", CancelAll), + DECLARE_NAPI_FUNCTION("cancelGroup", CancelGroup), DECLARE_NAPI_FUNCTION("addSlot", AddSlot), DECLARE_NAPI_FUNCTION("addSlots", AddSlots), DECLARE_NAPI_FUNCTION("setSlotByBundle", SetSlotByBundle), @@ -56,11 +60,21 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("getSlotsByBundle", GetSlotsByBundle), DECLARE_NAPI_FUNCTION("removeSlot", RemoveSlot), DECLARE_NAPI_FUNCTION("removeAllSlots", RemoveAllSlots), + DECLARE_NAPI_FUNCTION("removeGroupByBundle", RemoveGroupByBundle), DECLARE_NAPI_FUNCTION("enableNotification", EnableNotification), DECLARE_NAPI_FUNCTION("isNotificationEnabled", IsNotificationEnabled), DECLARE_NAPI_FUNCTION("displayBadge", DisplayBadge), DECLARE_NAPI_FUNCTION("isBadgeDisplayed", IsBadgeDisplayed), - DECLARE_NAPI_FUNCTION("setDoNotDisturbMode", SetDoNotDisturbMode), + DECLARE_NAPI_FUNCTION("setDoNotDisturbDate", SetDoNotDisturbDate), + DECLARE_NAPI_FUNCTION("getDoNotDisturbDate", GetDoNotDisturbDate), + DECLARE_NAPI_FUNCTION("supportDoNotDisturbMode", SupportDoNotDisturbMode), + DECLARE_NAPI_FUNCTION("isSupportTemplate", IsSupportTemplate), + DECLARE_NAPI_FUNCTION("isDistributedEnabled", IsDistributedEnabled), + DECLARE_NAPI_FUNCTION("enableDistributed", EnableDistributed), + DECLARE_NAPI_FUNCTION("enableDistributedByBundle", EnableDistributedByBundle), + DECLARE_NAPI_FUNCTION("enableDistributedSelf", EnableDistributedSelf), + DECLARE_NAPI_FUNCTION("isDistributedEnableByBundle", IsDistributedEnableByBundle), + DECLARE_NAPI_FUNCTION("getDeviceRemindType", GetDeviceRemindType), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); @@ -78,6 +92,8 @@ static napi_value Init(napi_env env, napi_value exports) */ NotificationInit(env, exports); ConstantInit(env, exports); + OHOS::Media::PixelMapNapi::Init(env, exports); + return exports; } @@ -89,6 +105,5 @@ __attribute__((constructor)) void RegisterModule(void) napi_module_register(&_module); } EXTERN_C_END - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index 7bcaf88c2d01a5bad50f3d926230e419fcf475e5..b544ea7d834390545e1fa79c3f81b5cffdc6c3b6 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -12,11 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + #include "publish.h" -#include "notification_basic_content.h" -#include "notification_constant.h" -#include "notification_content.h" -#include "notification_normal_content.h" namespace OHOS { namespace NotificationNapi { @@ -26,12 +23,10 @@ struct AsyncCallbackInfoPublish { napi_env env = nullptr; napi_async_work asyncWork = nullptr; NotificationRequest request; - std::string lable; CallbackPromiseInfo info; }; struct ParametersInfoPublish { - std::string lable; NotificationRequest request; napi_ref callback = nullptr; }; @@ -58,17 +53,17 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); // argv[0] : NotificationRequest - if (Common::GetNotificationRequest(env, argv[0], params.request) == nullptr) { + if (Common::GetNotificationRequest(env, argv[PARAM0], params.request) == nullptr) { return nullptr; } // argv[1] : callback if (argc >= PUBLISH_NOTIFICATION_MAX) { - if (GetCallback(env, argv[1], params) == nullptr) { + if (GetCallback(env, argv[PARAM1], params) == nullptr) { return nullptr; } } @@ -92,7 +87,7 @@ napi_value Publish(napi_env env, napi_callback_info info) if (!asynccallbackinfo) { return Common::JSParaError(env, params.callback); } - asynccallbackinfo->lable = params.lable; + asynccallbackinfo->request = params.request; Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); @@ -111,7 +106,7 @@ napi_value Publish(napi_env env, napi_callback_info info) asynccallbackinfo->request.GetContent()->GetContentType()); asynccallbackinfo->info.errorCode = - NotificationHelper::PublishNotification(asynccallbackinfo->lable, asynccallbackinfo->request); + NotificationHelper::PublishNotification(asynccallbackinfo->request); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("Publish napi_create_async_work complete start"); diff --git a/interfaces/kits/napi/ans/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..23107e15848e53de1dbc8323cdbe2df22dc0667f --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") + +cflags = [] + +config("native_module_config") { + visibility = [ ":*" ] + + include_dirs = [] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + defines = [ + "APP_LOG_TAG = \"ANS_STANDARD\"", + "LOG_DOMAIN = 0xD001800", + ] +} + +ohos_shared_library("reminderagent") { + include_dirs = [ + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", + "//foundation/multimedia/image_standard/interfaces/kits/js/common/include/", + "../../include", + "//third_party/node/src", + "//third_party/libuv/include", + "//third_party/jsoncpp/include", + ] + + configs = [ ":native_module_config" ] + + sources = [ + "../common.cpp", + "../slot.cpp", + "native_module.cpp", + "publish.cpp", + "reminder_common.cpp", + ] + + deps = [ + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/ans/native:ans_innerkits", + "${frameworks_path}/wantagent:wantagent_innerkits", + "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", + "//foundation/multimedia/image_standard/interfaces/innerkits:image", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:abilitykit_native", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "napi:ace_napi", + ] + + relative_install_dir = "module" + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/interfaces/kits/napi/ans/src/reminder/native_module.cpp b/interfaces/kits/napi/ans/src/reminder/native_module.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f4fe3650ba080b8ce115245cd6fed1f18e68a762 --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/native_module.cpp @@ -0,0 +1,108 @@ +/* + * 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 "napi/native_api.h" +#include "napi/native_node_api.h" +#include "reminder/publish.h" +#include "slot.h" + +#include "reminder/native_module.h" + +namespace OHOS { +namespace ReminderAgentNapi { +EXTERN_C_START +napi_value ReminderAgentInit(napi_env env, napi_value exports) +{ + ANSR_LOGI("ReminderAgentInit start"); + napi_property_descriptor desc[] = { + DECLARE_NAPI_FUNCTION("cancelReminder", CancelReminder), + DECLARE_NAPI_FUNCTION("cancelAllReminders", CancelAllReminders), + DECLARE_NAPI_FUNCTION("getValidReminders", GetValidReminders), + DECLARE_NAPI_FUNCTION("publishReminder", PublishReminder), + DECLARE_NAPI_FUNCTION("addNotificationSlot", NotificationNapi::AddSlot), + DECLARE_NAPI_FUNCTION("removeNotificationSlot", NotificationNapi::RemoveSlot), + }; + NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); + return exports; +} + +napi_value ConstantInit(napi_env env, napi_value exports) +{ + ANSR_LOGI("ConstantInit start"); + napi_value objReminderType = nullptr; + napi_create_object(env, &objReminderType); + + napi_value prop = nullptr; + if (napi_create_int32(env, static_cast(ReminderRequest::ReminderType::TIMER), &prop) == napi_ok) { + napi_set_named_property(env, objReminderType, "REMINDER_TYPE_TIMER", prop); + } + if (napi_create_int32(env, static_cast(ReminderRequest::ReminderType::ALARM), &prop) == napi_ok) { + napi_set_named_property(env, objReminderType, "REMINDER_TYPE_ALARM", prop); + } + if (napi_create_int32(env, static_cast(ReminderRequest::ReminderType::CALENDAR), &prop) == napi_ok) { + napi_set_named_property(env, objReminderType, "REMINDER_TYPE_CALENDAR", prop); + } + + napi_value objButtonType = nullptr; + napi_create_object(env, &objButtonType); + if (napi_create_int32(env, static_cast(ReminderRequest::ActionButtonType::CLOSE), &prop) == napi_ok) { + napi_set_named_property(env, objButtonType, "ACTION_BUTTON_TYPE_CLOSE", prop); + } + if (napi_create_int32(env, static_cast(ReminderRequest::ActionButtonType::SNOOZE), &prop) == napi_ok) { + napi_set_named_property(env, objButtonType, "ACTION_BUTTON_TYPE_SNOOZE", prop); + } + + napi_property_descriptor exportFuncs[] = { + DECLARE_NAPI_PROPERTY("ReminderType", objReminderType), + DECLARE_NAPI_PROPERTY("ActionButtonType", objButtonType), + }; + + napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); + return exports; +}; +EXTERN_C_END + +/* + * Module define + */ +static napi_module _module = { + .nm_version = 1, + .nm_flags = 0, + .nm_filename = nullptr, + .nm_register_func = Init, + .nm_modname = "reminderAgent", + .nm_priv = ((void *)0), + .reserved = {0}, +}; + +/* + * function for module exports + */ +static napi_value Init(napi_env env, napi_value exports) +{ + ReminderAgentInit(env, exports); + ConstantInit(env, exports); + return exports; +} + +/* + * Module register function + */ +extern "C" __attribute__((constructor)) void RegisterModule(void) +{ + napi_module_register(&_module); +} +} // namespace ReminderAgentNapi +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp new file mode 100644 index 0000000000000000000000000000000000000000..16084497d2e887590d76c8ca3b2bdd407fb8789b --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -0,0 +1,642 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "common.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" + +#include "reminder/publish.h" + +namespace OHOS { +namespace ReminderAgentNapi { +static const int32_t PUBLISH_PARAM_LEN = 2; +static const int32_t CANCEL_PARAM_LEN = 2; +static const int32_t CANCEL_ALL_PARAM_LEN = 1; +static const int32_t GET_VALID_PARAM_LEN = 1; + +struct AsyncCallbackInfo { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + int32_t reminderId = -1; + std::shared_ptr reminder = nullptr; + NotificationNapi::CallbackPromiseInfo info; + napi_value result = nullptr; +}; + +struct Parameters { + int32_t reminderId = -1; + std::shared_ptr reminder = nullptr; + napi_ref callback = nullptr; +}; + +napi_value GetCallback(const napi_env &env, const napi_value &value, Parameters ¶ms) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + if (valuetype != napi_function) { + ANSR_LOGW("Wrong argument type. Function expected."); + return nullptr; + } + napi_create_reference(env, value, 1, ¶ms.callback); + return NotificationNapi::Common::NapiGetNull(env); +} + +AsyncCallbackInfo* SetAsynccallbackinfo(const napi_env &env, Parameters& params, napi_value& promise) +{ + AsyncCallbackInfo *asynccallbackinfo = new (std::nothrow) AsyncCallbackInfo { + .env = env, .asyncWork = nullptr}; + if (!asynccallbackinfo) { + NotificationNapi::Common::JSParaError(env, params.callback); + return nullptr; + } + NotificationNapi::Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + return asynccallbackinfo; +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +{ + size_t argc = PUBLISH_PARAM_LEN; + napi_value argv[PUBLISH_PARAM_LEN] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc < 1 || argc > PUBLISH_PARAM_LEN) { + ANSR_LOGW("Wrong number of arguments"); + return nullptr; + } + + // argv[0] : reminderRequest + if (ReminderCommon::GetReminderRequest(env, argv[0], params.reminder) == nullptr) { + ANSR_LOGW("[reminderAgent]CreateReminder returns nullptr"); + return nullptr; + } + + // argv[1]: callback + if (argc == PUBLISH_PARAM_LEN) { + if (GetCallback(env, argv[1], params) == nullptr) { + ANSR_LOGW("[reminderAgent]GetCallbak returns nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +{ + ANSR_LOGI("ParseCanCelParameter"); + size_t argc = CANCEL_PARAM_LEN; + napi_value argv[CANCEL_PARAM_LEN] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc < 1 || argc > CANCEL_PARAM_LEN) { + ANSR_LOGW("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: reminder id + int32_t reminderId = -1; + if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId, true)) { + return nullptr; + } + if (reminderId < 0) { + ANSR_LOGW("Param id of cancels Reminder is illegal."); + return nullptr; + } + params.reminderId = reminderId; + + // argv[1]: callback + if (argc >= CANCEL_PARAM_LEN) { + if (GetCallback(env, argv[1], params) == nullptr) { + ANSR_LOGW("GetCallbak is nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +{ + ANSR_LOGI("ParseCanCelAllParameter"); + size_t argc = CANCEL_ALL_PARAM_LEN; + napi_value argv[CANCEL_ALL_PARAM_LEN] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc > CANCEL_ALL_PARAM_LEN) { + ANSR_LOGW("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: callback + if (argc == CANCEL_ALL_PARAM_LEN) { + if (GetCallback(env, argv[0], params) == nullptr) { + ANSR_LOGW("getCallbak is nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ParseGetValidParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +{ + size_t argc = GET_VALID_PARAM_LEN; + napi_value argv[GET_VALID_PARAM_LEN] = {nullptr}; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, NULL, NULL)); + if (argc < 0 || argc > GET_VALID_PARAM_LEN) { + ANSR_LOGW("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: callback + if (argc == GET_VALID_PARAM_LEN) { + if (GetCallback(env, argv[0], params) == nullptr) { + ANSR_LOGW("getCallbak is nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value CancelReminder(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("Cancel reminder"); + + // param + Parameters params; + if (ParseCanCelParameter(env, info, params) == nullptr) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // promise + napi_value promise = nullptr; + AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); + if (!asynccallbackinfo) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + asynccallbackinfo->reminderId = params.reminderId; + + // resource name + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "cancelReminder", NAPI_AUTO_LENGTH, &resourceName); + + // create and queue async work + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANSR_LOGI("Cancel napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + asynccallbackinfo->info.errorCode = ReminderHelper::CancelReminder(asynccallbackinfo->reminderId); + }, + [](napi_env env, napi_status status, void *data) { + ANSR_LOGI("Cancel napi_create_async_work complete start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + ANSR_LOGI("Cancel napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return NotificationNapi::Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value CancelAllReminders(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("Cancel all reminder"); + + // param + Parameters params; + if (ParseCanCelAllParameter(env, info, params) == nullptr) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // promise + napi_value promise = nullptr; + AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); + if (!asynccallbackinfo) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // resource name + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "cancelAllReminders", NAPI_AUTO_LENGTH, &resourceName); + + // create and queue async work + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANSR_LOGI("CancelAll napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + asynccallbackinfo->info.errorCode = ReminderHelper::CancelAllReminders(); + }, + [](napi_env env, napi_status status, void *data) { + ANSR_LOGD("CancelAll napi_create_async_work complete start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + ANSR_LOGD("CancelAll napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return NotificationNapi::Common::NapiGetNull(env); + } else { + return promise; + } +} + +void ParseReminderTimer(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + napi_value value = nullptr; + ReminderRequestTimer& timer = (ReminderRequestTimer&)reminder; + napi_create_uint32(env, timer.GetInitInfo(), &value); + napi_set_named_property(env, result, TIMER_COUNT_DOWN_TIME, value); +} + +void ParseReminderAlarm(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + // hour + napi_value value = nullptr; + ReminderRequestAlarm& alarm = (ReminderRequestAlarm&)reminder; + napi_create_uint32(env, static_cast(alarm.GetHour()), &value); + napi_set_named_property(env, result, ALARM_HOUR, value); + + // minute + napi_create_uint32(env, static_cast(alarm.GetMinute()), &value); + napi_set_named_property(env, result, ALARM_MINUTE, value); + + // daysOfWeek + napi_create_array(env, &value); + napi_set_named_property(env, result, ALARM_DAYS_OF_WEEK, value); + int count = 0; + for (auto day : alarm.GetDaysOfWeek()) { + if (day) { + napi_value napiDay = nullptr; + napi_create_int32(env, day, &napiDay); + napi_set_element(env, value, count, napiDay); + count++; + } + } +} + +void ParseReminderCalendar(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + // dateTime + napi_value value = nullptr; + ReminderRequestCalendar& calender = (ReminderRequestCalendar&)reminder; + napi_value dateTime = nullptr; + napi_create_object(env, &dateTime); + napi_set_named_property(env, result, CALENDAR_DATE_TIME, dateTime); + + napi_create_uint32(env, static_cast(calender.GetYear()), &value); + napi_set_named_property(env, dateTime, CALENDAR_YEAR, value); + napi_create_uint32(env, static_cast(calender.GetMonth()), &value); + napi_set_named_property(env, dateTime, CALENDAR_MONTH, value); + napi_create_uint32(env, static_cast(calender.GetDay()), &value); + napi_set_named_property(env, dateTime, CALENDAR_DAY, value); + napi_create_uint32(env, static_cast(calender.GetHour()), &value); + napi_set_named_property(env, dateTime, CALENDAR_HOUR, value); + napi_create_uint32(env, static_cast(calender.GetMinute()), &value); + napi_set_named_property(env, dateTime, CALENDAR_MINUTE, value); + napi_create_uint32(env, static_cast(calender.GetSecond()), &value); + napi_set_named_property(env, dateTime, CALENDAR_SECOND, value); + + // repeatMonths + napi_create_array(env, &value); + napi_set_named_property(env, result, CALENDAR_REPEAT_MONTHS, value); + int count = 0; + for (auto month : calender.GetRepeatMonths()) { + napi_value napiDay = nullptr; + napi_create_int32(env, month, &napiDay); + napi_set_element(env, value, count, napiDay); + count++; + } + + // repeatDays + napi_create_array(env, &value); + napi_set_named_property(env, result, CALENDAR_REPEAT_DAYS, value); + count = 0; + for (auto day : calender.GetRepeatDays()) { + napi_value napiDay = nullptr; + napi_create_int32(env, day, &napiDay); + napi_set_element(env, value, count, napiDay); + count++; + } +} + +void ParseReminder( + const napi_env &env, ReminderRequest::ReminderType &type, ReminderRequest &reminder, napi_value &result) +{ + switch (type) { + case ReminderRequest::ReminderType::TIMER: { + ParseReminderTimer(env, reminder, result); + break; + } + case ReminderRequest::ReminderType::ALARM: { + ParseReminderAlarm(env, reminder, result); + break; + } + case ReminderRequest::ReminderType::CALENDAR: { + ParseReminderCalendar(env, reminder, result); + break; + } + default: { + break; + } + } +} + +void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + auto actionButtonsMap = reminder.GetActionButtons(); + + // create array + napi_value array = nullptr; + napi_create_array(env, &array); + napi_set_named_property(env, result, ACTION_BUTTON, array); + int index = 0; + for (std::map::iterator it + = actionButtonsMap.begin(); it != actionButtonsMap.end(); ++it) { + // create obj + napi_value actionButton = nullptr; + napi_create_object(env, &actionButton); + + napi_value buttonInfo = nullptr; + napi_create_uint32(env, static_cast(it->second.type), &buttonInfo); + napi_set_named_property(env, actionButton, ACTION_BUTTON_TYPE, buttonInfo); + napi_create_string_utf8(env, (it->second.title).c_str(), NAPI_AUTO_LENGTH, &buttonInfo); + napi_set_named_property(env, actionButton, ACTION_BUTTON_TITLE, buttonInfo); + + // add obj to array + napi_set_element(env, array, index, actionButton); + index++; + } +} + +void ParseWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + // create obj + napi_value wantAgentInfo = nullptr; + napi_create_object(env, &wantAgentInfo); + napi_set_named_property(env, result, WANT_AGENT, wantAgentInfo); + + napi_value info = nullptr; + napi_create_string_utf8(env, (reminder.GetWantAgentInfo()->pkgName).c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_named_property(env, wantAgentInfo, WANT_AGENT_PKG, info); + napi_create_string_utf8(env, (reminder.GetWantAgentInfo()->abilityName).c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_named_property(env, wantAgentInfo, WANT_AGENT_ABILITY, info); +} + +void ParseMaxScreenWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + // create obj + napi_value maxScreenWantAgentInfo = nullptr; + napi_create_object(env, &maxScreenWantAgentInfo); + napi_set_named_property(env, result, MAX_SCREEN_WANT_AGENT, maxScreenWantAgentInfo); + + napi_value info = nullptr; + napi_create_string_utf8(env, (reminder.GetMaxScreenWantAgentInfo()->pkgName).c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_named_property(env, maxScreenWantAgentInfo, MAX_SCREEN_WANT_AGENT_PKG, info); + napi_create_string_utf8(env, (reminder.GetMaxScreenWantAgentInfo()->abilityName).c_str(), NAPI_AUTO_LENGTH, &info); + napi_set_named_property(env, maxScreenWantAgentInfo, MAX_SCREEN_WANT_AGENT_ABILITY, info); +} + +napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + ANSR_LOGI("enter"); + napi_value value = nullptr; + + napi_create_string_utf8(env, reminder.Dump().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, "reminder", value); + + // type + ReminderRequest::ReminderType type = reminder.GetReminderType(); + napi_create_int32(env, static_cast(type), &value); + napi_set_named_property(env, result, REMINDER_TYPE, value); + + // reminder + ParseReminder(env, type, reminder, result); + + // title + napi_create_string_utf8(env, reminder.GetTitle().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, TITLE, value); + + // content + napi_create_string_utf8(env, reminder.GetContent().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, CONTENT, value); + + // expiredContent + napi_create_string_utf8(env, reminder.GetExpiredContent().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, EXPIRED_CONTENT, value); + + // snoozeContent + napi_create_string_utf8(env, reminder.GetSnoozeContent().c_str(), NAPI_AUTO_LENGTH, &value); + napi_set_named_property(env, result, SNOOZE_CONTENT, value); + + // ringDuration + napi_create_int64(env, reminder.GetRingDuration(), &value); + napi_set_named_property(env, result, RING_DURATION, value); + + // timeInterval + napi_create_int64(env, reminder.GetTimeInterval(), &value); + napi_set_named_property(env, result, TIME_INTERVAL, value); + + // notificationId + napi_create_int32(env, reminder.GetNotificationId(), &value); + napi_set_named_property(env, result, NOTIFICATION_ID, value); + + // snoozeTimes + napi_create_int32(env, reminder.GetSnoozeTimes(), &value); + napi_set_named_property(env, result, SNOOZE_TIMES, value); + + // slotType + NotificationNapi::SlotType jsSlotType; + NotificationNapi::Common::SlotTypeCToJS(reminder.GetSlotType(), jsSlotType); + napi_create_int32(env, static_cast(jsSlotType), &value); + napi_set_named_property(env, result, SLOT_TYPE, value); + + // wantAgent + ParseWantAgent(env, reminder, result); + + // maxScreenWantAgent + ParseMaxScreenWantAgent(env, reminder, result); + + // actionButtons + ParseActionButtons(env, reminder, result); + return NotificationNapi::Common::NapiGetBoolean(env, true); +} + +void GetValidRemindersInner(napi_env env, std::vector>& validReminders, napi_value& arr) +{ + int count = 0; + napi_create_array(env, &arr); + for (auto reminder : validReminders) { + if (reminder == nullptr) { + ANSR_LOGW("reminder is null"); + continue; + } + napi_value result = nullptr; + napi_create_object(env, &result); + if (!SetValidReminder(env, *reminder, result)) { + ANSR_LOGW("Set reminder object failed"); + continue; + } + napi_set_element(env, arr, count, result); + count++; + } + ANSR_LOGI("GetValid reminders count = %{public}d", count); +} + +napi_value GetValidReminders(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("Get valid reminders"); + + // param + Parameters params; + if (ParseGetValidParameter(env, info, params) == nullptr) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // promise + napi_value promise = nullptr; + AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); + if (!asynccallbackinfo) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // resource name + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "getValidReminders", NAPI_AUTO_LENGTH, &resourceName); + + // create and start async work + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANSR_LOGI("GetValid reminders napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + std::vector> validReminders; + asynccallbackinfo->info.errorCode = ReminderHelper::GetValidReminders(validReminders); + if (asynccallbackinfo->info.errorCode != ERR_OK) { + asynccallbackinfo->result = NotificationNapi::Common::NapiGetNull(env); + return; + } + napi_value arr = nullptr; + GetValidRemindersInner(env, validReminders, arr); + asynccallbackinfo->result = arr; + }, + [](napi_env env, napi_status status, void *data) { + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, asynccallbackinfo->result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return NotificationNapi::Common::NapiGetNull(env); + } else { + return promise; + } +} + +napi_value PublishReminder(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("PublishReminder"); + + // param + Parameters params; + if (ParseParameters(env, info, params) == nullptr) { + ANSR_LOGW("Parse params error"); + return NotificationNapi::Common::JSParaError(env, params.callback); + } + + // promise + napi_value promise = nullptr; + AsyncCallbackInfo *asynccallbackinfo = SetAsynccallbackinfo(env, params, promise); + if (!asynccallbackinfo) { + return NotificationNapi::Common::JSParaError(env, params.callback); + } + asynccallbackinfo->reminder = params.reminder; + + // resource name + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "publishReminder", NAPI_AUTO_LENGTH, &resourceName); + + // create and start async work + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANSR_LOGI("Publish napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); + ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + + // reminderId + napi_value napiReminderId = nullptr; + napi_create_int32(env, asynccallbackinfo->reminder->GetReminderId(), &napiReminderId); + asynccallbackinfo->result = napiReminderId; + }, + [](napi_env env, napi_status status, void *data) { + ANSR_LOGI("Publish napi_create_async_work complete start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + NotificationNapi::Common::ReturnCallbackPromise( + env, asynccallbackinfo->info, asynccallbackinfo->result); + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + ANSR_LOGI("Publish napi_create_async_work complete end"); + }, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return NotificationNapi::Common::NapiGetNull(env); + } else { + return promise; + } +} +} +} \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4bf5d4985de6999774a41888df7e9a0fa2046c83 --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -0,0 +1,515 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "common.h" +#include "reminder_request_alarm.h" +#include "reminder_request_calendar.h" +#include "reminder_request_timer.h" + +#include "reminder/reminder_common.h" + +namespace OHOS { +namespace ReminderAgentNapi { +using namespace OHOS::Notification; + +napi_value ReminderCommon::GetReminderRequest( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_typeof(env, value, &valuetype)); + if (valuetype != napi_object) { + ANSR_LOGW("Wrong argument type. Object expected."); + return nullptr; + } + + // gen reminder + if (GenReminder(env, value, reminder) == nullptr) { + return nullptr; + } + return NotificationNapi::Common::NapiGetNull(env); +} + +bool ReminderCommon::GenActionButtons( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + char str[NotificationNapi::STR_MAX_SIZE] = {0}; + napi_valuetype valuetype = napi_undefined; + napi_value actionButtons = nullptr; + if (!GetObject(env, value, ReminderAgentNapi::ACTION_BUTTON, actionButtons)) { + return true; + } + bool isArray = false; + napi_is_array(env, actionButtons, &isArray); + if (!isArray) { + ANSR_LOGW("Wrong argument type:%{public}s. array expected.", ACTION_BUTTON); + return false; + } + + uint32_t length = 0; + napi_get_array_length(env, actionButtons, &length); + for (size_t i = 0; i < length; i++) { + napi_value actionButton = nullptr; + napi_get_element(env, actionButtons, i, &actionButton); + NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); + if (valuetype != napi_object) { + ANSR_LOGW("Wrong element type:%{public}s. object expected.", ACTION_BUTTON); + return false; + } + + int32_t buttonType = static_cast(ReminderRequest::ActionButtonType::INVALID); + if (GetStringUtf8(env, actionButton, + ReminderAgentNapi::ACTION_BUTTON_TITLE, str, NotificationNapi::STR_MAX_SIZE) && + GetInt32(env, actionButton, ReminderAgentNapi::ACTION_BUTTON_TYPE, buttonType, false)) { + if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE && + ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::SNOOZE) { + ANSR_LOGW("Wrong argument type:%{public}s. buttonType not support.", ACTION_BUTTON); + return false; + } + std::string title(str); + reminder->SetActionButton(title, static_cast(buttonType)); + ANSR_LOGD("button title=%{public}s, type=%{public}d", title.c_str(), buttonType); + } else { + ANSR_LOGW("Parse action button error."); + return false; + } + } + return true; +} + +void ReminderCommon::GenWantAgent( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + char str[NotificationNapi::STR_MAX_SIZE] = {0}; + napi_value wantAgent = nullptr; + if (GetObject(env, value, ReminderAgentNapi::WANT_AGENT, wantAgent)) { + auto wantAgentInfo = std::make_shared(); + if (GetStringUtf8(env, wantAgent, ReminderAgentNapi::WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) { + wantAgentInfo->pkgName = str; + } + if (GetStringUtf8(env, wantAgent, + ReminderAgentNapi::WANT_AGENT_ABILITY, str, NotificationNapi::STR_MAX_SIZE)) { + wantAgentInfo->abilityName = str; + } + reminder->SetWantAgentInfo(wantAgentInfo); + } +} + +void ReminderCommon::GenMaxScreenWantAgent( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + char str[NotificationNapi::STR_MAX_SIZE] = {0}; + napi_value maxScreenWantAgent = nullptr; + if (GetObject(env, value, ReminderAgentNapi::MAX_SCREEN_WANT_AGENT, maxScreenWantAgent)) { + std::shared_ptr maxScreenWantAgentInfo( + new ReminderRequest::MaxScreenAgentInfo()); + if (GetStringUtf8(env, maxScreenWantAgent, + ReminderAgentNapi::MAX_SCREEN_WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) { + maxScreenWantAgentInfo->pkgName = str; + } + if (GetStringUtf8(env, maxScreenWantAgent, + ReminderAgentNapi::MAX_SCREEN_WANT_AGENT_ABILITY, str, NotificationNapi::STR_MAX_SIZE)) { + maxScreenWantAgentInfo->abilityName = str; + } + reminder->SetMaxScreenWantAgentInfo(maxScreenWantAgentInfo); + } +} +bool ReminderCommon::CreateReminder( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + napi_value result = nullptr; + napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); + int32_t reminderType = -1; + napi_get_value_int32(env, result, &reminderType); + switch (ReminderRequest::ReminderType(reminderType)) { + case ReminderRequest::ReminderType::TIMER: + CreateReminderTimer(env, value, reminder); + break; + case ReminderRequest::ReminderType::ALARM: + CreateReminderAlarm(env, value, reminder); + break; + case ReminderRequest::ReminderType::CALENDAR: + CreateReminderCalendar(env, value, reminder); + break; + default: + ANSR_LOGW("Reminder type is not support. (type:%{public}d)", reminderType); + break; + } + if (reminder == nullptr) { + ANSR_LOGW("Instance of reminder error."); + return false; + } + return true; +} + +napi_value ReminderCommon::GenReminder( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + // reminderType + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); + if (!hasProperty) { + ANSR_LOGW("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); + return nullptr; + } + + // createReminder + if (!CreateReminder(env, value, reminder)) { + return nullptr; + } + char str[NotificationNapi::STR_MAX_SIZE] = {0}; + + // title + if (GetStringUtf8(env, value, ReminderAgentNapi::TITLE, str, NotificationNapi::STR_MAX_SIZE)) { + reminder->SetTitle(str); + } + + // content + if (GetStringUtf8(env, value, ReminderAgentNapi::CONTENT, str, NotificationNapi::STR_MAX_SIZE)) { + reminder->SetContent(str); + } + + // expiredContent + if (GetStringUtf8(env, value, ReminderAgentNapi::EXPIRED_CONTENT, str, NotificationNapi::STR_MAX_SIZE)) { + reminder->SetExpiredContent(str); + } + + // snoozeContent + if (GetStringUtf8(env, value, ReminderAgentNapi::SNOOZE_CONTENT, str, NotificationNapi::STR_MAX_SIZE)) { + reminder->SetSnoozeContent(str); + } + + // ringDuration + int64_t propVal = 0; + if (GetInt64(env, value, ReminderAgentNapi::RING_DURATION, propVal)) { + if (propVal < 0) { + reminder->SetRingDuration(0); + } else { + uint64_t ringDuration = static_cast(propVal); + reminder->SetRingDuration(ringDuration); + } + } + + // timeInterval + if (GetInt64(env, value, ReminderAgentNapi::TIME_INTERVAL, propVal)) { + if (propVal < 0) { + reminder->SetTimeInterval(0); + } else { + uint64_t timeInterval = static_cast(propVal); + reminder->SetTimeInterval(timeInterval); + } + } + + // notificationId + int32_t propertyVal = 0; + if (GetInt32(env, value, ReminderAgentNapi::NOTIFICATION_ID, propertyVal, false)) { + reminder->SetNotificationId(propertyVal); + } + + // snoozeTimes + if (GetInt32(env, value, ReminderAgentNapi::SNOOZE_TIMES, propertyVal, false)) { + if (propertyVal < 0) { + reminder->SetSnoozeTimes(0); + } else { + uint8_t snoozeTimes = propertyVal > UINT8_MAX ? UINT8_MAX : propertyVal; + reminder->SetSnoozeTimes(static_cast(snoozeTimes)); + } + } + + // slotType + int32_t slotType = 0; + if (GetInt32(env, value, ReminderAgentNapi::SLOT_TYPE, slotType, false)) { + enum NotificationConstant::SlotType actureType = NotificationConstant::SlotType::OTHER; + if (!NotificationNapi::Common::SlotTypeJSToC(NotificationNapi::SlotType(slotType), actureType)) { + ANSR_LOGW("slot type not support."); + return nullptr; + } + reminder->SetSlotType(actureType); + } + + // wantAgent + GenWantAgent(env, value, reminder); + + // maxScreenWantAgent + GenMaxScreenWantAgent(env, value, reminder); + + // actionButtons + if (!GenActionButtons(env, value, reminder)) { + return nullptr; + } + return NotificationNapi::Common::NapiGetNull(env); +} + +bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value, + const char* propertyName, char* propertyVal, const int32_t size) +{ + bool hasProperty = false; + napi_value result = nullptr; + napi_valuetype valuetype = napi_undefined; + size_t strLen = 0; + + NAPI_CALL(env, napi_has_named_property(env, value, propertyName, &hasProperty)); + if (hasProperty) { + napi_get_named_property(env, value, propertyName, &result); + NAPI_CALL(env, napi_typeof(env, result, &valuetype)); + if (valuetype != napi_string) { + ANSR_LOGW("Wrong argument type:%{public}s. string expected.", propertyName); + return false; + } + NAPI_CALL(env, napi_get_value_string_utf8(env, result, propertyVal, size - 1, &strLen)); + } + return hasProperty; +} + +bool ReminderCommon::GetInt32(const napi_env &env, const napi_value &value, + const char* propertyName, int32_t& propertyVal, bool isNecessary) +{ + napi_value result = nullptr; + if (!GetPropertyValIfExist(env, value, propertyName, result)) { + if (isNecessary) { + ANSR_LOGW("Correct property %{public}s expected.", propertyName); + } + return false; + } + napi_get_value_int32(env, result, &propertyVal); + return true; +} + +bool ReminderCommon::GetInt64(const napi_env &env, const napi_value &value, + const char* propertyName, int64_t& propertyVal) +{ + napi_value result = nullptr; + if (!GetPropertyValIfExist(env, value, propertyName, result)) { + return false; + } + napi_get_value_int64(env, result, &propertyVal); + return true; +} + +bool ReminderCommon::GetPropertyValIfExist(const napi_env &env, const napi_value &value, + const char* propertyName, napi_value& propertyVal) +{ + napi_valuetype valuetype = napi_undefined; + if (propertyName == nullptr) { + propertyVal = value; + } else { + bool hasProperty = false; + NAPI_CALL(env, napi_has_named_property(env, value, propertyName, &hasProperty)); + if (!hasProperty) { + return false; + } + napi_get_named_property(env, value, propertyName, &propertyVal); + } + NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); + if (valuetype != napi_number) { + if (propertyName == nullptr) { + ANSR_LOGW("Wrong argument type. number expected."); + } else { + ANSR_LOGW("Wrong argument type:%{public}s, number expected.", propertyName); + } + return false; + } + return true; +} + +bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value, + const char* propertyName, napi_value& propertyVal) +{ + bool hasProperty = false; + napi_valuetype valuetype = napi_undefined; + + NAPI_CALL(env, napi_has_named_property(env, value, propertyName, &hasProperty)); + if (!hasProperty) { + return false; + } + napi_get_named_property(env, value, propertyName, &propertyVal); + NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); + if (valuetype != napi_object) { + ANSR_LOGW("Wrong argument type:%{public}s. object expected.", propertyName); + return false; + } + return true; +} + +napi_value ReminderCommon::CreateReminderTimer( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + int64_t propertyCountDownTime = 0; + if (!GetInt64(env, value, ReminderAgentNapi::TIMER_COUNT_DOWN_TIME, propertyCountDownTime)) { + ANSR_LOGW("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); + return nullptr; + } + + if (propertyCountDownTime <= 0) { + ANSR_LOGW("Create countDown reminder fail: designated %{public}s should be set larger than 0.", + ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); + return nullptr; + } + + reminder = std::make_shared(static_cast(propertyCountDownTime)); + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ReminderCommon::CreateReminderAlarm( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + // hour + int32_t propertyHourVal = 0; + if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal, true)) { + return nullptr; + } + + // minute + int32_t propertyMinuteVal = 0; + if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal, true)) { + return nullptr; + } + if (propertyHourVal < 0 || propertyHourVal > 23) { + ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 23].", + ReminderAgentNapi::ALARM_HOUR); + return nullptr; + } + if (propertyMinuteVal < 0 || propertyMinuteVal > 59) { + ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 59].", + ReminderAgentNapi::ALARM_MINUTE); + return nullptr; + } + + // daysOfWeek + std::vector daysOfWeek; + uint8_t maxDaysOfWeek = 7; + if (ParseInt32Array(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, daysOfWeek, maxDaysOfWeek) == nullptr) { + return nullptr; + } + reminder = std::make_shared( + static_cast(propertyHourVal), static_cast(propertyMinuteVal), daysOfWeek); + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ReminderCommon::CreateReminderCalendar( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + napi_value dateTimeObj = nullptr; + if (!GetObject(env, value, ReminderAgentNapi::CALENDAR_DATE_TIME, dateTimeObj)) { + ANSR_LOGW("Create calender reminder fail: dateTime must be setted."); + return nullptr; + } + + // year month day hour minute second + int32_t propertyYearVal = 0; + int32_t propertyMonthVal = 0; + int32_t propertyDayVal = 0; + int32_t propertyHourVal = 0; + int32_t propertyMinteVal = 0; + if (!GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_YEAR, propertyYearVal, true) + || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MONTH, propertyMonthVal, true) + || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_DAY, propertyDayVal, true) + || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_HOUR, propertyHourVal, true) + || !GetInt32(env, dateTimeObj, ReminderAgentNapi::CALENDAR_MINUTE, propertyMinteVal, true)) { + return nullptr; + } + if (!CheckCalendarParams(propertyYearVal, propertyMonthVal, propertyDayVal, + propertyHourVal, propertyMinteVal)) { + return nullptr; + } + + // repeatMonth + std::vector repeatMonths; + if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_MONTHS, repeatMonths, + ReminderRequestCalendar::MAX_MONTHS_OF_YEAR) == nullptr) { + return nullptr; + } + + // repeatDay + std::vector repeatDays; + if (ParseInt32Array(env, value, ReminderAgentNapi::CALENDAR_REPEAT_DAYS, repeatDays, + ReminderRequestCalendar::MAX_DAYS_OF_MONTH) == nullptr) { + return nullptr; + } + + tm dateTime; + dateTime.tm_year = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::YEAR, propertyYearVal); + dateTime.tm_mon = ReminderRequest::GetCTime(ReminderRequest::TimeTransferType::MONTH, propertyMonthVal); + dateTime.tm_mday = propertyDayVal; + dateTime.tm_hour = propertyHourVal; + dateTime.tm_min = propertyMinteVal; + dateTime.tm_sec = 0; + reminder = std::make_shared(dateTime, repeatMonths, repeatDays); + return NotificationNapi::Common::NapiGetNull(env); +} + +bool ReminderCommon::CheckCalendarParams(const int32_t &year, const int32_t &month, const int32_t &day, + const int32_t &hour, const int32_t &min) +{ + if (year < 0 || year > UINT16_MAX) { + ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [0, %{public}u]", + ReminderAgentNapi::CALENDAR_YEAR, UINT16_MAX); + return false; + } + if (month < 1 || month > ReminderRequestCalendar::MAX_MONTHS_OF_YEAR) { + ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [1, %{public}u]", + ReminderAgentNapi::CALENDAR_MONTH, ReminderRequestCalendar::MAX_MONTHS_OF_YEAR); + return false; + } + if (day < 1 || day > ReminderRequestCalendar::MAX_DAYS_OF_MONTH) { + ANSR_LOGW("Create calender reminder fail: designated %{public}s must between [1, %{public}u]", + ReminderAgentNapi::CALENDAR_DAY, ReminderRequestCalendar::MAX_DAYS_OF_MONTH); + return false; + } + return true; +} + +napi_value ReminderCommon::ParseInt32Array(const napi_env &env, const napi_value &value, + const char* propertyName, std::vector &propertyVal, uint8_t maxLen) +{ + napi_value result = nullptr; + if (!GetObject(env, value, propertyName, result)) { + return NotificationNapi::Common::NapiGetNull(env); + } + if (result != nullptr) { + bool isArray = false; + napi_is_array(env, result, &isArray); + if (!isArray) { + ANSR_LOGW("Property %{public}s is expected to be an array.", propertyName); + return nullptr; + } + uint32_t length = 0; + napi_get_array_length(env, result, &length); + if (length > maxLen) { + ANSR_LOGW("The max length of array of %{public}s is %{public}d.", propertyName, maxLen); + return nullptr; + } + napi_valuetype valuetype = napi_undefined; + for (size_t i = 0; i < length; i++) { + int32_t propertyDayVal = 10; + napi_value repeatDayVal = nullptr; + napi_get_element(env, result, i, &repeatDayVal); + NAPI_CALL(env, napi_typeof(env, repeatDayVal, &valuetype)); + if (valuetype != napi_number) { + ANSR_LOGW("%{public}s's element is expected to be number.", propertyName); + return nullptr; + } + napi_get_value_int32(env, repeatDayVal, &propertyDayVal); + if (propertyDayVal < 1 || propertyDayVal > maxLen) { + ANSR_LOGW("%{public}s's element must between [1, %{public}d].", propertyName, maxLen); + return nullptr; + } + propertyVal.push_back(static_cast(propertyDayVal)); + } + } + return NotificationNapi::Common::NapiGetNull(env); +} +} +} diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index 90c71f2f2cb521612b05eb5fb290c2cdfc75d9c5..0757bbea307e3fd2cc35436d90ec5e5db6d36214 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -13,10 +13,8 @@ * limitations under the License. */ -#include "remove.h" #include -#include "common.h" -#include "notification_bundle_option.h" +#include "remove.h" namespace OHOS { namespace NotificationNapi { @@ -29,8 +27,11 @@ const int REMOVE_ALL_WHEN_HAS_PARA_MIN_PARA = 1; const int REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA = 2; const int REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA = 3; +const int REMOVE_GROUP_BY_BUNDLE_MIN_PARA = 2; +const int REMOVE_GROUP_BY_BUNDLE_MAX_PARA = 3; + struct BundleAndKeyInfo { - BundleOption option; + NotificationBundleOption option; NotificationKey key; }; @@ -47,6 +48,19 @@ struct AsyncCallbackInfoRemove { CallbackPromiseInfo info; }; +struct RemoveParamsGroupByBundle { + NotificationBundleOption option; + std::string groupName = ""; + napi_ref callback = nullptr; +}; + +struct AsyncCallbackInfoRemoveGroupByBundle { + napi_env env = nullptr; + napi_async_work asyncWork = nullptr; + RemoveParamsGroupByBundle params {}; + CallbackPromiseInfo info; +}; + napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, RemoveParams ¶ms) { ANS_LOGI("enter"); @@ -58,7 +72,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, NAPI_ASSERT(env, argc >= REMOVE_MIN_PARA, "Wrong number of arguments"); napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, (valuetype == napi_string) || (valuetype == napi_object), "Wrong argument type. String or object expected."); @@ -66,28 +80,28 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[0]: hashCode size_t strLen = 0; char str[STR_MAX_SIZE] = {0}; - NAPI_CALL(env, napi_get_value_string_utf8(env, argv[0], str, STR_MAX_SIZE - 1, &strLen)); + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM0], str, STR_MAX_SIZE - 1, &strLen)); params.hashcode = str; // argv[1]:callback if (argc >= REMOVE_OR_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } } else { NAPI_ASSERT(env, argc >= REMOVE_BY_BUNDLE_AND_KEY_MIN_PARA, "Wrong number of arguments"); BundleAndKeyInfo info {}; // argv[0]: BundleOption - auto retValue = Common::GetBundleOption(env, argv[0], info.option); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], info.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } // argv[1]: NotificationKey - retValue = Common::GetNotificationKey(env, argv[1], info.key); + retValue = Common::GetNotificationKey(env, argv[PARAM1], info.key); if (retValue == nullptr) { ANS_LOGE("GetNotificationKey failed."); return nullptr; @@ -97,9 +111,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA - 1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[REMOVE_BY_BUNDLE_AND_KEY_MAX_PARA - 1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } } @@ -120,31 +134,70 @@ napi_value ParseParametersByRemoveAll(const napi_env &env, const napi_callback_i } napi_valuetype valuetype = napi_undefined; - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, (valuetype == napi_function) || (valuetype == napi_object), "Wrong argument type. Function or object expected."); if (valuetype == napi_function) { // argv[0]: callback - napi_create_reference(env, argv[0], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM0], 1, ¶ms.callback); } else { BundleAndKeyInfo info {}; // argv[0]: BundleOption - auto retValue = Common::GetBundleOption(env, argv[0], info.option); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], info.option); NAPI_ASSERT(env, retValue != nullptr, "GetBundleOption failed."); params.bundleAndKeyInfo = info; // argv[1]:callback if (argc >= REMOVE_ALL_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } } return Common::NapiGetNull(env); } +napi_value ParseParameters( + const napi_env &env, const napi_callback_info &info, RemoveParamsGroupByBundle ¶ms) +{ + ANS_LOGI("enter"); + + size_t argc = REMOVE_GROUP_BY_BUNDLE_MAX_PARA; + napi_value argv[REMOVE_GROUP_BY_BUNDLE_MAX_PARA] = {nullptr}; + napi_value thisVar = nullptr; + napi_valuetype valuetype = napi_undefined; + NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); + NAPI_ASSERT(env, argc >= REMOVE_GROUP_BY_BUNDLE_MIN_PARA, "Wrong number of arguments"); + + // argv[0]: bundle + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: groupName: string + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + NAPI_CALL(env, napi_get_value_string_utf8(env, argv[PARAM1], str, STR_MAX_SIZE - 1, &strLen)); + params.groupName = str; + + // argv[2]:callback + if (argc >= REMOVE_GROUP_BY_BUNDLE_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + napi_value Remove(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -178,9 +231,8 @@ napi_value Remove(napi_env env, napi_callback_info info) } else if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); - NotificationBundleOption bundleOption(infos.option.bundle, infos.option.uid); asynccallbackinfo->info.errorCode = - NotificationHelper::RemoveNotification(bundleOption, infos.key.id, infos.key.label); + NotificationHelper::RemoveNotification(infos.option, infos.key.id, infos.key.label); } }, [](napi_env env, napi_status status, void *data) { @@ -241,8 +293,7 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) if (asynccallbackinfo->params.bundleAndKeyInfo.has_value()) { auto &infos = asynccallbackinfo->params.bundleAndKeyInfo.value(); - NotificationBundleOption bundleOption(infos.option.bundle, infos.option.uid); - asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllNotifications(bundleOption); + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllNotifications(infos.option); } else { asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotifications(); } @@ -275,5 +326,72 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackRemoveGroupByBundle(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = (AsyncCallbackInfoRemoveGroupByBundle *)data; + + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + +napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info) +{ + ANS_LOGI("enter"); + + RemoveParamsGroupByBundle params {}; + if (ParseParameters(env, info, params) == nullptr) { + return Common::NapiGetUndefined(env); + } + + AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = + new (std::nothrow) AsyncCallbackInfoRemoveGroupByBundle {.env = env, .asyncWork = nullptr, .params = params}; + if (!asynccallbackinfo) { + return Common::JSParaError(env, params.callback); + } + napi_value promise = nullptr; + Common::PaddingCallbackPromiseInfo(env, params.callback, asynccallbackinfo->info, promise); + + napi_value resourceName = nullptr; + napi_create_string_latin1(env, "removeGroupByBundle", NAPI_AUTO_LENGTH, &resourceName); + // Asynchronous function call + napi_create_async_work(env, + nullptr, + resourceName, + [](napi_env env, void *data) { + ANS_LOGI("RemoveGroupByBundle napi_create_async_work start"); + AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = (AsyncCallbackInfoRemoveGroupByBundle *)data; + ANS_LOGI("option.bundle = %{public}s, option.uid = %{public}d, groupName = %{public}s", + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid(), + asynccallbackinfo->params.groupName.c_str()); + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveGroupByBundle( + asynccallbackinfo->params.option, asynccallbackinfo->params.groupName); + }, + AsyncCompleteCallbackRemoveGroupByBundle, + (void *)asynccallbackinfo, + &asynccallbackinfo->asyncWork); + + NAPI_CALL(env, napi_queue_async_work(env, asynccallbackinfo->asyncWork)); + + if (asynccallbackinfo->info.isCallback) { + return Common::NapiGetNull(env); + } else { + return promise; + } +} } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index c5ba3fe797ec355bd0db347207f8081a09224619..7eab91e8540828f2a756fe541d4eb343460ee813 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -22,10 +22,8 @@ const int ADD_SLOTS_MAX_PARA = 2; const int SET_SLOT_AS_BUNDLE_MAX_PARA = 3; const int GET_SLOT_MAX_PARA = 2; const int GET_SLOT_NUM_AS_BUNDLE_MAX_PARA = 2; -const int GET_SLOTS_MAX_PARA = 1; const int GET_SLOTS_AS_BUNDLE_MAX_PARA = 2; const int REMOVE_SLOT_MAX_PARA = 2; -const int REMOVE_ALL_SLOTS_MAX_PARA = 1; struct ParametersInfoAddSlot { NotificationSlot slot; @@ -56,7 +54,7 @@ struct AsyncCallbackInfoAddSlots { }; struct ParametersInfoSetSlotByBundle { - BundleOption option; + NotificationBundleOption option; std::vector> slots; napi_ref callback = nullptr; }; @@ -77,41 +75,41 @@ struct AsyncCallbackInfoGetSlot { napi_env env = nullptr; napi_async_work asyncWork = nullptr; enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - napi_value result = nullptr; CallbackPromiseInfo info; + sptr slot = nullptr; }; struct ParametersInfoGetSlotNumByBundle { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; }; struct AsyncCallbackInfoGetSlotNumByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_value result = nullptr; ParametersInfoGetSlotNumByBundle params; CallbackPromiseInfo info; + int num = 0; }; struct AsyncCallbackInfoGetSlots { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_value result = nullptr; CallbackPromiseInfo info; + std::vector> slots; }; struct ParametersInfoGetSlotsByBundle { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; }; struct AsyncCallbackInfoGetSlotsByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_value result = nullptr; ParametersInfoGetSlotsByBundle params; CallbackPromiseInfo info; + std::vector> slots; }; struct ParametersInfoRemoveSlot { @@ -143,28 +141,28 @@ napi_value ParseParametersByAddSlot(const napi_env &env, const napi_callback_inf napi_valuetype valuetype = napi_undefined; // argv[0]: NotificationSlot - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT( env, (valuetype == napi_object || valuetype == napi_number), "Wrong argument type. Object or number expected."); if (valuetype == napi_number) { paras.isAddSlotByType = true; int slotType = 0; - napi_get_value_int32(env, argv[0], &slotType); + napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.inType)) { return nullptr; } } else { paras.isAddSlotByType = false; - if (!Common::GetNotificationSlot(env, argv[0], paras.slot)) { + if (!Common::GetNotificationSlot(env, argv[PARAM0], paras.slot)) { return nullptr; } } // argv[1]:callback if (argc >= ADD_SLOT_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); } @@ -181,14 +179,14 @@ napi_value ParseParametersByAddSlots(const napi_env &env, const napi_callback_in napi_valuetype valuetype = napi_undefined; // argv[0]: Array bool isArray = false; - napi_is_array(env, argv[0], &isArray); + napi_is_array(env, argv[PARAM0], &isArray); NAPI_ASSERT(env, isArray, "Wrong argument type. Array expected."); uint32_t length = 0; - napi_get_array_length(env, argv[0], &length); + napi_get_array_length(env, argv[PARAM0], &length); NAPI_ASSERT(env, length > 0, "The array is empty."); for (size_t i = 0; i < length; i++) { napi_value nSlot = nullptr; - napi_get_element(env, argv[0], i, &nSlot); + napi_get_element(env, argv[PARAM0], i, &nSlot); NAPI_CALL(env, napi_typeof(env, nSlot, &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); NotificationSlot slot; @@ -200,9 +198,9 @@ napi_value ParseParametersByAddSlots(const napi_env &env, const napi_callback_in // argv[1]:callback if (argc >= ADD_SLOTS_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); } @@ -220,19 +218,19 @@ napi_value ParseParametersSetSlotByBundle( NAPI_ASSERT(env, argc >= SET_SLOT_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); // argv[0]: bundle - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; } // argv[1]: slot - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); NotificationSlot slot; - if (!Common::GetNotificationSlot(env, argv[1], slot)) { + if (!Common::GetNotificationSlot(env, argv[PARAM1], slot)) { return nullptr; } std::vector slots; @@ -249,9 +247,9 @@ napi_value ParseParametersSetSlotByBundle( // argv[2]:callback if (argc >= SET_SLOT_AS_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[SET_SLOT_AS_BUNDLE_MAX_PARA - 1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[SET_SLOT_AS_BUNDLE_MAX_PARA - 1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -268,19 +266,19 @@ napi_value ParseParametersByGetSlot(const napi_env &env, const napi_callback_inf napi_valuetype valuetype = napi_undefined; // argv[0]: SlotType - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); int slotType = 0; - napi_get_value_int32(env, argv[0], &slotType); + napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; } // argv[1]:callback if (argc >= GET_SLOT_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); } @@ -298,9 +296,9 @@ napi_value ParseParametersGetSlotNumByBundle( NAPI_ASSERT(env, argc >= GET_SLOT_NUM_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); // argv[0]: bundle - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; @@ -308,32 +306,14 @@ napi_value ParseParametersGetSlotNumByBundle( // argv[1]:callback if (argc >= GET_SLOT_NUM_AS_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); } -napi_value ParseParametersByGetSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); - size_t argc = GET_SLOTS_MAX_PARA; - napi_value argv[GET_SLOTS_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - // argv[0]:callback - napi_valuetype valuetype = napi_undefined; - if (argc >= GET_SLOTS_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); - } - return Common::NapiGetNull(env); -} - napi_value ParseParametersGetSlotsByBundle( const napi_env &env, const napi_callback_info &info, ParametersInfoGetSlotsByBundle ¶ms) { @@ -347,9 +327,9 @@ napi_value ParseParametersGetSlotsByBundle( NAPI_ASSERT(env, argc >= GET_SLOTS_AS_BUNDLE_MAX_PARA - 1, "Wrong number of arguments"); // argv[0]: bundle - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); - auto retValue = Common::GetBundleOption(env, argv[0], params.option); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + auto retValue = Common::GetBundleOption(env, argv[PARAM0], params.option); if (retValue == nullptr) { ANS_LOGE("GetBundleOption failed."); return nullptr; @@ -357,9 +337,9 @@ napi_value ParseParametersGetSlotsByBundle( // argv[1]:callback if (argc >= GET_SLOTS_AS_BUNDLE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -377,37 +357,19 @@ napi_value ParseParametersByRemoveSlot( napi_valuetype valuetype = napi_undefined; // argv[0]: SlotType - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); int slotType = 0; - napi_get_value_int32(env, argv[0], &slotType); + napi_get_value_int32(env, argv[PARAM0], &slotType); if (!Common::SlotTypeJSToC(SlotType(slotType), paras.outType)) { return nullptr; } // argv[1]:callback if (argc >= REMOVE_SLOT_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶s.callback); - } - return Common::NapiGetNull(env); -} - -napi_value ParseParametersByRemoveAllSlots(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); - size_t argc = REMOVE_ALL_SLOTS_MAX_PARA; - napi_value argv[REMOVE_ALL_SLOTS_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= REMOVE_ALL_SLOTS_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); } @@ -442,7 +404,7 @@ napi_value AddSlot(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("AddSlot napi_create_async_work start"); - AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; if (asynccallbackinfo->isAddSlotByType) { asynccallbackinfo->info.errorCode = NotificationHelper::AddSlotByType(asynccallbackinfo->inType); } else { @@ -451,7 +413,7 @@ napi_value AddSlot(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlot napi_create_async_work end"); - AsyncCallbackInfoAddSlot *asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoAddSlot *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -502,12 +464,12 @@ napi_value AddSlots(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("AddSlots napi_create_async_work start"); - AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; + auto asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; asynccallbackinfo->info.errorCode = NotificationHelper::AddNotificationSlots(asynccallbackinfo->slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("AddSlots napi_create_async_work end"); - AsyncCallbackInfoAddSlots *asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; + auto asynccallbackinfo = (AsyncCallbackInfoAddSlots *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -558,17 +520,14 @@ napi_value SetSlotByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("SetSlotByBundle napi_create_async_work start"); - AsyncCallbackInfoSetSlotByBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; + auto asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - asynccallbackinfo->info.errorCode = - NotificationHelper::UpdateNotificationSlots(bundleOption, asynccallbackinfo->params.slots); + asynccallbackinfo->info.errorCode = NotificationHelper::UpdateNotificationSlots( + asynccallbackinfo->params.option, asynccallbackinfo->params.slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("SetSlotByBundle napi_create_async_work end"); - AsyncCallbackInfoSetSlotByBundle *asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; + auto asynccallbackinfo = (AsyncCallbackInfoSetSlotByBundle *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -594,6 +553,42 @@ napi_value SetSlotByBundle(napi_env env, napi_callback_info info) } } + +void AsyncCompleteCallbackGetSlot(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("GetSlot napi_create_async_work end"); + + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + + auto asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + napi_value result = Common::NapiGetNull(env); + if (asynccallbackinfo->info.errorCode == ERR_OK) { + if (asynccallbackinfo->slot == nullptr) { + asynccallbackinfo->info.errorCode = ERROR; + } else { + napi_create_object(env, &result); + if (!Common::SetNotificationSlot(env, *asynccallbackinfo->slot, result)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value GetSlot(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -619,41 +614,12 @@ napi_value GetSlot(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetSlot napi_create_async_work start"); - AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; - sptr slot = nullptr; asynccallbackinfo->info.errorCode = - NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, slot); - asynccallbackinfo->result = Common::NapiGetNull(env); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - return; - } - if (slot == nullptr) { - asynccallbackinfo->info.errorCode = ERROR; - return; - } - napi_create_object(env, &asynccallbackinfo->result); - if (!Common::SetNotificationSlot(env, *slot, asynccallbackinfo->result)) { - asynccallbackinfo->info.errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlot napi_create_async_work end"); - AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, asynccallbackinfo->slot); }, + AsyncCompleteCallbackGetSlot, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -691,20 +657,17 @@ napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetSlotNumByBundle napi_create_async_work start"); - AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; - - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - int num = 0; - asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, num); - napi_create_int32(env, num, &asynccallbackinfo->result); + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; + + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotNumAsBundle( + asynccallbackinfo->params.option, asynccallbackinfo->num); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlotNumByBundle napi_create_async_work end"); - AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; + napi_value result = nullptr; + napi_create_int32(env, asynccallbackinfo->num, &result); + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); @@ -728,12 +691,60 @@ napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackGetSlots(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + napi_value result = nullptr; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_value arr = nullptr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : asynccallbackinfo->slots) { + if (!vec) { + ANS_LOGW("Invalid NotificationSlot object ptr"); + continue; + } + napi_value nSlot = nullptr; + napi_create_object(env, &nSlot); + if (!Common::SetNotificationSlot(env, *vec, nSlot)) { + continue; + } + napi_set_element(env, arr, count, nSlot); + count++; + } + ANS_LOGI("getSlots count = %{public}zu", count); + result = arr; + if ((count == 0) && (asynccallbackinfo->slots.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value GetSlots(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByGetSlots(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -753,54 +764,10 @@ napi_value GetSlots(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetSlots napi_create_async_work start"); - AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; - - std::vector> slots; - asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(slots); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = Common::NapiGetNull(env); - return; - } - - napi_value arr = nullptr; - napi_create_array(env, &arr); - size_t count = 0; - for (auto vec : slots) { - if (!vec) { - ANS_LOGW("Invalid NotificationSlot object ptr"); - continue; - } - napi_value nSlot = nullptr; - napi_create_object(env, &nSlot); - if (!Common::SetNotificationSlot(env, *vec, nSlot)) { - continue; - } - napi_set_element(env, arr, count, nSlot); - count++; - } - ANS_LOGI("getSlots count = %{public}zu", count); - asynccallbackinfo->result = arr; - if ((count == 0) && (slots.size() > 0)) { - asynccallbackinfo->info.errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlots napi_create_async_work end"); - AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(asynccallbackinfo->slots); }, + AsyncCompleteCallbackGetSlots, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -813,6 +780,54 @@ napi_value GetSlots(napi_env env, napi_callback_info info) } } +void AsyncCompleteCallbackGetSlotsByBundle(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("enter"); + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + napi_value result = nullptr; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; + if (asynccallbackinfo->info.errorCode != ERR_OK) { + result = Common::NapiGetNull(env); + } else { + napi_value arr = nullptr; + napi_create_array(env, &arr); + size_t count = 0; + for (auto vec : asynccallbackinfo->slots) { + if (!vec) { + ANS_LOGW("Invalid NotificationSlot object ptr"); + continue; + } + napi_value nSlot = nullptr; + napi_create_object(env, &nSlot); + if (!Common::SetNotificationSlot(env, *vec, nSlot)) { + continue; + } + napi_set_element(env, arr, count, nSlot); + count++; + } + ANS_LOGI("getSlots count = %{public}zu", count); + result = arr; + if ((count == 0) && (asynccallbackinfo->slots.size() > 0)) { + asynccallbackinfo->info.errorCode = ERROR; + result = Common::NapiGetNull(env); + } + } + Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); + + if (asynccallbackinfo->info.callback != nullptr) { + napi_delete_reference(env, asynccallbackinfo->info.callback); + } + + napi_delete_async_work(env, asynccallbackinfo->asyncWork); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } +} + napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -838,58 +853,12 @@ napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("GetSlotsByBundle napi_create_async_work start"); - AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - - std::vector> slots; - asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotsForBundle(bundleOption, slots); - if (asynccallbackinfo->info.errorCode != ERR_OK) { - asynccallbackinfo->result = Common::NapiGetNull(env); - return; - } - - napi_value arr = nullptr; - napi_create_array(env, &arr); - size_t count = 0; - for (auto vec : slots) { - if (!vec) { - ANS_LOGW("Invalid NotificationSlot object ptr"); - continue; - } - napi_value nSlot = nullptr; - napi_create_object(env, &nSlot); - if (!Common::SetNotificationSlot(env, *vec, nSlot)) { - continue; - } - napi_set_element(env, arr, count, nSlot); - count++; - } - ANS_LOGI("getSlots count = %{public}zu", count); - asynccallbackinfo->result = arr; - if ((count == 0) && (slots.size() > 0)) { - asynccallbackinfo->info.errorCode = ERROR; - asynccallbackinfo->result = Common::NapiGetNull(env); - } - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlotsByBundle napi_create_async_work end"); - AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; - - Common::ReturnCallbackPromise(env, asynccallbackinfo->info, asynccallbackinfo->result); - - if (asynccallbackinfo->info.callback != nullptr) { - napi_delete_reference(env, asynccallbackinfo->info.callback); - } - - napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotsForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->slots); }, + AsyncCompleteCallbackGetSlotsByBundle, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -927,12 +896,12 @@ napi_value RemoveSlot(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("removeSlot napi_create_async_work start"); - AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; asynccallbackinfo->info.errorCode = NotificationHelper::RemoveNotificationSlot(asynccallbackinfo->outType); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("removeSlot napi_create_async_work end"); - AsyncCallbackInfoRemoveSlot *asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoRemoveSlot *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -963,7 +932,7 @@ napi_value RemoveAllSlots(napi_env env, napi_callback_info info) ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParametersByRemoveAllSlots(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -983,12 +952,12 @@ napi_value RemoveAllSlots(napi_env env, napi_callback_info info) resourceName, [](napi_env env, void *data) { ANS_LOGI("RemoveAllSlots napi_create_async_work start"); - AsyncCallbackInfoRemoveAllSlots *asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; + auto asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; asynccallbackinfo->info.errorCode = NotificationHelper::RemoveAllSlots(); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("RemoveAllSlots napi_create_async_work end"); - AsyncCallbackInfoRemoveAllSlots *asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; + auto asynccallbackinfo = (AsyncCallbackInfoRemoveAllSlots *)data; Common::ReturnCallbackPromise(env, asynccallbackinfo->info, Common::NapiGetNull(env)); @@ -1013,6 +982,5 @@ napi_value RemoveAllSlots(napi_env env, napi_callback_info info) return promise; } } - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 4edb90d995aef25473cef75ca58a3dbe77b345e4..a0a5b2cd04364da4ef552e4ec7af97b3fcd1badf 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -13,10 +13,11 @@ * limitations under the License. */ -#include -#include #include "subscribe.h" +#include +#include + namespace OHOS { namespace NotificationNapi { const int SUBSRIBE_MAX_PARA = 3; @@ -28,12 +29,14 @@ const std::string CONNECTED = "onConnect"; const std::string DIS_CONNECTED = "onDisconnect"; const std::string DIE = "onDestroy"; const std::string DISTURB_MODE_CHANGE = "onDisturbModeChange"; +const std::string DISTURB_DATE_CHANGE = "onDoNotDisturbDateChange"; struct NotificationReceiveDataWorker { napi_env env = nullptr; napi_ref ref = nullptr; std::shared_ptr request; std::shared_ptr sortingMap; + NotificationDoNotDisturbDate date; int deleteReason = 0; int result = 0; int disturbMode = 0; @@ -47,12 +50,12 @@ napi_value SetSubscribeCallbackData(const napi_env &env, ANS_LOGI("enter"); if (request == nullptr) { ANS_LOGE("request is null"); - return Common::NapiGetboolean(env, false); + return Common::NapiGetBoolean(env, false); } if (sortingMap == nullptr) { ANS_LOGE("sortingMap is null"); - return Common::NapiGetboolean(env, false); + return Common::NapiGetBoolean(env, false); } // request: NotificationRequest @@ -60,7 +63,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, napi_create_object(env, &requestResult); if (!Common::SetNotification(env, request.get(), requestResult)) { ANS_LOGE("SetNotification call failed"); - return Common::NapiGetboolean(env, false); + return Common::NapiGetBoolean(env, false); } napi_set_named_property(env, result, "request", requestResult); @@ -69,7 +72,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, napi_create_object(env, &sortingMapResult); if (!Common::SetNotificationSortingMap(env, sortingMap, sortingMapResult)) { ANS_LOGE("SetNotificationSortingMap call failed"); - return Common::NapiGetboolean(env, false); + return Common::NapiGetBoolean(env, false); } napi_set_named_property(env, result, "sortingMap", sortingMapResult); @@ -78,7 +81,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, napi_value value = nullptr; int outReason = 0; if (!Common::ReasonCToJS(deleteReason, outReason)) { - return Common::NapiGetboolean(env, false); + return Common::NapiGetBoolean(env, false); } napi_create_int32(env, outReason, &value); napi_set_named_property(env, result, "reason", value); @@ -107,7 +110,7 @@ napi_value SetSubscribeCallbackData(const napi_env &env, } napi_set_named_property(env, result, "vibrationValues", arr); - return Common::NapiGetboolean(env, true); + return Common::NapiGetBoolean(env, true); } SubscriberInstance::SubscriberInstance() @@ -141,6 +144,40 @@ SubscriberInstance::~SubscriberInstance() void SubscriberInstance::OnCanceled(const std::shared_ptr &request) {} +void UvQueueWorkOnCanceled(uv_work_t *work, int status) +{ + ANS_LOGI("OnCanceled uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + if (!SetSubscribeCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + dataWorkerData->deleteReason, + result)) { + ANS_LOGE("Failed to convert data to JS"); + } else { + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); + } + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void SubscriberInstance::OnCanceled(const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) { @@ -186,52 +223,59 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdata = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnCanceled uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result = nullptr; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!SetSubscribeCallbackData(dataWorkerData->env, - dataWorkerData->request, - dataWorkerData->sortingMap, - dataWorkerData->deleteReason, - result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnCanceled); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::OnConsumed(const std::shared_ptr &request) {} +void UvQueueWorkOnConsumed(uv_work_t *work, int status) +{ + ANS_LOGI("OnConsumed uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + if (!SetSubscribeCallbackData(dataWorkerData->env, + dataWorkerData->request, + dataWorkerData->sortingMap, + NO_DELETE_REASON, + result)) { + ANS_LOGE("Failed to convert data to JS"); + } else { + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); + } + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void SubscriberInstance::OnConsumed(const std::shared_ptr &request, const std::shared_ptr &sortingMap) { @@ -251,8 +295,8 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrGetNotificationRequest().GetNotificationId()); - ANS_LOGI("OnConsumed sortingMap size = %{public}zu", sortingMap->GetKey().size()); + ANS_LOGI("OnConsumed Notification key = %{public}s, sortingMap size = %{public}zu", + request->GetKey().c_str(), sortingMap->GetKey().size()); uv_loop_s *loop = nullptr; napi_get_uv_event_loop(consumeCallbackInfo_.env, &loop); @@ -275,47 +319,50 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrdata = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnConsumed uv_work_t start"); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnConsumed); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } +} - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } +void UvQueueWorkOnUpdate(uv_work_t *work, int status) +{ + ANS_LOGI("OnUpdate uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result = nullptr; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!SetSubscribeCallbackData(dataWorkerData->env, - dataWorkerData->request, - dataWorkerData->sortingMap, - NO_DELETE_REASON, - result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + if (!Common::SetNotificationSortingMap(dataWorkerData->env, dataWorkerData->sortingMap, result)) { + ANS_LOGE("Failed to convert data to JS"); + } else { + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); + } - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; } void SubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) @@ -353,46 +400,48 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { ANS_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; return; } work->data = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUpdate uv_work_t start"); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnUpdate); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } +} - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } +void UvQueueWorkOnConnected(uv_work_t *work, int status) +{ + ANS_LOGI("OnConnected uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result = nullptr; - napi_create_object(dataWorkerData->env, &result); - int error = 0; - if (!Common::SetNotificationSortingMap(dataWorkerData->env, dataWorkerData->sortingMap, result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; - } else { - error = NO_ERROR; - } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; } -void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) +void SubscriberInstance::OnConnected() { ANS_LOGI("enter"); @@ -400,7 +449,6 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult ANS_LOGI("subscribe callback unset"); return; } - ANS_LOGI("OnSubscribeResult result = %{public}d", result); uv_loop_s *loop = nullptr; napi_get_uv_event_loop(subscribeCallbackInfo_.env, &loop); @@ -415,48 +463,56 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult return; } - dataWorker->result = (int)result; dataWorker->env = subscribeCallbackInfo_.env; dataWorker->ref = subscribeCallbackInfo_.ref; uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { ANS_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; return; } work->data = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnSubscribeResult uv_work_t start"); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnConnected); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } +} - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } +void UvQueueWorkOnDisconnected(uv_work_t *work, int status) +{ + ANS_LOGI("OnDisconnected uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // result: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; } -void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +void SubscriberInstance::OnDisconnected() { ANS_LOGI("enter"); @@ -464,7 +520,6 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu ANS_LOGI("unsubscribe callback unset"); return; } - ANS_LOGI("OnUnsubscribeResult result = %{public}d", result); uv_loop_s *loop = nullptr; napi_get_uv_event_loop(unsubscribeCallbackInfo_.env, &loop); @@ -479,7 +534,6 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu return; } - dataWorker->result = (int)result; dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; dataWorker->subscriber = this; @@ -487,40 +541,46 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { ANS_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; return; } work->data = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUnsubscribeResult uv_work_t start"); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnDisconnected); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } +} - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } +void UvQueueWorkOnDied(uv_work_t *work, int status) +{ + ANS_LOGI("OnDied uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // result: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } - DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); + Common::SetCallback( + dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; } void SubscriberInstance::OnDied() @@ -551,50 +611,70 @@ void SubscriberInstance::OnDied() uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { ANS_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; return; } work->data = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDied uv_work_t start"); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnDied); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } +} - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } +void UvQueueWorkOnDoNotDisturbDateChange(uv_work_t *work, int status) +{ + ANS_LOGI("OnDoNotDisturbDateChange uv_work_t start"); - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + + napi_value result = nullptr; + napi_create_object(dataWorkerData->env, &result); + + if (!Common::SetDoNotDisturbDate(dataWorkerData->env, dataWorkerData->date, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + } - Common::SetCallback( - dataWorkerData->env, dataWorkerData->ref, NO_ERROR, Common::NapiGetNull(dataWorkerData->env)); + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; } -void SubscriberInstance::OnDisturbModeChanged(int disturbMode) +void SubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptr &date) { ANS_LOGI("enter"); - if (disturbModeCallbackInfo_.ref == nullptr) { - ANS_LOGI("disturbModeChange callback unset"); + if (disturbDateCallbackInfo_.ref == nullptr) { + ANS_LOGI("disturbDateCallbackInfo_ callback unset"); + return; + } + + if (date == nullptr) { + ANS_LOGE("date is null"); return; } - ANS_LOGI("OnDisturbModeChanged disturbMode = %{public}d", disturbMode); uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); + napi_get_uv_event_loop(disturbDateCallbackInfo_.env, &loop); if (loop == nullptr) { ANS_LOGE("loop instance is nullptr"); return; @@ -606,45 +686,27 @@ void SubscriberInstance::OnDisturbModeChanged(int disturbMode) return; } - dataWorker->disturbMode = disturbMode; - dataWorker->env = disturbModeCallbackInfo_.env; - dataWorker->ref = disturbModeCallbackInfo_.ref; + dataWorker->date = *date; + dataWorker->env = disturbDateCallbackInfo_.env; + dataWorker->ref = disturbDateCallbackInfo_.ref; uv_work_t *work = new (std::nothrow) uv_work_t; if (work == nullptr) { ANS_LOGE("new work failed"); + delete dataWorker; + dataWorker = nullptr; return; } work->data = (void *)dataWorker; - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDisturbModeChanged uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // disturbMode: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->disturbMode, &result); - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnDoNotDisturbDateChange); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) @@ -689,6 +751,12 @@ void SubscriberInstance::SetDisturbModeCallbackInfo(const napi_env &env, const n disturbModeCallbackInfo_.ref = ref; } +void SubscriberInstance::SetDisturbDateCallbackInfo(const napi_env &env, const napi_ref &ref) +{ + disturbDateCallbackInfo_.env = env; + disturbDateCallbackInfo_.ref = ref; +} + void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string &type, const napi_ref &ref) { if (type == CONSUME) { @@ -705,6 +773,8 @@ void SubscriberInstance::SetCallbackInfo(const napi_env &env, const std::string SetDieCallbackInfo(env, ref); } else if (type == DISTURB_MODE_CHANGE) { SetDisturbModeCallbackInfo(env, ref); + } else if (type == DISTURB_DATE_CHANGE) { + SetDisturbDateCallbackInfo(env, ref); } else { ANS_LOGW("type is error"); } @@ -821,6 +891,17 @@ napi_value GetNotificationSubscriber( subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_MODE_CHANGE, result); } + // onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void + NAPI_CALL(env, napi_has_named_property(env, value, "onDoNotDisturbDateChange", &hasProperty)); + if (hasProperty) { + napi_value nOnDisturbDateChanged = nullptr; + napi_get_named_property(env, value, "onDoNotDisturbDateChange", &nOnDisturbDateChanged); + NAPI_CALL(env, napi_typeof(env, nOnDisturbDateChanged, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, nOnDisturbDateChanged, 1, &result); + subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_DATE_CHANGE, result); + } + return Common::NapiGetNull(env); } @@ -877,17 +958,25 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_valuetype valuetype = napi_undefined; // argv[0]:subscriber - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. NotificationSubscriber object expected."); SubscriberInstancesInfo subscriberInstancesInfo; - if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { - if (GetNotificationSubscriber(env, argv[0], subscriberInstancesInfo) == nullptr) { + if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { + if (GetNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo) == nullptr) { ANS_LOGE("NotificationSubscriber parse failed"); + if (subscriberInstancesInfo.subscriber) { + delete subscriberInstancesInfo.subscriber; + subscriberInstancesInfo.subscriber = nullptr; + } return nullptr; } if (!AddSubscriberInstancesInfo(env, subscriberInstancesInfo)) { ANS_LOGE("AddSubscriberInstancesInfo add failed"); + if (subscriberInstancesInfo.subscriber) { + delete subscriberInstancesInfo.subscriber; + subscriberInstancesInfo.subscriber = nullptr; + } return nullptr; } } @@ -895,14 +984,14 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]:callback or NotificationSubscribeInfo if (argc >= SUBSRIBE_MAX_PARA - 1) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, (valuetype == napi_function) || (valuetype == napi_object), "Wrong argument type for arg1. Function or NotificationSubscribeInfo object expected."); if (valuetype == napi_function) { - napi_create_reference(env, argv[1], 1, &callback); + napi_create_reference(env, argv[PARAM1], 1, &callback); } else { - if (Common::GetNotificationSubscriberInfo(env, argv[1], subscriberInfo) == nullptr) { + if (Common::GetNotificationSubscriberInfo(env, argv[PARAM1], subscriberInfo) == nullptr) { ANS_LOGE("NotificationSubscribeInfo parse failed"); return nullptr; } @@ -911,9 +1000,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[2]:callback if (argc >= SUBSRIBE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[SUBSRIBE_MAX_PARA - 1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM2], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[SUBSRIBE_MAX_PARA - 1], 1, &callback); + napi_create_reference(env, argv[PARAM2], 1, &callback); } return Common::NapiGetNull(env); @@ -927,6 +1016,10 @@ napi_value Subscribe(napi_env env, napi_callback_info info) SubscriberInstance *objectInfo = nullptr; NotificationSubscribeInfo subscriberInfo; if (ParseParameters(env, info, subscriberInfo, objectInfo, callback) == nullptr) { + if (objectInfo) { + delete objectInfo; + objectInfo = nullptr; + } return Common::NapiGetUndefined(env); } ANS_LOGI("Subscribe objectInfo = %{public}p", objectInfo); @@ -935,6 +1028,10 @@ napi_value Subscribe(napi_env env, napi_callback_info info) .env = env, .asyncWork = nullptr, .objectInfo = objectInfo, .subscriberInfo = subscriberInfo }; if (!asynccallbackinfo) { + if (objectInfo) { + delete objectInfo; + objectInfo = nullptr; + } return Common::JSParaError(env, callback); } napi_value promise = nullptr; @@ -953,6 +1050,7 @@ napi_value Subscribe(napi_env env, napi_callback_info info) ANS_LOGI("Subscribe with NotificationSubscribeInfo"); OHOS::Notification::NotificationSubscribeInfo subscribeInfo; subscribeInfo.AddAppNames(asynccallbackinfo->subscriberInfo.bundleNames); + subscribeInfo.AddAppUserId(asynccallbackinfo->subscriberInfo.userId); asynccallbackinfo->info.errorCode = NotificationHelper::SubscribeNotification(*(asynccallbackinfo->objectInfo), subscribeInfo); } else { @@ -987,6 +1085,5 @@ napi_value Subscribe(napi_env env, napi_callback_info info) return promise; } } - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp index f50a80441ec54dab0709180b47b0998aee78a388..7ffc15278f2bcb79bf9ffbc11535dac7cf9951d9 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -16,6 +16,8 @@ #include "unsubscribe.h" #include "subscribe.h" +#include "ans_inner_errors.h" + namespace OHOS { namespace NotificationNapi { const int UNSUBSCRIBE_MAX_PARA = 2; @@ -43,21 +45,22 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_valuetype valuetype = napi_undefined; // argv[0]:subscriber - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. Subscribe object expected."); SubscriberInstancesInfo subscriberInstancesInfo; - if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { - return nullptr; + if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { + ANS_LOGW("Subscriber not found"); } + paras.objectInfo = subscriberInstancesInfo.subscriber; ANS_LOGI("ObjectInfo = %{public}p start", paras.objectInfo); // argv[1]:callback if (argc >= UNSUBSCRIBE_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[1], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); @@ -81,7 +84,7 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) Common::PaddingCallbackPromiseInfo(env, paras.callback, asynccallbackinfo->info, promise); napi_value resourceName = nullptr; - napi_create_string_latin1(env, "Unsubscribe", NAPI_AUTO_LENGTH, &resourceName); + napi_create_string_latin1(env, "unsubscribe", NAPI_AUTO_LENGTH, &resourceName); // Asynchronous function call napi_create_async_work(env, @@ -91,6 +94,12 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) ANS_LOGI("Unsubscribe napi_create_async_work start"); AsyncCallbackInfoUnsubscribe *asynccallbackinfo = (AsyncCallbackInfoUnsubscribe *)data; + if (asynccallbackinfo->objectInfo == nullptr) { + ANS_LOGE("invalid object info"); + asynccallbackinfo->info.errorCode = ERR_ANS_INVALID_PARAM; + return; + } + asynccallbackinfo->info.errorCode = NotificationHelper::UnSubscribeNotification(*(asynccallbackinfo->objectInfo)); }, @@ -121,6 +130,5 @@ napi_value Unsubscribe(napi_env env, napi_callback_info info) return promise; } } - } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/wantagent/BUILD.gn b/interfaces/kits/napi/wantagent/BUILD.gn index 8e9f83c18b137d5131cf8cbedeca5e3007a70d78..666c747cafc29d82aa40cd1d8e6b349902f49414 100644 --- a/interfaces/kits/napi/wantagent/BUILD.gn +++ b/interfaces/kits/napi/wantagent/BUILD.gn @@ -16,16 +16,12 @@ import("//build/ohos.gni") ohos_shared_library("wantagent") { include_dirs = [ - "//foundation/ace/napi/interfaces/kits", "//third_party/node/src", "//foundation/aafwk/standard/services/common/include", "//utils/system/safwk/native/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include", - "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/context", "//third_party/libuv/include", "//foundation/aafwk/standard/frameworks/kits/ability/native/include", - "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", - "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/frameworks/kits/appkit/native/ability_runtime", "//foundation/aafwk/standard/services/abilitymgr/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", "//foundation/aafwk/standard/services/common/include", @@ -39,23 +35,24 @@ ohos_shared_library("wantagent") { deps = [ "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", - "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/frameworks/kits/appkit:app_context", + "//foundation/aafwk/standard/frameworks/kits/appkit:appkit_native", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", - "//foundation/ace/napi:ace_napi", - "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", "//utils/native/base:utils", ] external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "napi:ace_napi", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", ] relative_install_dir = "module" diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index bce26d68216dcb7befb72aa310ff2ebf1abbedab..c530972e4c90d2e07558ab9120c5304ba5a359bf 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -15,8 +15,8 @@ #include "napi_want_agent.h" -#include -#include +#include +#include #include #include @@ -25,6 +25,13 @@ #include "want_agent_helper.h" namespace OHOS { +#define NAPI_ASSERT_RETURN_NULL(env, assertion, message) \ +do { \ + if (!(assertion)) { \ + HILOG_INFO(message); \ + return nullptr; \ + } \ +} while (0) constexpr int32_t BUSINESS_ERROR_CODE_OK = 0; TriggerCompleteCallBack::TriggerCompleteCallBack() @@ -50,6 +57,7 @@ auto OnSendFinishedUvAfterWorkCallback = [](uv_work_t *work, int status) { TriggerReceiveDataWorker *dataWorkerData = static_cast(work->data); if (dataWorkerData == nullptr) { HILOG_INFO("TriggerReceiveDataWorker instance(uv_work_t) is nullptr"); + delete work; return; } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; @@ -189,7 +197,7 @@ napi_value WantAgentFlagsInit(napi_env env, napi_value exports) SetNamedPropertyByInteger(env, obj, NUMBER_OF_PARAMETERS_NINE, "REPLACE_BUNDLE"); napi_property_descriptor exportFuncs[] = { - DECLARE_NAPI_PROPERTY("Flags", obj), + DECLARE_NAPI_PROPERTY("WantAgentFlags", obj), }; napi_define_properties(env, exports, sizeof(exportFuncs) / sizeof(*exportFuncs), exportFuncs); @@ -227,6 +235,10 @@ auto NAPI_GetBundleNameExecuteCallBack = [](napi_env env, void *data) { auto NAPI_GetBundleNameCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetBundleName compeleted(CallBack Mode)..."); AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback = nullptr; napi_value undefined = nullptr; @@ -243,16 +255,22 @@ auto NAPI_GetBundleNameCompleteCallBack = [](napi_env env, napi_status status, v } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; auto NAPI_GetBundleNamePromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetBundleName compeleted(Promise Mode)..."); AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result = nullptr; napi_create_string_utf8(env, asyncCallbackInfo->bundleName.c_str(), NAPI_AUTO_LENGTH, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_GetBundleNameWrap( @@ -306,7 +324,7 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) napi_valuetype wantAgentType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentType); - NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); @@ -319,10 +337,10 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetBundleNameCallbackInfo{ + AsyncGetBundleNameCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetBundleNameCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -346,12 +364,20 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) auto NAPI_GetUidWrapExecuteCallBack = [](napi_env env, void *data) { HILOG_INFO("GetUid called(CallBack Mode)..."); AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } asyncCallbackInfo->uid = WantAgentHelper::GetUid(asyncCallbackInfo->wantAgent); }; auto NAPI_GetUidWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetUid compeleted(CallBack Mode)..."); AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {0}; napi_value callback = nullptr; napi_value undefined = nullptr; @@ -368,16 +394,22 @@ auto NAPI_GetUidWrapCompleteCallBack = [](napi_env env, napi_status status, void } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; auto NAPI_GetUidWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetUid compeleted(Promise Mode)..."); AsyncGetUidCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result = nullptr; napi_create_int32(env, asyncCallbackInfo->uid, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_GetUidWrap( @@ -431,7 +463,7 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) napi_valuetype wantAgentType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentType); - NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); @@ -443,10 +475,10 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncGetUidCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetUidCallbackInfo{ + AsyncGetUidCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetUidCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -470,12 +502,20 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) auto NAPI_GetWantWrapExecuteCallBack = [](napi_env env, void *data) { HILOG_INFO("GetWant called(CallBack Mode)..."); AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } asyncCallbackInfo->want = WantAgentHelper::GetWant(asyncCallbackInfo->wantAgent); }; auto NAPI_GetWantWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWant compeleted(CallBack Mode)..."); AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr || asyncCallbackInfo->want == nullptr) { + HILOG_ERROR("asyncCallbackInfo or want is nullptr."); + return; + } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {}; napi_value callback = nullptr; napi_value undefined = nullptr; @@ -491,15 +531,21 @@ auto NAPI_GetWantWrapCompleteCallBack = [](napi_env env, napi_status status, voi } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; auto NAPI_GetWantWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("GetWant compeleted(Promise Mode)..."); AsyncGetWantCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr || asyncCallbackInfo->want == nullptr) { + HILOG_ERROR("asyncCallbackInfo or want is nullptr."); + return; + } napi_value result = WrapWant(env, *(asyncCallbackInfo->want)); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_GetWantWrap( @@ -553,7 +599,7 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) napi_valuetype wantAgentType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentType); - NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); @@ -565,10 +611,10 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncGetWantCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantCallbackInfo{ + AsyncGetWantCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -614,6 +660,10 @@ auto NAPI_CancelWrapExecuteCallBack = [](napi_env env, void *data) { auto NAPI_CancelWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("Cancel compeleted(CallBack Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {nullptr}; napi_value callback = nullptr; napi_value undefined = nullptr; @@ -630,16 +680,22 @@ auto NAPI_CancelWrapCompleteCallBack = [](napi_env env, napi_status status, void } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; auto NAPI_CancelWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("Cancel compeleted(Promise Mode)..."); AsyncCancelCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result = nullptr; napi_get_null(env, &result); napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_CancelWrap( @@ -693,7 +749,7 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) napi_valuetype wantAgentType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentType); - NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); @@ -705,10 +761,10 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncCancelCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCancelCallbackInfo{ + AsyncCancelCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncCancelCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -734,8 +790,7 @@ auto NAPI_TriggerWrapExecuteCallBack = [](napi_env env, void *data) { AsyncTriggerCallbackInfo *asyncCallbackInfo = static_cast(data); asyncCallbackInfo->triggerObj->SetCallbackInfo(env, asyncCallbackInfo->callback[0]); asyncCallbackInfo->triggerObj->SetWantAgentInstance(asyncCallbackInfo->wantAgent); - WantAgentHelper::TriggerWantAgent(asyncCallbackInfo->context, - asyncCallbackInfo->wantAgent, + WantAgentHelper::TriggerWantAgent(asyncCallbackInfo->wantAgent, asyncCallbackInfo->triggerObj, asyncCallbackInfo->triggerInfo); }; @@ -743,8 +798,13 @@ auto NAPI_TriggerWrapExecuteCallBack = [](napi_env env, void *data) { auto NAPI_TriggerWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("Trigger compeleted ..."); AsyncTriggerCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_TriggerWrap(napi_env env, napi_callback_info info, AsyncTriggerCallbackInfo &asyncCallbackInfo) @@ -778,7 +838,7 @@ napi_value NAPI_GetTriggerInfo(napi_value argv[NUMBER_OF_PARAMETERS_THREE], uint napi_value jsTriggerInfo = argv[1]; napi_valuetype valueType = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, jsTriggerInfo, &valueType)); - NAPI_ASSERT(env, valueType == napi_object, "param type mismatch!"); + NAPI_ASSERT_RETURN_NULL(env, valueType == napi_object, "param type mismatch!"); // Get triggerInfo code int32_t code = -1; @@ -823,7 +883,7 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) napi_valuetype wantAgentType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentType); - NAPI_ASSERT(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgent = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgent)); @@ -831,20 +891,11 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) return NapiGetNull(env); } - // Get context - napi_value global = nullptr; - NAPI_CALL(env, napi_get_global(env, &global)); - napi_value abilityObj = nullptr; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - std::shared_ptr context = ability->GetContext(); - bool callBackMode = false; if (argc >= NUMBER_OF_PARAMETERS_THREE) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } @@ -854,7 +905,7 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) return NapiGetNull(env); } - AsyncTriggerCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncTriggerCallbackInfo{ + AsyncTriggerCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncTriggerCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -863,7 +914,6 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) return NapiGetNull(env); } asyncCallbackInfo->wantAgent = std::make_shared(*pWantAgent); - asyncCallbackInfo->context = context; asyncCallbackInfo->triggerInfo = triggerInfo; asyncCallbackInfo->triggerObj = nullptr; if (callBackMode) { @@ -890,6 +940,10 @@ auto NAPI_EqualWrapExecuteCallBack = [](napi_env env, void *data) { auto NAPI_EqualWrapCompleteCallBack = [](napi_env env, napi_status status, void *data) { HILOG_INFO("Equal compeleted(CallBack Mode)..."); AsyncEqualCallbackInfo *asyncCallbackInfo = static_cast(data); + if (asyncCallbackInfo == nullptr) { + HILOG_ERROR("asyncCallbackInfo is nullptr."); + return; + } napi_value result[NUMBER_OF_PARAMETERS_TWO] = {}; napi_value callback = nullptr; napi_value undefined = nullptr; @@ -906,6 +960,7 @@ auto NAPI_EqualWrapCompleteCallBack = [](napi_env env, napi_status status, void } napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; auto NAPI_EqualWrapPromiseCompleteCallBack = [](napi_env env, napi_status status, void *data) { @@ -916,6 +971,7 @@ auto NAPI_EqualWrapPromiseCompleteCallBack = [](napi_env env, napi_status status napi_resolve_deferred(asyncCallbackInfo->env, asyncCallbackInfo->deferred, result); napi_delete_async_work(env, asyncCallbackInfo->asyncWork); delete asyncCallbackInfo; + asyncCallbackInfo = nullptr; }; napi_value NAPI_EqualWrap( @@ -969,7 +1025,7 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) napi_valuetype wantAgentFirstType = napi_valuetype::napi_null; napi_typeof(env, argv[0], &wantAgentFirstType); - NAPI_ASSERT(env, wantAgentFirstType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentFirstType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgentFirst = nullptr; napi_unwrap(env, argv[0], (void **)&(pWantAgentFirst)); @@ -979,7 +1035,7 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) napi_valuetype wantAgentSecondType = napi_valuetype::napi_null; napi_typeof(env, argv[1], &wantAgentSecondType); - NAPI_ASSERT(env, wantAgentSecondType == napi_object, "Wrong argument type. Object expected."); + NAPI_ASSERT_RETURN_NULL(env, wantAgentSecondType == napi_object, "Wrong argument type. Object expected."); Notification::WantAgent::WantAgent *pWantAgentSecond = nullptr; napi_unwrap(env, argv[1], (void **)&(pWantAgentSecond)); @@ -991,10 +1047,10 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) if (argc >= NUMBER_OF_PARAMETERS_THREE) { napi_valuetype valuetype = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, argv[NUMBER_OF_PARAMETERS_TWO], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncEqualCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncEqualCallbackInfo{ + AsyncEqualCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncEqualCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -1148,7 +1204,7 @@ napi_value NAPI_GetWantAgentWants(napi_env env, napi_value jsWantAgentInfo, cons { napi_valuetype jsWantAgentInfoType = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, jsWantAgentInfo, &jsWantAgentInfoType)); - NAPI_ASSERT(env, jsWantAgentInfoType == napi_object, "param type mismatch!"); + NAPI_ASSERT_RETURN_NULL(env, jsWantAgentInfoType == napi_object, "param type mismatch!"); napi_value jsWants = GetPropertyValueByPropertyName(env, jsWantAgentInfo, "wants", napi_object); bool isArray = false; @@ -1187,7 +1243,7 @@ napi_value NAPI_GetWantAgentWants(napi_env env, napi_value jsWantAgentInfo, cons napi_get_element(env, JsWantAgentFlags, i, &napiWantAgentFlags); napi_valuetype valuetype0 = napi_valuetype::napi_null; NAPI_CALL(env, napi_typeof(env, napiWantAgentFlags, &valuetype0)); - NAPI_ASSERT(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype0 == napi_number, "Wrong argument type. Numbers expected."); int32_t value0 = 0; NAPI_CALL(env, napi_get_value_int32(env, napiWantAgentFlags, &value0)); paras.wantAgentFlags.emplace_back(static_cast(value0)); @@ -1229,24 +1285,15 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) return NapiGetNull(env); } - // Get context - napi_value global = 0; - NAPI_CALL(env, napi_get_global(env, &global)); - napi_value abilityObj = 0; - NAPI_CALL(env, napi_get_named_property(env, global, "ability", &abilityObj)); - Ability *ability = nullptr; - NAPI_CALL(env, napi_get_value_external(env, abilityObj, (void **)&ability)); - std::shared_ptr context = ability->GetContext(); - bool callBackMode = false; if (argc >= NUMBER_OF_PARAMETERS_TWO) { napi_valuetype valuetype; NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + NAPI_ASSERT_RETURN_NULL(env, valuetype == napi_function, "Wrong argument type. Function expected."); callBackMode = true; } - AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantAgentCallbackInfo{ + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantAgentCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, @@ -1260,7 +1307,7 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) asyncCallbackInfo->requestCode = requestCode; asyncCallbackInfo->wantAgentFlags = wantAgentFlags; asyncCallbackInfo->extraInfo.reset(new (std::nothrow) AAFwk::WantParams(extraInfo)); - asyncCallbackInfo->context = context; + asyncCallbackInfo->context = OHOS::AbilityRuntime::Context::GetApplicationContext(); if (callBackMode) { napi_create_reference(env, argv[1], 1, &asyncCallbackInfo->callback[0]); @@ -1290,4 +1337,4 @@ napi_value NapiGetNull(napi_env env) napi_get_null(env, &result); return result; } -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.h b/interfaces/kits/napi/wantagent/napi_want_agent.h index e79f2e93d5edde266d6865783350ec782ddee7ca..b6312c5853ad564dce45e0aede661c7ea2ba1790 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.h +++ b/interfaces/kits/napi/wantagent/napi_want_agent.h @@ -16,22 +16,22 @@ #ifndef NAPI_WANT_AGENT_H #define NAPI_WANT_AGENT_H -#include -#include #include +#include +#include #include +#include "ability.h" +#include "completed_callback.h" +#include "context/context.h" +#include "napi/native_api.h" #include "napi/native_common.h" #include "napi/native_node_api.h" - -#include "want_agent_constant.h" -#include "completed_callback.h" -#include "context.h" +#include "trigger_info.h" #include "want.h" -#include "want_params.h" -#include "ability.h" #include "want_agent.h" -#include "trigger_info.h" +#include "want_agent_constant.h" +#include "want_params.h" namespace OHOS { using namespace OHOS::AppExecFwk; @@ -61,7 +61,7 @@ struct AsyncGetWantAgentCallbackInfo { int32_t requestCode = -1; std::vector wantAgentFlags; std::shared_ptr extraInfo; - std::shared_ptr context; + std::shared_ptr context; std::shared_ptr wantAgent; }; @@ -117,7 +117,6 @@ struct AsyncTriggerCallbackInfo { napi_ref callback[2] = {0}; bool callBackMode = false; std::shared_ptr triggerObj; - std::shared_ptr context; std::shared_ptr wantAgent; Notification::WantAgent::TriggerInfo triggerInfo; }; diff --git a/interfaces/kits/napi/wantagent/native_module.cpp b/interfaces/kits/napi/wantagent/native_module.cpp index 0177c32c6cfb67d60cce620ccc660bd8da784a02..f4474a384bc9d96c11bce2005773ae619d2c939e 100644 --- a/interfaces/kits/napi/wantagent/native_module.cpp +++ b/interfaces/kits/napi/wantagent/native_module.cpp @@ -14,8 +14,8 @@ */ #include -#include -#include +#include +#include #include #include "napi_want_agent.h" diff --git a/notification.gni b/notification.gni index 54fa4469fc4810380c4d1e4c2e64d1a2b8053dda..8a5ca46cab2350d2b8f5f71a667fdb9981c9613e 100644 --- a/notification.gni +++ b/notification.gni @@ -21,6 +21,8 @@ interfaces_path = "${ans_standard_path}/interfaces" core_path = "${frameworks_path}/ans/core" +native_path = "${frameworks_path}/ans/native" + test_path = "${ans_standard_path}/test" tools_path = "${ans_standard_path}/tools" @@ -28,15 +30,17 @@ tools_path = "${ans_standard_path}/tools" aafwk_path = "//foundation/aafwk/standard" ans_standard_external_deps = [ - "aafwk_standard:base", - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] + +distributed_notification_supported = true diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml old mode 100755 new mode 100644 index 7f45c1fc08c584b6ff62c2b12119baacbd64c0e1..55c3ff31e2aa4ff1f2bf9c2d962e27bf0cc09837 --- a/sa_profile/3203.xml +++ b/sa_profile/3203.xml @@ -17,6 +17,9 @@ 3203 /system/lib/libans.z.so + 1301 + 3299 + 5000 true false 1 diff --git a/services/BUILD.gn b/services/BUILD.gn index 14494d7b40075d79c1ada3e30d41f720d08f87f2..6f1abec6e964b1fe3e4c1c9fef18287d26c62866 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -11,6 +11,12 @@ # See the License for the specific language governing permissions and # limitations under the License. +import("//base/notification/ans_standard/notification.gni") + group("services_target") { deps = [ "ans:ans_targets" ] + + if (distributed_notification_supported) { + deps += [ "distributed:libans_distributed" ] + } } diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 180ec3c81061f8981fa8c7771903206df173818b..12c62d3079d00a2f0828f1a3df7197bd455b9da4 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -19,12 +19,7 @@ group("ans_targets") { } config("public_ans_config") { - include_dirs = [ - "${services_path}/ans/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", - ] + include_dirs = [ "${services_path}/ans/include" ] defines = [ "APP_LOG_TAG = \"Ans\"", "LOG_DOMAIN = 0xD002200", @@ -38,13 +33,15 @@ ohos_shared_library("libans") { "src/advanced_notification_service.cpp", "src/advanced_notification_service_ability.cpp", "src/bundle_manager_helper.cpp", - "src/disturb_filter.cpp", "src/notification_preferences.cpp", "src/notification_preferences_database.cpp", "src/notification_preferences_info.cpp", "src/notification_slot_filter.cpp", "src/notification_subscriber_manager.cpp", "src/permission_filter.cpp", + "src/reminder_data_manager.cpp", + "src/reminder_event_manager.cpp", + "src/reminder_timer_info.cpp", "src/system_event_observer.cpp", ] @@ -53,13 +50,12 @@ ohos_shared_library("libans") { "//utils/native/base:utils_config", ] + defines = [] + deps = [ "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", ] @@ -67,7 +63,21 @@ ohos_shared_library("libans") { cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] } - external_deps = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + + external_deps = [ + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "distributeddatamgr:distributeddata_inner", + "multimedia_image_standard:image_native", + "multimedia_media_standard:media_client", + "os_account_standard:os_account_innerkits", + "time_native:time_service", + ] external_deps += ans_standard_external_deps subsystem_name = "notification" diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 67445a14771839cb95be63c93b71062d3ddace1b..95cc804a56656635c4b01a2bced396738b6da201 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -25,6 +25,7 @@ #include "event_runner.h" #include "refbase.h" +#include "ans_const_define.h" #include "ans_manager_stub.h" #include "distributed_kv_data_manager.h" #include "distributed_kvstore_death_recipient.h" @@ -36,7 +37,6 @@ namespace OHOS { namespace Notification { - class AdvancedNotificationService final : public AnsManagerStub { public: ~AdvancedNotificationService() override; @@ -71,8 +71,6 @@ public: const sptr notification, const std::string &representativeBundle) override; ErrCode SetNotificationBadgeNum(int num) override; ErrCode GetBundleImportance(int &importance) override; - ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode) override; - ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode) override; ErrCode HasNotificationPolicyAccessPermission(bool &granted) override; ErrCode SetPrivateNotificationsAllowed(bool allow) override; ErrCode GetPrivateNotificationsAllowed(bool &allow) override; @@ -101,13 +99,44 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; + ErrCode SetDoNotDisturbDate(const sptr &date) override; + ErrCode GetDoNotDisturbDate(sptr &date) override; + ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport) override; + ErrCode CancelGroup(const std::string &groupName) override; + ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + + ErrCode IsDistributedEnabled(bool &enabled) override; + ErrCode EnableDistributed(bool enabled) override; + ErrCode EnableDistributedByBundle(const sptr &bundleOption, bool enabled) override; + ErrCode EnableDistributedSelf(bool enabled) override; + ErrCode IsDistributedEnableByBundle(const sptr &bundleOption, bool &enabled) override; + ErrCode GetDeviceRemindType(NotificationConstant::RemindType &remindType) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; + ErrCode PublishContinuousTaskNotification(const sptr &request) override; + ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) override; + ErrCode PublishReminder(sptr &reminder) override; + ErrCode CancelReminder(const int32_t reminderId) override; + ErrCode GetValidReminders(std::vector> &reminders) override; + ErrCode CancelAllReminders() override; + ErrCode IsSupportTemplate(const std::string &templateName, bool &support) override; // SystemEvent void OnBundleRemoved(const sptr &bundleOption); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + void OnScreenOn(); + void OnScreenOff(); +#endif // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); + ErrCode CancelPreparedNotification( + int notificationId, const std::string &label, const sptr &bundleOption); + ErrCode PrepareNotificationInfo( + const sptr &request, sptr &bundleOption); + ErrCode PublishPreparedNotification( + const sptr &request, const sptr &bundleOption); private: struct RecentInfo; @@ -119,9 +148,11 @@ private: void AddToNotificationList(const std::shared_ptr &record); void UpdateInNotificationList(const std::shared_ptr &record); + ErrCode AssignToNotificationList(const std::shared_ptr &record); ErrCode RemoveFromNotificationList(const sptr &bundleOption, const std::string &label, int notificationId, sptr ¬ification, bool isCancel = false); ErrCode RemoveFromNotificationList(const std::string &key, sptr ¬ification, bool isCancel = false); + ErrCode RemoveFromNotificationListForDeleteAll(const std::string &key, sptr ¬ification); std::vector GetNotificationKeys(const sptr &bundleOption); bool IsNotificationExists(const std::string &key); void SortNotificationList(); @@ -137,9 +168,35 @@ private: int64_t GetNowSysTime(); ErrCode ActiveNotificationDump(std::vector &dumpInfo); ErrCode RecentNotificationDump(std::vector &dumpInfo); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + ErrCode DistributedNotificationDump(std::vector &dumpInfo); +#endif ErrCode SetRecentNotificationCount(const std::string arg); void UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason); + void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); + bool CheckPermission(const std::string &bundleName); + ErrCode PrepereContinuousTaskNotificationRequest(const sptr &request, const int &uid); + bool GetActiveUserId(int& userId); + void TriggerRemoveWantAgent(const sptr &request); + + ErrCode SetNotificationRemindType(sptr notification, bool isLocal); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::vector GetLocalNotificationKeys(const sptr &bundleOption); + NotificationConstant::RemindType GetRemindType(); + ErrCode DoDistributedPublish( + const sptr bundleOption, const std::shared_ptr record); + ErrCode DoDistributedDelete(const std::string deviceId, const sptr notification); + std::string GetNotificationDeviceId(const std::string &key); + void OnDistributedPublish( + const std::string &deviceId, const std::string &bundleName, sptr &request); + void OnDistributedUpdate( + const std::string &deviceId, const std::string &bundleName, sptr &request); + void OnDistributedDelete( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id); + ErrCode GetDistributedEnableInApplicationInfo(const sptr bundleOption, bool &enable); +#endif + private: static sptr instance_; static std::mutex instanceMutex_; @@ -152,9 +209,12 @@ private: std::shared_ptr distributedKvStoreDeathRecipient_ = nullptr; std::shared_ptr systemEventObserver_ = nullptr; DistributedKv::DistributedKvDataManager dataManager_; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + NotificationConstant::DistributedReminderPolicy distributedReminderPolicy_ = DEFAULT_DISTRIBUTED_REMINDER_POLICY; + bool localScreenOn_ = true; +#endif }; - } // namespace Notification } // namespace OHOS -#endif // ADVANCED_NOTIFICATION_SERVICE_H \ No newline at end of file +#endif // ADVANCED_NOTIFICATION_SERVICE_H diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 10f8ac311f8f895412713a166e8aed543a632338..ec5c866d8169672394e40ff6507a2da72a8a1df4 100644 --- a/services/ans/include/advanced_notification_service_ability.h +++ b/services/ans/include/advanced_notification_service_ability.h @@ -23,7 +23,6 @@ namespace OHOS { namespace Notification { - class AdvancedNotificationServiceAbility final : public SystemAbility { public: AdvancedNotificationServiceAbility(const int32_t systemAbilityId, bool runOnCreate); @@ -38,7 +37,6 @@ private: private: sptr service_; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index bb8dc8169f727c85d7c76cd9043379b08c466d73..5bd43d100c53db2e4ae79e1be51fcff3520f26a7 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -29,12 +29,14 @@ namespace OHOS { namespace Notification { - class BundleManagerHelper : public DelayedSingleton { public: std::string GetBundleNameByUid(int uid); bool IsSystemApp(int uid); - int GetDefaultUidByBundleName(const std::string& bundle); + int GetDefaultUidByBundleName(const std::string &bundle); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + bool GetDistributedNotificationEnabled(const std::string &bundleName, const int userId); +#endif private: void Connect(); @@ -49,7 +51,6 @@ private: DECLARE_DELAYED_SINGLETON(BundleManagerHelper) }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/distributed_kvstore_death_recipient.h b/services/ans/include/distributed_kvstore_death_recipient.h index d5960480143d54ad5727d664162023f7ccdd2429..a023318892e01241f667bc2fddcaa37746b13bb5 100644 --- a/services/ans/include/distributed_kvstore_death_recipient.h +++ b/services/ans/include/distributed_kvstore_death_recipient.h @@ -22,7 +22,6 @@ namespace OHOS { namespace Notification { - class DistributedKvStoreDeathRecipient : public DistributedKv::KvStoreDeathRecipient { public: DistributedKvStoreDeathRecipient(const std::function &callback) @@ -43,7 +42,6 @@ public: private: std::function callback_; }; - } // namespace Notification } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTRIBUTED_KVSTORE_DEATH_RECIPIENT_H \ No newline at end of file diff --git a/services/ans/include/interface_system_event.h b/services/ans/include/interface_system_event.h index b4aba38fcbc2d2b0886146ae80adae52b53b7b4c..0c583550351610ef96b15fcf55a27b60b5a45867 100644 --- a/services/ans/include/interface_system_event.h +++ b/services/ans/include/interface_system_event.h @@ -23,11 +23,13 @@ namespace OHOS { namespace Notification { - struct ISystemEvent { std::function &)> onBundleRemoved; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::function onScreenOn; + std::function onScreenOff; +#endif }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_filter.h b/services/ans/include/notification_filter.h index 30dc7b90205adf2f8ce107c7d51e8ba19574db0e..4c229109e32e821e8895c07f879e21aff5490c91 100644 --- a/services/ans/include/notification_filter.h +++ b/services/ans/include/notification_filter.h @@ -24,18 +24,16 @@ namespace OHOS { namespace Notification { - class INotificationFilter { public: - INotificationFilter(){}; - virtual ~INotificationFilter(){}; + INotificationFilter() {}; + virtual ~INotificationFilter() {}; virtual void OnStart() = 0; virtual void OnStop() = 0; virtual ErrCode OnPublish(const std::shared_ptr &record) = 0; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 103c4c10dbd05bf3ed01f306d9e20ca4dee520d4..04ef9233cd0113c01f06ab8a044454624be52cc2 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -19,36 +19,41 @@ #include "refbase.h" #include "singleton.h" +#include "notification_do_not_disturb_date.h" #include "notification_preferences_database.h" - namespace OHOS { namespace Notification { class NotificationPreferences final { public: DISALLOW_COPY_AND_MOVE(NotificationPreferences); static NotificationPreferences &GetInstance(); - ErrCode AddNotificationSlots(const sptr &bundleOption, const std::vector> &slots); + ErrCode AddNotificationSlots( + const sptr &bundleOption, const std::vector> &slots); ErrCode AddNotificationSlotGroups( const sptr &bundleOption, const std::vector> &groups); ErrCode AddNotificationBundleProperty(const sptr &bundleOption); - ErrCode RemoveNotificationSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType); + ErrCode RemoveNotificationSlot( + const sptr &bundleOption, const NotificationConstant::SlotType &slotType); ErrCode RemoveNotificationAllSlots(const sptr &bundleOption); - ErrCode RemoveNotificationSlotGroups(const sptr &bundleOption, const std::vector &groupIds); + ErrCode RemoveNotificationSlotGroups( + const sptr &bundleOption, const std::vector &groupIds); ErrCode RemoveNotificationForBundle(const sptr &bundleOption); - ErrCode UpdateNotificationSlots(const sptr &bundleOption, const std::vector> &slot); + ErrCode UpdateNotificationSlots( + const sptr &bundleOption, const std::vector> &slot); ErrCode UpdateNotificationSlotGroups( const sptr &bundleOption, const std::vector> &groups); - ErrCode GetNotificationSlot( - const sptr &bundleOption, const NotificationConstant::SlotType &type, sptr &slot); - ErrCode GetNotificationAllSlots(const sptr &bundleOption, std::vector> &slots); + ErrCode GetNotificationSlot(const sptr &bundleOption, + const NotificationConstant::SlotType &type, sptr &slot); + ErrCode GetNotificationAllSlots( + const sptr &bundleOption, std::vector> &slots); ErrCode GetNotificationSlotsNumForBundle(const sptr &bundleOption, int &num); - ErrCode GetNotificationSlotGroup( - const sptr &bundleOption, const std::string &groupId, sptr &group); + ErrCode GetNotificationSlotGroup(const sptr &bundleOption, const std::string &groupId, + sptr &group); ErrCode GetNotificationAllSlotGroups( const sptr &bundleOption, std::vector> &groups); - ErrCode GetNotificationAllSlotInSlotGroup( - const sptr &bundleOption, const std::string &groupId, std::vector> &slots); + ErrCode GetNotificationAllSlotInSlotGroup(const sptr &bundleOption, + const std::string &groupId, std::vector> &slots); ErrCode IsShowBadge(const sptr &bundleOption, bool &enable); ErrCode SetShowBadge(const sptr &bundleOption, const bool enable); ErrCode GetImportance(const sptr &bundleOption, int &importance); @@ -59,43 +64,48 @@ public: ErrCode SetPrivateNotificationsAllowed(const sptr &bundleOption, const bool allow); ErrCode GetNotificationsEnabledForBundle(const sptr &bundleOption, bool &enabled); ErrCode SetNotificationsEnabledForBundle(const sptr &bundleOption, const bool enabled); - ErrCode GetNotificationsEnabled(bool &enabled); - ErrCode SetNotificationsEnabled(const bool &enabled); - ErrCode GetDisturbMode(NotificationConstant::DisturbMode &mode); - ErrCode SetDisturbMode(const NotificationConstant::DisturbMode &mode); + ErrCode GetNotificationsEnabled(const sptr &bundleOption, bool &enabled); + ErrCode SetNotificationsEnabled(const sptr &bundleOption, const bool &enabled); + ErrCode GetDoNotDisturbDate(const sptr &bundleOption, + sptr &date); + ErrCode SetDoNotDisturbDate(const sptr &bundleOption, + const sptr date); + ErrCode GetTemplateSupported(const std::string& templateName, bool &support); + ErrCode ClearNotificationInRestoreFactorySettings(); void OnDistributedKvStoreDeathRecipient(); private: - ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, const sptr &slot, - NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckGroupForCreateSlotGroup(const sptr &bundleOption, const sptr &group, - NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckSlotForRemoveSlot(const sptr &bundleOption, const NotificationConstant::SlotType &slotType, + ErrCode CheckSlotForCreateSlot(const sptr &bundleOption, + const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; + ErrCode CheckGroupForCreateSlotGroup(const sptr &bundleOption, + const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; + ErrCode CheckSlotForRemoveSlot(const sptr &bundleOption, + const NotificationConstant::SlotType &slotType, NotificationPreferencesInfo &preferencesInfo) const; + ErrCode CheckGroupForRemoveSlotGroup(const sptr &bundleOption, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckGroupForRemoveSlotGroup( - const sptr &bundleOption, const std::string &groupId, NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckSlotForUpdateSlot(const sptr &bundleOption, const sptr &slot, - NotificationPreferencesInfo &preferencesInfo) const; - ErrCode CheckGroupForUpdateSlotGroup(const sptr &bundleOption, const sptr &group, - NotificationPreferencesInfo &preferencesInfo) const; - template - ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const sptr &bundleOption, - const BundleType &type, const T &value); - template - ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, - const BundleType &type, const T &value); - template - ErrCode GetBundleProperty(const sptr &bundleOption, const BundleType &type, T &value) const; + ErrCode CheckSlotForUpdateSlot(const sptr &bundleOption, + const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; + ErrCode CheckGroupForUpdateSlotGroup(const sptr &bundleOption, + const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; + template + ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, + const sptr &bundleOption, const BundleType &type, const T &value); + template + ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, + const sptr &bundleOption, const BundleType &type, const T &value); + template + ErrCode GetBundleProperty( + const sptr &bundleOption, const BundleType &type, T &value) const; std::string GenerateBundleKey(const sptr &bundleOption) const; + bool GetActiveUserId(int& userId); private: NotificationPreferencesInfo preferencesInfo_ {}; std::unique_ptr preferncesDB_ = nullptr; DECLARE_DELAYED_REF_SINGLETON(NotificationPreferences); }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index b88bafbf29173db024538d1b4ddceae2b9ee74da..6b531e4515ecd4242f30a8888b049db1954909ff 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -24,22 +24,24 @@ namespace OHOS { namespace Notification { - class NotificationPreferencesDatabase final { public: NotificationPreferencesDatabase(); ~NotificationPreferencesDatabase(); - bool PutSlotsToDisturbeDB(const std::string &bundleKey, const std::vector> &slots); - bool PutGroupsToDisturbeDB(const std::string &bundleKey, const std::vector> &groups); + bool PutSlotsToDisturbeDB( + const std::string &bundleName, const int &bundleUid, const std::vector> &slots); + bool PutGroupsToDisturbeDB( + const std::string &bundleName, const int &bundleUid, const std::vector> &groups); bool PutBundlePropertyToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); - bool PutShowBadge(const std::string &bundleKey, const bool &enable); - bool PutImportance(const std::string &bundleKey, const int &importance); - bool PutTotalBadgeNums(const std::string &bundleKey, const int &totalBadgeNum); - bool PutPrivateNotificationsAllowed(const std::string &bundleKey, const bool &allow); - bool PutNotificationsEnabledForBundle(const std::string &bundleKey, const bool &enabled); - bool PutNotificationsEnabled(const bool &enabled); - bool PutDisturbMode(const NotificationConstant::DisturbMode &mode); + bool PutShowBadge(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable); + bool PutImportance(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &importance); + bool PutTotalBadgeNums(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &totalBadgeNum); + bool PutPrivateNotificationsAllowed(const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &allow); + bool PutNotificationsEnabledForBundle( + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled); + bool PutNotificationsEnabled(const int32_t &userId, const bool &enabled); + bool PutDoNotDisturbDate(const int32_t &userId, const sptr &date); bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); @@ -57,9 +59,9 @@ private: void CloseKvStore(); bool CheckKvStore(); - bool CheckBundle(const std::string &bundleKey); + bool CheckBundle(const std::string &bundleName, const int &bundleUid); bool PutBundlePropertyValueToDisturbeDB(const NotificationPreferencesInfo::BundleInfo &bundleInfo); - template + template OHOS::DistributedKv::Status PutBundlePropertyToDisturbeDB( const std::string &bundleKey, const BundleType &type, const T &t); bool PutBundleToDisturbeDB( @@ -71,9 +73,9 @@ private: bool GetRemoveGroupKeysFromDisturbeDB( const std::string &bundleKey, const std::string &groupId, std::vector &keys); - bool SlotToEntry(const std::string &bundleKey, const sptr &slot, + bool SlotToEntry(const std::string &bundleName, const int &bundleUid, const sptr &slot, std::vector &entries); - bool GroupToEntry(const std::string &bundleKey, const sptr &group, + bool GroupToEntry(const std::string &bundleName, const int &bundleUid, const sptr &group, std::vector &entries); void GenerateGroupEntry(const std::string &bundleKey, const sptr &group, std::vector &entries) const; @@ -87,6 +89,7 @@ private: std::string VectorToString(const std::vector &data) const; void StringToVector(const std::string &str, std::vector &data) const; int StringToInt(const std::string &str) const; + int64_t StringToInt64(const std::string &str) const; bool IsSlotKey(const std::string &bundleKey, const std::string &key) const; bool IsGroupKey(const std::string &bundleKey, const std::string &key) const; std::string GenerateSlotKey( @@ -102,7 +105,9 @@ private: const OHOS::DistributedKv::Entry &entry); void ParseBundlePropertyFromDisturbeDB(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &bundleKey, const OHOS::DistributedKv::Entry &entry); - void ParseDisturbeMode(NotificationPreferencesInfo &info); + void ParseDoNotDisturbType(NotificationPreferencesInfo &info); + void ParseDoNotDisturbBeginDate(NotificationPreferencesInfo &info); + void ParseDoNotDisturbEndDate(NotificationPreferencesInfo &info); void ParseEnableAllNotification(NotificationPreferencesInfo &info); void ParseGroupDescription( const std::string &bundleKey, sptr &group, const OHOS::DistributedKv::Entry &entry); @@ -110,9 +115,11 @@ private: void ParseBundleImportance(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleShowBadge(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleBadgeNum(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; - void ParseBundlePrivateAllowed(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; + void ParseBundlePrivateAllowed( + NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseBundleEnableNotification( NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; + void ParseBundleUid(NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const; void ParseSlot( const std::string &findString, sptr &slot, const OHOS::DistributedKv::Entry &entry); void ParseSlotGroupId(sptr &slot, const std::string &value) const; @@ -121,12 +128,18 @@ private: void ParseSlotShowBadge(sptr &slot, const std::string &value) const; void ParseSlotEnableLight(sptr &slot, const std::string &value) const; void ParseSlotEnableVrbration(sptr &slot, const std::string &value) const; - void ParseSlotLedLightColor(sptr &slot, const std::string &kevaluey) const; + void ParseSlotLedLightColor(sptr &slot, const std::string &value) const; void ParseSlotLockscreenVisibleness(sptr &slot, const std::string &value) const; void ParseSlotSound(sptr &slot, const std::string &value) const; void ParseSlotVibrationSytle(sptr &slot, const std::string &value) const; void ParseSlotEnableBypassDnd(sptr &slot, const std::string &value) const; + std::string GenerateBundleLablel(const NotificationPreferencesInfo::BundleInfo &bundleInfo) const; + void GetDoNotDisturbType(NotificationPreferencesInfo &info, int userId); + void GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int userId); + void GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int userId); + void GetEnableAllNotification(NotificationPreferencesInfo &info, int userId); + static const std::map &, std::string &)>> slotMap_; @@ -136,10 +149,9 @@ private: const DistributedKv::AppId appId_ {APP_ID}; const DistributedKv::StoreId storeId_ {STORE_ID}; - std::unique_ptr kvStorePtr_ = nullptr; + std::shared_ptr kvStorePtr_ = nullptr; DistributedKv::DistributedKvDataManager dataManager_; }; - } // namespace Notification } // namespace OHOS -#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_DATABASE_H \ No newline at end of file +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_NOTIFICATION_PREFERENCES_DATABASE_H diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 4e78453253c5ec179402bee14b80d3e896886f67..943252dc58036f4fa90477da57ec426f749f3d59 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -21,6 +21,7 @@ #include #include "notification_bundle_option.h" +#include "notification_do_not_disturb_date.h" #include "notification_slot.h" #include "notification_slot_group.h" #include "preferences_constant.h" @@ -79,19 +80,21 @@ public: {} ~NotificationPreferencesInfo() {} - void SetEnabledAllNotification(const bool &value); - bool GetEnabledAllNotification() const; - void SetDisturbMode(const NotificationConstant::DisturbMode &mode); - NotificationConstant::DisturbMode GetDisturbMode() const; void SetBundleInfo(const BundleInfo &info); bool GetBundleInfo(const sptr &bundleOption, BundleInfo &info) const; bool RemoveBundleInfo(const sptr &bundleOption); bool IsExsitBundleInfo(const sptr &bundleOption) const; void ClearBundleInfo(); + void SetDoNotDisturbDate(const int32_t &userId, + const sptr &doNotDisturbDate); + bool GetDoNotDisturbDate(const int32_t &userId, + sptr &doNotDisturbDate) const; + void SetEnabledAllNotification(const int32_t &userId, const bool &enable); + bool GetEnabledAllNotification(const int32_t &userId, bool &enable) const; private: - bool isEnabledAllNotification_ = true; - NotificationConstant::DisturbMode disturbMode_ = NotificationConstant::DisturbMode::ALLOW_ALL; + std::map isEnabledAllNotification_; + std::map> doNotDisturbDate_; std::map infos_; }; } // namespace Notification diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index f41e65faf8544b23d92ee845e964744b9712207d..9939e09a63b7893c21d4a45810ca4b6b0ee0002b 100644 --- a/services/ans/include/notification_record.h +++ b/services/ans/include/notification_record.h @@ -18,6 +18,8 @@ #include "refbase.h" +#include + #include "notification.h" #include "notification_bundle_option.h" #include "notification_request.h" @@ -25,14 +27,15 @@ namespace OHOS { namespace Notification { - struct NotificationRecord { sptr bundleOption; sptr request; sptr notification; sptr slot; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId; +#endif // DISTRIBUTED_NOTIFICATION_SUPPORTED }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_slot_filter.h b/services/ans/include/notification_slot_filter.h index 45092a2bc17a5b32e160ef01f914003d5941b3d4..3b8978c2c581b2bf23b61f427beab1087c4aebd9 100644 --- a/services/ans/include/notification_slot_filter.h +++ b/services/ans/include/notification_slot_filter.h @@ -20,18 +20,16 @@ namespace OHOS { namespace Notification { - class NotificationSlotFilter : public INotificationFilter { public: - NotificationSlotFilter(){}; - ~NotificationSlotFilter(){}; + NotificationSlotFilter() {}; + ~NotificationSlotFilter() {}; void OnStart() override; void OnStop() override; ErrCode OnPublish(const std::shared_ptr &record) override; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index 0e1ff2c115d90f61715a707760247871abc5e259..f6e2ae64531e82389a465593f32ad15f8b599679 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -28,6 +28,7 @@ #include "singleton.h" #include "ans_subscriber_interface.h" +#include "notification_bundle_option.h" #include "notification_constant.h" #include "notification_request.h" #include "notification_sorting_map.h" @@ -45,7 +46,7 @@ public: void NotifyCanceled( const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); void NotifyUpdated(const sptr ¬ificationMap); - void NotifyDisturbModeChanged(const NotificationConstant::DisturbMode &mode); + void NotifyDoNotDisturbDateChanged(const sptr &date); void OnRemoteDied(const wptr &object); private: @@ -54,12 +55,13 @@ private: std::shared_ptr FindSubscriberRecord(const wptr &object); std::shared_ptr FindSubscriberRecord(const sptr &subscriber); std::shared_ptr CreateSubscriberRecord(const sptr &subscriber); - void AddRecordInfo(std::shared_ptr &record, const sptr &subscribeInfo); + void AddRecordInfo( + std::shared_ptr &record, const sptr &subscribeInfo); void RemoveRecordInfo( std::shared_ptr &record, const sptr &subscribeInfo); - void AddSubscriberInner( + ErrCode AddSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo); - void RemoveSubscriberInner( + ErrCode RemoveSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo); void NotifyConsumedInner( @@ -67,7 +69,7 @@ private: void NotifyCanceledInner( const sptr ¬ification, const sptr ¬ificationMap, int deleteReason); void NotifyUpdatedInner(const sptr ¬ificationMap); - void NotifyDisturbModeChangedInner(const NotificationConstant::DisturbMode &mode); + void NotifyDoNotDisturbDateChangedInner(const sptr &date); private: std::list> subscriberRecordList_ {}; @@ -79,7 +81,6 @@ private: DECLARE_DELAYED_SINGLETON(NotificationSubscriberManager); DISALLOW_COPY_AND_MOVE(NotificationSubscriberManager); }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/permission_filter.h b/services/ans/include/permission_filter.h index 850069cc8ce2a7a2425fda46887324b1246ae541..f0610279d9ec938eeea5cd8f70484eb3b922af14 100644 --- a/services/ans/include/permission_filter.h +++ b/services/ans/include/permission_filter.h @@ -20,18 +20,16 @@ namespace OHOS { namespace Notification { - class PermissionFilter : public INotificationFilter { public: - PermissionFilter(){}; - ~PermissionFilter(){}; + PermissionFilter() {}; + ~PermissionFilter() {}; void OnStart() override; void OnStop() override; ErrCode OnPublish(const std::shared_ptr &record) override; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index 30702e8febbf4f880693c3c088b5c6c8cfd3323f..b5430c697dbc41372481a6455bac9aa86055aec5 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -18,8 +18,9 @@ namespace OHOS { namespace Notification { - -const static std::string KEY_DISTURB_MODE = "ans_disturbMode"; +const static std::string KEY_DO_NOT_DISTURB_TYPE = "ans_doNotDisturbType"; +const static std::string KEY_DO_NOT_DISTURB_BEGIN_DATE = "ans_doNotDisturbBeginDate"; +const static std::string KEY_DO_NOT_DISTURB_END_DATE = "ans_doNotDisturbEndDate"; const static std::string KEY_ENABLE_ALL_NOTIFICATION = "ans_notificationAll"; const static std::string KEY_BUNDLE_LABEL = "label_ans_bundle_"; const static std::string KEY_UNDER_LINE = "_"; @@ -31,6 +32,7 @@ const static std::string KEY_BUNDLE_SHOW_BADGE = "showBadge"; const static std::string KEY_BUNDLE_BADGE_TOTAL_NUM = "badgeTotalNum"; const static std::string KEY_BUNDLE_PRIVATE_ALLOWED = "privateAllowed"; const static std::string KEY_BUNDLE_ENABLE_NOTIFICATION = "enabledNotification"; +const static std::string KEY_BUNDLE_UID = "uid"; const static std::string KEY_GROUP = "group"; const static std::string KEY_GROUP_ID = "id"; @@ -72,7 +74,6 @@ enum class BundleType { BUNDLE_PRIVATE_ALLOWED_TYPE, BUNDLE_ENABLE_NOTIFICATION_TYPE, }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..c1167f1bae653e2bd515541d724a8a7a20534df0 --- /dev/null +++ b/services/ans/include/reminder_data_manager.h @@ -0,0 +1,449 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H + +#include +#include + +#include "advanced_notification_service.h" +#include "player.h" +#include "reminder_request.h" +#include "reminder_timer_info.h" + +namespace OHOS { +namespace Notification { +class ReminderDataManager final { +public: + ReminderDataManager() {}; + ~ReminderDataManager() {}; + + ReminderDataManager(ReminderDataManager &other) = delete; + ReminderDataManager& operator = (const ReminderDataManager &other) = delete; + + /** + * @brief Cancels all the reminders relative to the bundle option. + */ + void CancelAllReminders(const sptr &bundleOption); + + /** + * @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. + */ + void CancelReminder(const int32_t &reminderId, const sptr &bundleOption); + + /** + * @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(); + + /** + * 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 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. + */ + void PublishReminder(sptr &reminder, 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(AdvancedNotificationService *advancedNotificationService); + + /** + * @brief Show the reminder. + * + * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. + */ + void ShowActiveReminder(); + + /** + * @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); + + /** + * @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); + + static const uint8_t TIME_ZONE_CHANGE; + static const uint8_t DATE_TIME_CHANGE; + +private: + enum class TimerType : uint8_t { + TRIGGER_TIMER, + ALERTING_TIMER + }; + + /** + * 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); + + /** + * 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 std::string &bundleName) 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. + * @return pointer of ReminderTimerInfo. + */ + std::shared_ptr CreateTimerInfo(TimerType type) 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); + + /** + * Find bundle option from {@link notificationBundleOptionMap_} by reminder id. + * + * @param reminderId Indicates the reminder id. + * @return pointer of NotificationBundleOption or nullptr. + */ + sptr FindNotificationBundleOption(const int32_t &reminderId) const; + + /** + * 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(); + + /** + * Obtains all the reminders of the target bundle name. + * + * @param bundleName Indicates the bundle name. + * @return all the reminders of the target bundle name. + */ + std::vector> GetSameBundleRemindersLocked(std::string &bundleName); + + void HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged); + + /** + * @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(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; + + /** + * Judge the two reminders is belong to the same application or not. + * + * @param reminder Indicates the first reminder. + * @param otherPkgName Indicates the package name of second reminder. + * @param otherUserId Indicates the user id of second reminder. + * @return true if the two reminders belong to the same application. + */ + bool IsBelongToSameApp( + const sptr reminder, const std::string otherPkgName, const int otherUserId); + + 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. + */ + std::vector> RefreshRemindersLocked(uint8_t type); + + /** + * 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); + + /** + * @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 the recent reminder timing. + */ + void StartRecentReminder(); + + /** + * 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); + + /** + * @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 waitInMilli, 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); + + static bool cmp(sptr &reminderRequest, sptr &other); + + /** + * Single instance. + */ + static std::shared_ptr REMINDER_DATA_MANAGER; + + /** + * Used for multi-thread syncronise. + */ + static std::mutex MUTEX; + static std::mutex SHOW_MUTEX; + static std::mutex ALERT_MUTEX; + + /** + * Max number of reminders limit for the whole system. + */ + static const int16_t MAX_NUM_REMINDER_LIMIT_SYSTEM; + + /** + * Max number of reminders limit for one application. + */ + static const int16_t MAX_NUM_REMINDER_LIMIT_APP; + + /** + * 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_; + + /** + * Map used to record all the bundle information of the reminders in system. + */ + std::map> notificationBundleOptionMap_; + + /** + * 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. + */ + uint64_t timerIdAlerting_ {0}; + + /** + * Indicates the active reminder that timing is taking effect. + */ + int32_t activeReminderId_ = -1; + sptr activeReminder_ = nullptr; + + /** + * Indicates the reminder which is playing sound or vibration. + */ + int32_t alertingReminderId_ = -1; + sptr alertingReminder_ = nullptr; + + std::shared_ptr soundPlayer_ = nullptr; + + /** + * Indicates the total count of reminders in system. + */ + int16_t totalCount_ {0}; + AdvancedNotificationService *advancedNotificationService_; +}; +} // namespace OHOS +} // namespace Nofitifcation +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_DATA_MANAGER_H \ No newline at end of file diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..09c908f496c74cf9c9047e326fea8acf31cca3a0 --- /dev/null +++ b/services/ans/include/reminder_event_manager.h @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H +#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H + +#include "common_event_subscriber.h" +#include "reminder_data_manager.h" + +#include + +namespace OHOS { +namespace Notification { +class ReminderEventManager { +public: + 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; + +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(OHOS::EventFwk::Want &want) const; + void HandleProcessDied(OHOS::EventFwk::Want &want) const; + int32_t GetUid(const int userId, const std::string bundleName) const; + std::shared_ptr reminderDataManager_ = nullptr; +}; +}; +} // namespace OHOS +} // namespace Notification +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_EVENT_MANAGER_H diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h new file mode 100644 index 0000000000000000000000000000000000000000..0d8ddeb33efee159253c9ae1768f46cdc5c75bfb --- /dev/null +++ b/services/ans/include/reminder_timer_info.h @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_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; + } + + /** + * When timing is up, this function will execute as call back. + */ + void OnTrigger() override; + + /** + * Indicates the timing type. + */ + void SetType(const int &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_; +}; +} // namespace OHOS +} // namespace Notification + +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/ans/include/remote_death_recipient.h b/services/ans/include/remote_death_recipient.h index 400dfd58d209d710ebe01f1a765d70c176f184c7..ea52d41e60ef0fbeaf0378b823a560d83e72d654 100644 --- a/services/ans/include/remote_death_recipient.h +++ b/services/ans/include/remote_death_recipient.h @@ -12,18 +12,16 @@ * See the License for the specific language governing permissions and * limitations under the License. */ +#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H #include #include "iremote_object.h" #include "refbase.h" -#ifndef BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H -#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_REMOTE_DEATH_RECIPIENT_H - namespace OHOS { namespace Notification { - class RemoteDeathRecipient : public IRemoteObject::DeathRecipient { public: RemoteDeathRecipient(std::function &)> callback) @@ -46,7 +44,6 @@ public: private: std::function &)> callback_; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/system_event_observer.h b/services/ans/include/system_event_observer.h index 7fc8cd4fece62a6763e06ce43474d0b955e55552..382959c4f802efe02da74dfd433497a4131c8777 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -26,10 +26,9 @@ namespace OHOS { namespace Notification { - class SystemEventObserver { public: - SystemEventObserver(const ISystemEvent& callbacks); + SystemEventObserver(const ISystemEvent &callbacks); ~SystemEventObserver(); private: @@ -39,7 +38,6 @@ private: std::shared_ptr subscriber_ = nullptr; ISystemEvent callbacks_; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/system_event_subscriber.h b/services/ans/include/system_event_subscriber.h index 41b58c48db1f91ffe03ad44bdd576be7f300204c..593f92b8bb6c7386a0f06251a78ee3627f4778f9 100644 --- a/services/ans/include/system_event_subscriber.h +++ b/services/ans/include/system_event_subscriber.h @@ -22,7 +22,6 @@ namespace OHOS { namespace Notification { - class SystemEventSubscriber : public EventFwk::CommonEventSubscriber { public: SystemEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscribeInfo, @@ -43,7 +42,6 @@ public: private: std::function callback_; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 875112f77e009f61afabe4f21fd5427ad87944db..11d9f816adfade7aea25a2059e99965f8a96ea0a 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -19,11 +19,11 @@ #include #include +#include "ability_context.h" #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "bundle_manager_helper.h" -#include "disturb_filter.h" #include "ipc_skeleton.h" #include "notification_constant.h" #include "notification_filter.h" @@ -31,20 +31,35 @@ #include "notification_slot.h" #include "notification_slot_filter.h" #include "notification_subscriber_manager.h" +#include "os_account_manager.h" #include "permission_filter.h" +#include "reminder_data_manager.h" +#include "trigger_info.h" +#include "want_agent_helper.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 { - namespace { -static const std::string ACTIVE_NOTIFICATION_OPTION = "active"; -static const std::string RECENT_NOTIFICATION_OPTION = "recent"; -static const std::string SET_RECENT_COUNT_OPTION = "setRecentCount"; +constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active"; +constexpr char RECENT_NOTIFICATION_OPTION[] = "recent"; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed"; +#endif +constexpr char SET_RECENT_COUNT_OPTION[] = "setRecentCount"; +constexpr char FOUNDATION_BUNDLE_NAME[] = "ohos.global.systemres"; -static const int32_t NOTIFICATION_MIN_COUNT = 0; -static const int32_t NOTIFICATION_MAX_COUNT = 1024; +constexpr int32_t NOTIFICATION_MIN_COUNT = 0; +constexpr int32_t NOTIFICATION_MAX_COUNT = 1024; -static const int32_t DEFAULT_RECENT_COUNT = 16; +constexpr int32_t DEFAULT_RECENT_COUNT = 16; + +constexpr int HOURS_IN_ONE_DAY = 24; struct RecentNotification { sptr notification = nullptr; @@ -65,7 +80,6 @@ std::mutex AdvancedNotificationService::instanceMutex_; static const std::shared_ptr NOTIFICATION_FILTERS[] = { std::make_shared(), std::make_shared(), - std::make_shared(), }; inline std::string GetClientBundleName() @@ -143,7 +157,7 @@ inline ErrCode CheckPictureSize(const sptr &request) return result; } -inline ErrCode PrepereNotificationRequest(const sptr &request) +ErrCode PrepereNotificationRequest(const sptr &request) { std::string bundle = GetClientBundleName(); if (bundle.empty()) { @@ -158,6 +172,12 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque request->SetCreatorUid(uid); request->SetCreatorPid(pid); + int userId = SUBSCRIBE_USER_INIT; + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { + userId = SUBSCRIBE_USER_ALL; + } + request->SetCreatorUserId(userId); ErrCode result = CheckPictureSize(request); return result; @@ -185,10 +205,36 @@ AdvancedNotificationService::AdvancedNotificationService() ISystemEvent iSystemEvent = { std::bind(&AdvancedNotificationService::OnBundleRemoved, this, std::placeholders::_1), +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::bind(&AdvancedNotificationService::OnScreenOn, this), + std::bind(&AdvancedNotificationService::OnScreenOff, this), +#endif }; systemEventObserver_ = std::make_shared(iSystemEvent); dataManager_.RegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_); + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedNotificationManager::IDistributedCallback distributedCallback = { + .OnPublish = std::bind(&AdvancedNotificationService::OnDistributedPublish, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnUpdate = std::bind(&AdvancedNotificationService::OnDistributedUpdate, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnDelete = std::bind(&AdvancedNotificationService::OnDistributedDelete, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3, + std::placeholders::_4), + }; + DistributedNotificationManager::GetInstance()->RegisterCallback(distributedCallback); +#endif } AdvancedNotificationService::~AdvancedNotificationService() @@ -196,6 +242,9 @@ AdvancedNotificationService::~AdvancedNotificationService() dataManager_.UnRegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_); StopFilters(); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedNotificationManager::GetInstance()->UngegisterCallback(); +#endif } sptr AdvancedNotificationService::GenerateBundleOption() @@ -228,29 +277,79 @@ sptr AdvancedNotificationService::GenerateValidBundleO return validBundleOption; } -ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) +ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ptr &record) { - ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_OK; + if (!IsNotificationExists(record->notification->GetKey())) { + result = FlowControl(record); + } else { + if (record->request->IsAlertOneTime()) { + record->notification->SetEnableLight(false); + record->notification->SetEnableSound(false); + record->notification->SetEnableViration(false); + } + UpdateInNotificationList(record); + } + return result; +} + +ErrCode AdvancedNotificationService::CancelPreparedNotification( + int notificationId, const std::string &label, const sptr &bundleOption) +{ + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + sptr notification = nullptr; + result = RemoveFromNotificationList(bundleOption, label, notificationId, notification, true); + if (result != ERR_OK) { + return; + } + + if (notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete("", notification); +#endif + } + })); + return result; +} +ErrCode AdvancedNotificationService::PrepareNotificationInfo( + const sptr &request, sptr &bundleOption) +{ if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) && !IsSystemApp()) { return ERR_ANS_NON_SYSTEM_APP; } - ErrCode result = PrepereNotificationRequest(request); if (result != ERR_OK) { return result; } - - sptr bundleOption = GenerateBundleOption(); + bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; } + ANS_LOGI( + "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid()); + return ERR_OK; +} - std::shared_ptr record = std::make_shared(); +ErrCode AdvancedNotificationService::PublishPreparedNotification( + const sptr &request, const sptr &bundleOption) +{ + ANS_LOGI("PublishPreparedNotification"); + auto record = std::make_shared(); record->request = request; record->notification = new Notification(request); record->bundleOption = bundleOption; + SetNotificationRemindType(record->notification, true); + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { result = AssignValidNotificationSlot(record); if (result != ERR_OK) { @@ -264,28 +363,31 @@ ErrCode AdvancedNotificationService::Publish(const std::string &label, const spt return; } - if (!IsNotificationExists(record->notification->GetKey())) { - result = FlowControl(record); - if (result != ERR_OK) { - return; - } - } else { - if (record->request->IsAlertOneTime()) { - record->notification->SetEnableLight(false); - record->notification->SetEnableSound(false); - record->notification->SetEnableViration(false); - } - UpdateInNotificationList(record); + result = AssignToNotificationList(record); + if (result != ERR_OK) { + return; } - UpdateRecentNotification(record->notification, false, 0); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedPublish(bundleOption, record); +#endif })); - return result; } +ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + sptr bundleOption; + ErrCode result = PrepareNotificationInfo(request, bundleOption); + if (result != ERR_OK) { + return result; + } + return PublishPreparedNotification(request, bundleOption); +} + bool AdvancedNotificationService::IsNotificationExists(const std::string &key) { bool isExists = false; @@ -379,28 +481,8 @@ void AdvancedNotificationService::StopFilters() ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::string &label) { ANS_LOGD("%{public}s", __FUNCTION__); - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - - ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([&]() { - sptr notification = nullptr; - result = RemoveFromNotificationList(bundleOption, label, notificationId, notification, true); - if (result != ERR_OK) { - return; - } - - if (notification != nullptr) { - int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; - UpdateRecentNotification(notification, true, reason); - sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); - } - })); - return result; + return CancelPreparedNotification(notificationId, label, bundleOption); } ErrCode AdvancedNotificationService::CancelAll() @@ -419,6 +501,9 @@ ErrCode AdvancedNotificationService::CancelAll() std::vector keys = GetNotificationKeys(bundleOption); for (auto key : keys) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif result = RemoveFromNotificationList(key, notification, true); if (result != ERR_OK) { continue; @@ -429,6 +514,9 @@ ErrCode AdvancedNotificationService::CancelAll() UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } } @@ -445,6 +533,10 @@ ErrCode AdvancedNotificationService::AddSlots(const std::vector bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -502,8 +594,13 @@ ErrCode AdvancedNotificationService::GetSlots(std::vector } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption, slots); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundleOption, slots); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + slots.clear(); + } + })); return result; } @@ -519,6 +616,9 @@ ErrCode AdvancedNotificationService::GetSlotGroup(const std::string &groupId, sp ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationSlotGroup(bundleOption, groupId, group); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; + } })); return result; } @@ -533,8 +633,13 @@ ErrCode AdvancedNotificationService::GetSlotGroups(std::vectorPostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleOption, groups); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlotGroups(bundleOption, groups); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + groups.clear(); + } + })); return result; } @@ -548,6 +653,9 @@ ErrCode AdvancedNotificationService::RemoveSlotGroups(const std::vectorPostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlotGroups(bundleOption, groupIds); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_ID_INVALID; + } })); return result; } @@ -645,37 +753,6 @@ ErrCode AdvancedNotificationService::GetBundleImportance(int &importance) return result; } -ErrCode AdvancedNotificationService::SetDisturbMode(NotificationConstant::DisturbMode mode) -{ - ANS_LOGD("%{public}s", __FUNCTION__); - - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; - } - - ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([&]() { - result = NotificationPreferences::GetInstance().SetDisturbMode(mode); - if (result == ERR_OK) { - NotificationSubscriberManager::GetInstance()->NotifyDisturbModeChanged(mode); - } - })); - return result; -} - -ErrCode AdvancedNotificationService::GetDisturbMode(NotificationConstant::DisturbMode &mode) -{ - ANS_LOGD("%{public}s", __FUNCTION__); - - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; - } - - ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().GetDisturbMode(mode); })); - return result; -} - ErrCode AdvancedNotificationService::HasNotificationPolicyAccessPermission(bool &granted) { return ERR_OK; @@ -709,6 +786,10 @@ ErrCode AdvancedNotificationService::GetPrivateNotificationsAllowed(bool &allow) ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().GetPrivateNotificationsAllowed(bundleOption, allow); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + allow = false; + } })); return result; } @@ -721,10 +802,17 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif result = RemoveFromNotificationList(key, notification); if (result != ERR_OK) { return; @@ -735,6 +823,9 @@ ErrCode AdvancedNotificationService::Delete(const std::string &key) UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } })); @@ -749,6 +840,10 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -758,6 +853,9 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptrPostSyncTask(std::bind([&]() { std::vector keys = GetNotificationKeys(bundle); for (auto key : keys) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif sptr notification = nullptr; result = RemoveFromNotificationList(key, notification); @@ -770,6 +868,9 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } } @@ -787,22 +888,34 @@ ErrCode AdvancedNotificationService::DeleteAll() return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { + int activeUserId = SUBSCRIBE_USER_INIT; + (void)GetActiveUserId(activeUserId); std::vector keys = GetNotificationKeys(nullptr); for (auto key : keys) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId = GetNotificationDeviceId(key); +#endif sptr notification = nullptr; - result = RemoveFromNotificationList(key, notification); - if (result != ERR_OK) { + result = RemoveFromNotificationListForDeleteAll(key, notification); + if (result != ERR_OK || notification == nullptr) { continue; } - if (notification != nullptr) { + if ((notification->GetUserId() == activeUserId) || (notification->GetUserId() == SUBSCRIBE_USER_ALL)) { int reason = NotificationConstant::CANCEL_ALL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } } @@ -837,14 +950,23 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } ErrCode result = ERR_OK; - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationAllSlots(bundle, slots); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + slots.clear(); + } + })); return result; } @@ -857,14 +979,22 @@ ErrCode AdvancedNotificationService::UpdateSlots( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } ErrCode result = ERR_OK; - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().UpdateNotificationSlots(bundle, slots); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; + } + })); return result; } @@ -877,14 +1007,22 @@ ErrCode AdvancedNotificationService::UpdateSlotGroups( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().UpdateNotificationSlotGroups(bundle, groups); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; + } + })); return result; } @@ -902,6 +1040,10 @@ ErrCode AdvancedNotificationService::SetShowBadgeEnabledForBundle( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -922,14 +1064,23 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; } ErrCode result = ERR_OK; - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().IsShowBadge(bundle, enabled); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + enabled = false; + } + })); return result; } @@ -943,8 +1094,13 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabled(bool &enabled) } ErrCode result = ERR_OK; - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().IsShowBadge(bundleOption, enabled); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().IsShowBadge(bundleOption, enabled); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + enabled = false; + } + })); return result; } @@ -952,13 +1108,22 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { - if (((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && - (record->bundleOption->GetUid() == bundleOption->GetUid())) && - (record->notification->GetLabel() == label) && (record->notification->GetId() == notificationId)) { - if (!isCancel && record->request->IsUnremovable()) { - return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && + (record->notification->GetLabel() == label) && + (record->notification->GetId() == notificationId) +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + && record->deviceId.empty() +#endif + ) { + if (!isCancel && !record->notification->IsRemoveAllowed()) { + return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; + // delete or delete all, call the function + if (!isCancel) { + TriggerRemoveWantAgent(record->request); + } notificationList_.remove(record); return ERR_OK; } @@ -972,7 +1137,31 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( { for (auto record : notificationList_) { if (record->notification->GetKey() == key) { - if (!isCancel && record->request->IsUnremovable()) { + if (!isCancel && !record->notification->IsRemoveAllowed()) { + return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; + } + notification = record->notification; + // delete or delete all, call the function + if (!isCancel) { + TriggerRemoveWantAgent(record->request); + } + notificationList_.remove(record); + return ERR_OK; + } + } + + return ERR_ANS_NOTIFICATION_NOT_EXISTS; +} + +ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll( + const std::string &key, sptr ¬ification) +{ + for (auto record : notificationList_) { + if (record->notification->GetKey() == key) { + if (!record->notification->IsRemoveAllowed()) { + return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; + } + if (record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; } notification = record->notification; @@ -989,15 +1178,19 @@ ErrCode AdvancedNotificationService::Subscribe( { ANS_LOGD("%{public}s", __FUNCTION__); - if (subscriber == nullptr) { - return ERR_ANS_INVALID_PARAM; - } - if (!IsSystemApp()) { ANS_LOGE("Client is not a system app"); return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + if (subscriber == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + return NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info); } @@ -1006,13 +1199,17 @@ ErrCode AdvancedNotificationService::Unsubscribe( { ANS_LOGD("%{public}s", __FUNCTION__); - if (subscriber == nullptr) { + if (!IsSystemApp()) { ANS_LOGE("Client is not a system app"); - return ERR_ANS_INVALID_PARAM; + return ERR_ANS_NON_SYSTEM_APP; } - if (!IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + if (subscriber == nullptr) { + return ERR_ANS_INVALID_PARAM; } return NotificationSubscriberManager::GetInstance()->RemoveSubscriber(subscriber, info); @@ -1029,8 +1226,12 @@ ErrCode AdvancedNotificationService::GetSlotByType( } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationSlot(bundleOption, slotType, slot); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; + } + })); return result; } @@ -1044,8 +1245,12 @@ ErrCode AdvancedNotificationService::RemoveSlotByType(const NotificationConstant } ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleOption, slotType); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().RemoveNotificationSlot(bundleOption, slotType); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_TYPE_NOT_EXIST; + } + })); return result; } @@ -1057,11 +1262,20 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([&]() { notifications.clear(); for (auto record : notificationList_) { - notifications.push_back(record->notification); + if (record->notification != nullptr && record->notification->GetUserId() == userId) { + notifications.push_back(record->notification); + } } })); return result; @@ -1092,6 +1306,10 @@ ErrCode AdvancedNotificationService::GetSpecialActiveNotifications( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { for (auto record : notificationList_) { @@ -1111,11 +1329,20 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { if (deviceId.empty()) { // Local device - result = NotificationPreferences::GetInstance().SetNotificationsEnabled(enabled); + result = NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption, enabled); } else { // Remote device } @@ -1132,6 +1359,10 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForSpecialBundle( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1157,10 +1388,19 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { allowed = false; - result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption, allowed); })); return result; } @@ -1186,6 +1426,9 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( if (!IsSystemApp()) { return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } targetBundle = GenerateValidBundleOption(bundleOption); } } @@ -1197,9 +1440,13 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { allowed = false; - result = NotificationPreferences::GetInstance().GetNotificationsEnabled(allowed); + result = NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption, allowed); if (result == ERR_OK && allowed) { result = NotificationPreferences::GetInstance().GetNotificationsEnabledForBundle(targetBundle, allowed); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + allowed = true; + } } })); return result; @@ -1215,6 +1462,10 @@ ErrCode AdvancedNotificationService::ShellDump(const std::string &dumpOption, st result = ActiveNotificationDump(dumpInfo); } else if (dumpOption == RECENT_NOTIFICATION_OPTION) { result = RecentNotificationDump(dumpInfo); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + } else if (dumpOption == DISTRIBUTED_NOTIFICATION_OPTION) { + result = DistributedNotificationDump(dumpInfo); +#endif } else if (dumpOption.substr(0, dumpOption.find_first_of(" ", 0)) == SET_RECENT_COUNT_OPTION) { result = SetRecentNotificationCount(dumpOption.substr(dumpOption.find_first_of(" ", 0) + 1)); } else { @@ -1225,20 +1476,164 @@ ErrCode AdvancedNotificationService::ShellDump(const std::string &dumpOption, st return result; } -ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vector &dumpInfo) +ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); - std::stringstream stream; - for (auto record : notificationList_) { - stream.clear(); - stream << "\tBundleName: " << record->notification->GetBundleName() << "\n"; - stream << "\tCreateTime: " << TimeToString(record->notification->GetNotificationRequest().GetCreateTime()) - << "\n"; + int uid = IPCSkeleton::GetCallingUid(); + if (uid != SYSTEM_SERVICE_UID) { + return ERR_ANS_NOT_SYSTEM_SERVICE; + } - stream << "\tNotification:\n"; - stream << "\t\tId: " << record->notification->GetId() << "\n"; - stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; + if (request->GetCreatorBundleName().empty()) { + request->SetCreatorBundleName(FOUNDATION_BUNDLE_NAME); + } + + if (request->GetOwnerBundleName().empty()) { + request->SetOwnerBundleName(FOUNDATION_BUNDLE_NAME); + } + + sptr bundleOption = nullptr; + bundleOption = new NotificationBundleOption(std::string(), uid); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = PrepereContinuousTaskNotificationRequest(request, uid); + if (result != ERR_OK) { + return result; + } + request->SetUnremovable(true); + std::shared_ptr record = std::make_shared(); + record->request = request; + record->bundleOption = bundleOption; + record->notification = new Notification(request); + if (record->notification != nullptr) { + record->notification->SetSourceType(NotificationConstant::SourceType::TYPE_CONTINUOUS); + } + + handler_->PostSyncTask(std::bind([&]() { + if (!IsNotificationExists(record->notification->GetKey())) { + AddToNotificationList(record); + } else { + if (record->request->IsAlertOneTime()) { + record->notification->SetEnableLight(false); + record->notification->SetEnableSound(false); + record->notification->SetEnableViration(false); + } + UpdateInNotificationList(record); + } + + UpdateRecentNotification(record->notification, false, 0); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + })); + + return result; +} + +ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std::string &label, int32_t notificationId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + int uid = IPCSkeleton::GetCallingUid(); + if (uid != SYSTEM_SERVICE_UID) { + return ERR_ANS_NOT_SYSTEM_SERVICE; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + sptr notification = nullptr; + for (auto record : notificationList_) { + if ((record->bundleOption->GetBundleName().empty()) && (record->bundleOption->GetUid() == uid) && + (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) { + notification = record->notification; + notificationList_.remove(record); + result = ERR_OK; + break; + } + } + if (notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); + } + })); + return result; +} + +ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) +{ + ANSR_LOGI("Publish reminder"); + ReminderDataManager::GetInstance()->SetService(this); + sptr notificationRequest = reminder->GetNotificationRequest(); + sptr bundleOption = nullptr; + ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); + if (result != ERR_OK) { + ANSR_LOGW("PrepareNotificationInfo fail"); + return result; + } + ReminderDataManager::GetInstance()->PublishReminder(reminder, bundleOption); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) +{ + ANSR_LOGI("Cancel Reminder"); + ReminderDataManager::GetInstance()->SetService(this); + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ReminderDataManager::GetInstance()->CancelReminder(reminderId, bundleOption); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::CancelAllReminders() +{ + ANSR_LOGI("Cancel all reminders"); + ReminderDataManager::GetInstance()->SetService(this); + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ReminderDataManager::GetInstance()->CancelAllReminders(bundleOption); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) +{ + ANSR_LOGI("GetValidReminders"); + ReminderDataManager::GetInstance()->SetService(this); + reminders.clear(); + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ReminderDataManager::GetInstance()->GetValidReminders(bundleOption, reminders); + ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vector &dumpInfo) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::stringstream stream; + for (auto record : notificationList_) { +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + if (!record->deviceId.empty()) { + continue; + } +#endif + stream.clear(); + stream << "\tBundleName: " << record->notification->GetBundleName() << "\n"; + + stream << "\tCreateTime: " << TimeToString(record->notification->GetNotificationRequest().GetCreateTime()) + << "\n"; + + stream << "\tNotification:\n"; + stream << "\t\tId: " << record->notification->GetId() << "\n"; + stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; stream << "\t\tClassification: " << record->notification->GetNotificationRequest().GetClassification() << "\n"; dumpInfo.push_back(stream.str()); @@ -1274,6 +1669,34 @@ ErrCode AdvancedNotificationService::RecentNotificationDump(std::vector &dumpInfo) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + std::stringstream stream; + for (auto record : notificationList_) { + if (record->deviceId.empty()) { + continue; + } + stream.clear(); + stream << "\tDeviceId: " << record->deviceId << "\n"; + stream << "\tBundleName: " << record->notification->GetBundleName() << "\n"; + + stream << "\tCreateTime: " << TimeToString(record->notification->GetNotificationRequest().GetCreateTime()) + << "\n"; + + stream << "\tNotification:\n"; + stream << "\t\tId: " << record->notification->GetId() << "\n"; + stream << "\t\tLabel: " << record->notification->GetLabel() << "\n"; + stream << "\t\tClassification: " << record->notification->GetNotificationRequest().GetClassification() << "\n"; + + dumpInfo.push_back(stream.str()); + } + + return ERR_OK; +} +#endif + ErrCode AdvancedNotificationService::SetRecentNotificationCount(const std::string arg) { ANS_LOGD("%{public}s arg = %{public}s", __FUNCTION__, arg.c_str()); @@ -1403,19 +1826,62 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrPostTask(std::bind([&]() { + handler_->PostTask(std::bind([this, bundleOption]() { ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption); if (result != ERR_OK) { - ANS_LOGE("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result); + ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result); + } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedPreferences::GetInstance()->DeleteDistributedBundleInfo(bundleOption); + std::vector keys = GetLocalNotificationKeys(bundleOption); +#else + std::vector keys = GetNotificationKeys(bundleOption); +#endif + for (auto key : keys) { + sptr notification = nullptr; + result = RemoveFromNotificationList(key, notification, true); + if (result != ERR_OK) { + continue; + } + + if (notification != nullptr) { + int reason = NotificationConstant::PACKAGE_CHANGED_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete("", notification); +#endif + } } })); } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +void AdvancedNotificationService::OnScreenOn() +{ + ANS_LOGI("%{public}s", __FUNCTION__); + localScreenOn_ = true; + DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(true); +} + +void AdvancedNotificationService::OnScreenOff() +{ + ANS_LOGI("%{public}s", __FUNCTION__); + localScreenOn_ = false; + DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false); +} +#endif + void AdvancedNotificationService::OnDistributedKvStoreDeathRecipient() { ANS_LOGD("%{public}s", __FUNCTION__); - handler_->PostTask( - std::bind([&]() { NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); })); + handler_->PostTask(std::bind([&]() { + NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient(); +#endif + })); } ErrCode AdvancedNotificationService::RemoveAllSlots() @@ -1428,8 +1894,12 @@ ErrCode AdvancedNotificationService::RemoveAllSlots() } ErrCode result = ERR_OK; - handler_->PostSyncTask( - std::bind([&]() { result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundleOption); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().RemoveNotificationAllSlots(bundleOption); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + } + })); return result; } @@ -1467,6 +1937,10 @@ ErrCode AdvancedNotificationService::RemoveNotification( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1476,16 +1950,27 @@ ErrCode AdvancedNotificationService::RemoveNotification( handler_->PostSyncTask(std::bind([&]() { sptr notification = nullptr; + sptr notificationRequest = nullptr; +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::string deviceId; +#endif for (auto record : notificationList_) { if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid()) && +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + (record->deviceId.empty()) && +#endif (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) { - if (record->request->IsUnremovable()) { - result = ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + if (!record->notification->IsRemoveAllowed()) { + result = ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; break; } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + deviceId = record->deviceId; +#endif notification = record->notification; + notificationRequest = record->request; notificationList_.remove(record); result = ERR_OK; break; @@ -1497,7 +1982,12 @@ ErrCode AdvancedNotificationService::RemoveNotification( UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } + + TriggerRemoveWantAgent(notificationRequest); })); return result; @@ -1511,6 +2001,10 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1519,21 +2013,33 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptrPostSyncTask(std::bind([&]() { std::vector> removeList; for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && - (record->bundleOption->GetUid() == bundleOption->GetUid()) && !record->request->IsUnremovable()) { + (record->bundleOption->GetUid() == bundleOption->GetUid()) && +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + record->deviceId.empty() && +#endif + !record->request->IsUnremovable()) { removeList.push_back(record); } } for (auto record : removeList) { notificationList_.remove(record); - if (record->notification != nullptr) { int reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(record->deviceId, record->notification); +#endif } + + TriggerRemoveWantAgent(record->request); } })); @@ -1548,6 +2054,10 @@ ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1555,11 +2065,838 @@ ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const sptrPostSyncTask(std::bind( - [&]() { result = NotificationPreferences::GetInstance().GetNotificationSlotsNumForBundle(bundle, num); })); + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().GetNotificationSlotsNumForBundle(bundle, num); + if (result == ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST) { + result = ERR_OK; + num = 0; + } + })); return result; } +ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (groupName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + std::vector> removeList; + for (auto record : notificationList_) { + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + record->deviceId.empty() && +#endif + (record->request->GetGroupName() == groupName)) { + removeList.push_back(record); + } + } + + for (auto record : removeList) { + notificationList_.remove(record); + + if (record->notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; + UpdateRecentNotification(record->notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(record->deviceId, record->notification); +#endif + } + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + if (bundleOption == nullptr || groupName.empty()) { + return ERR_ANS_INVALID_PARAM; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + std::vector> removeList; + for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } + if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) && + (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() && +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + record->deviceId.empty() && +#endif + (record->request->GetGroupName() == groupName)) { + removeList.push_back(record); + } + } + + for (auto record : removeList) { + notificationList_.remove(record); + + if (record->notification != nullptr) { + int reason = NotificationConstant::CANCEL_REASON_DELETE; + UpdateRecentNotification(record->notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(record->deviceId, record->notification); +#endif + } + } + })); + + return ERR_OK; +} + +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) +{ + tm result = {0}; + tm *lt = localtime(&time); + if (lt != nullptr) { + result = *lt; + } + return result; +} + +void AdvancedNotificationService::AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + time_t nowT = std::chrono::system_clock::to_time_t(now); + tm nowTm = GetLocalTime(nowT); + + auto beginDateMilliseconds = std::chrono::milliseconds(beginDate); + auto beginDateTimePoint = + std::chrono::time_point(beginDateMilliseconds); + time_t beginDateT = std::chrono::system_clock::to_time_t(beginDateTimePoint); + tm beginDateTm = GetLocalTime(beginDateT); + + auto endDateMilliseconds = std::chrono::milliseconds(endDate); + auto endDateTimePoint = + std::chrono::time_point(endDateMilliseconds); + time_t endDateT = std::chrono::system_clock::to_time_t(endDateTimePoint); + tm endDateTm = GetLocalTime(endDateT); + + tm todayBeginTm = nowTm; + todayBeginTm.tm_sec = 0; + todayBeginTm.tm_min = beginDateTm.tm_min; + todayBeginTm.tm_hour = beginDateTm.tm_hour; + + tm todayEndTm = nowTm; + todayEndTm.tm_sec = 0; + todayEndTm.tm_min = endDateTm.tm_min; + todayEndTm.tm_hour = endDateTm.tm_hour; + + time_t todayBeginT = mktime(&todayBeginTm); + if (todayBeginT == -1) { + return; + } + time_t todayEndT = mktime(&todayEndTm); + if (todayEndT == -1) { + return; + } + + auto newBeginTimePoint = std::chrono::system_clock::from_time_t(todayBeginT); + auto newEndTimePoint = std::chrono::system_clock::from_time_t(todayEndT); + + if (newBeginTimePoint >= newEndTimePoint) { + newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY); + } + + if (newEndTimePoint < now) { + newBeginTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY); + newEndTimePoint += std::chrono::hours(HOURS_IN_ONE_DAY); + } + + auto newBeginDuration = std::chrono::duration_cast(newBeginTimePoint.time_since_epoch()); + beginDate = newBeginDuration.count(); + + auto newEndDuration = std::chrono::duration_cast(newEndTimePoint.time_since_epoch()); + endDate = newEndDuration.count(); +} + +ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr &date) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + if (date == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + + int64_t beginDate = ResetSeconds(date->GetBeginDate()); + int64_t endDate = ResetSeconds(date->GetEndDate()); + + switch (date->GetDoNotDisturbType()) { + case NotificationConstant::DoNotDisturbType::NONE: + beginDate = 0; + endDate = 0; + break; + case NotificationConstant::DoNotDisturbType::ONCE: + AdjustDateForDndTypeOnce(beginDate, endDate); + break; + case NotificationConstant::DoNotDisturbType::CLEARLY: + if (beginDate >= endDate) { + return ERR_ANS_INVALID_PARAM; + } + break; + default: + break; + } + + const sptr newConfig = new NotificationDoNotDisturbDate( + date->GetDoNotDisturbType(), + beginDate, + endDate + ); + + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, newConfig); + if (result == ERR_OK) { + NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig); + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr &date) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + handler_->PostSyncTask(std::bind([&]() { + sptr currentConfig = nullptr; + result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption, currentConfig); + if (result == ERR_OK) { + int64_t now = GetCurrentTime(); + switch (currentConfig->GetDoNotDisturbType()) { + case NotificationConstant::DoNotDisturbType::CLEARLY: + case NotificationConstant::DoNotDisturbType::ONCE: + if (now >= currentConfig->GetEndDate()) { + date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, date); + } else { + date = currentConfig; + } + break; + default: + date = currentConfig; + break; + } + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + doesSupport = SUPPORT_DO_NOT_DISTRUB; + return ERR_OK; +} + +bool AdvancedNotificationService::CheckPermission(const std::string &bundleName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + if (IPCSkeleton::GetCallingUid() == SYSTEM_SERVICE_UID) { + return true; + } + if (bundleName.empty()) { + ANS_LOGE("Bundle name is empty."); + return false; + } + // Add permission check in future + return true; +} + +ErrCode AdvancedNotificationService::IsDistributedEnabled(bool &enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = DistributedPreferences::GetInstance()->GetDistributedEnable(enabled); + if (result != ERR_OK) { + result = ERR_OK; + enabled = false; + } + })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::EnableDistributed(bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask( + std::bind([&]() { result = DistributedPreferences::GetInstance()->SetDistributedEnable(enabled); })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::EnableDistributedByBundle( + const sptr &bundleOption, bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + bool appInfoEnable = true; + GetDistributedEnableInApplicationInfo(bundle, appInfoEnable); + if (!appInfoEnable) { + ANS_LOGD("Get from bms is %{public}d", appInfoEnable); + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundle, enabled); + if (result != ERR_OK) { + result = ERR_OK; + enabled = false; + } + })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::EnableDistributedSelf(const bool enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + bool appInfoEnable = true; + GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable); + if (!appInfoEnable) { + ANS_LOGD("Get from bms is %{public}d", appInfoEnable); + return ERR_ANS_PERMISSION_DENIED; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind( + [&]() { result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, enabled); })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::IsDistributedEnableByBundle( + const sptr &bundleOption, bool &enabled) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + bool appInfoEnable = true; + GetDistributedEnableInApplicationInfo(bundle, appInfoEnable); + if (!appInfoEnable) { + ANS_LOGD("Get from bms is %{public}d", appInfoEnable); + enabled = appInfoEnable; + return ERR_OK; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundle, enabled); + if (result != ERR_OK) { + result = ERR_OK; + enabled = false; + } + })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::GetDeviceRemindType(NotificationConstant::RemindType &remindType) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (!IsSystemApp()) { + return ERR_ANS_NON_SYSTEM_APP; + } + + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + handler_->PostSyncTask(std::bind([&]() { remindType = GetRemindType(); })); + return ERR_OK; +#else + return ERR_INVALID_OPERATION; +#endif +} + +ErrCode AdvancedNotificationService::SetNotificationRemindType(sptr notification, bool isLocal) +{ +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + notification->SetRemindType(GetRemindType()); +#else + notification->SetRemindType(NotificationConstant::RemindType::NONE); +#endif + return ERR_OK; +} + +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +std::vector AdvancedNotificationService::GetLocalNotificationKeys( + const sptr &bundleOption) +{ + std::vector keys; + + for (auto record : notificationList_) { + if ((bundleOption != nullptr) && (record->bundleOption->GetBundleName() != bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() != bundleOption->GetUid()) && record->deviceId.empty()) { + continue; + } + keys.push_back(record->notification->GetKey()); + } + + return keys; +} + +NotificationConstant::RemindType AdvancedNotificationService::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; + } + } +} + +std::string AdvancedNotificationService::GetNotificationDeviceId(const std::string &key) +{ + for (auto record : notificationList_) { + if (record->notification->GetKey() == key) { + return record->deviceId; + } + } + return std::string(); +} + +ErrCode AdvancedNotificationService::DoDistributedPublish( + const sptr bundleOption, const std::shared_ptr record) +{ + bool appInfoEnable = true; + GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable); + if (!appInfoEnable) { + return ERR_OK; + } + + if (!record->request->GetNotificationDistributedOptions().IsDistributed()) { + return ERR_OK; + } + + ErrCode result; + bool distributedEnable = false; + result = DistributedPreferences::GetInstance()->GetDistributedEnable(distributedEnable); + if (result != ERR_OK || !distributedEnable) { + return result; + } + + bool bundleDistributedEnable = false; + result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, bundleDistributedEnable); + if (result != ERR_OK || !bundleDistributedEnable) { + return result; + } + + return DistributedNotificationManager::GetInstance()->Publish(record->notification->GetBundleName(), + record->notification->GetLabel(), + record->notification->GetId(), + record->request); +} + +ErrCode AdvancedNotificationService::DoDistributedDelete( + const std::string deviceId, const sptr notification) +{ + if (!notification->GetNotificationRequest().GetNotificationDistributedOptions().IsDistributed()) { + return ERR_OK; + } + if (deviceId.empty()) { + return DistributedNotificationManager::GetInstance()->Delete( + notification->GetBundleName(), notification->GetLabel(), notification->GetId()); + } else { + return DistributedNotificationManager::GetInstance()->DeleteRemoteNotification( + deviceId, notification->GetBundleName(), notification->GetLabel(), notification->GetId()); + } + + return ERR_OK; +} + +inline bool CheckDistributedNotificationType(const sptr &request) +{ + DistributedDatabase::DeviceInfo localDeviceInfo; + DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo); + auto deviceTypeList = request->GetNotificationDistributedOptions().GetDevicesSupportDisplay(); + for (auto device : deviceTypeList) { + if (device == localDeviceInfo.deviceType) { + return true; + } + } + return false; +} + +void AdvancedNotificationService::OnDistributedPublish( + const std::string &deviceId, const std::string &bundleName, sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName)); + + handler_->PostTask(std::bind([this, deviceId, bundleName, request]() { + if (!CheckDistributedNotificationType(request)) { + ANS_LOGD("device type not support display."); + return; + } + + sptr bundleOption = + GenerateValidBundleOption(new NotificationBundleOption(bundleName, 0)); + if (bundleOption == nullptr) { + return; + } + std::shared_ptr record = std::make_shared(); + if (record == nullptr) { + return; + } + record->request = request; + record->notification = new Notification(deviceId, request); + record->bundleOption = bundleOption; + record->deviceId = deviceId; + SetNotificationRemindType(record->notification, false); + + ErrCode result = AssignValidNotificationSlot(record); + if (result != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); + return; + } + + result = Filter(record); + if (result != ERR_OK) { + ANS_LOGE("Reject by filters: %{public}d", result); + return; + } + + result = FlowControl(record); + if (result != ERR_OK) { + return; + } + + UpdateRecentNotification(record->notification, false, 0); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + })); +} + +void AdvancedNotificationService::OnDistributedUpdate( + const std::string &deviceId, const std::string &bundleName, sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + request->SetCreatorUid(BundleManagerHelper::GetInstance()->GetDefaultUidByBundleName(bundleName)); + + handler_->PostTask(std::bind([this, deviceId, bundleName, request]() { + if (!CheckDistributedNotificationType(request)) { + ANS_LOGD("device type not support display."); + return; + } + sptr bundleOption = + GenerateValidBundleOption(new NotificationBundleOption(bundleName, 0)); + if (bundleOption == nullptr) { + return; + } + std::shared_ptr record = std::make_shared(); + if (record == nullptr) { + return; + } + record->request = request; + record->notification = new Notification(deviceId, request); + record->bundleOption = bundleOption; + record->deviceId = deviceId; + SetNotificationRemindType(record->notification, false); + + ErrCode result = AssignValidNotificationSlot(record); + if (result != ERR_OK) { + ANS_LOGE("Can not assign valid slot!"); + return; + } + + result = Filter(record); + if (result != ERR_OK) { + ANS_LOGE("Reject by filters: %{public}d", result); + return; + } + + if (IsNotificationExists(record->notification->GetKey())) { + if (record->request->IsAlertOneTime()) { + record->notification->SetEnableLight(false); + record->notification->SetEnableSound(false); + record->notification->SetEnableViration(false); + } + UpdateInNotificationList(record); + } + + UpdateRecentNotification(record->notification, false, 0); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + })); +} + +void AdvancedNotificationService::OnDistributedDelete( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask(std::bind([this, deviceId, bundleName, label, id]() { + sptr bundleOption = + GenerateValidBundleOption(new NotificationBundleOption(bundleName, 0)); + if (bundleOption == nullptr) { + return; + } + + std::string recordDeviceId; + DistributedDatabase::DeviceInfo localDeviceInfo; + if (DistributedNotificationManager::GetInstance()->GetLocalDeviceInfo(localDeviceInfo) == ERR_OK && + deviceId == localDeviceInfo.deviceId) { + recordDeviceId = ""; + } else { + recordDeviceId = deviceId; + } + + sptr notification = nullptr; + for (auto record : notificationList_) { + if ((record->deviceId == recordDeviceId) && + (record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && + (record->notification->GetLabel() == label) && (record->notification->GetId() == id)) { + notification = record->notification; + notificationList_.remove(record); + break; + } + } + + if (notification != nullptr) { + int reason = NotificationConstant::APP_CANCEL_REASON_OTHER; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); + } + })); +} + +ErrCode AdvancedNotificationService::GetDistributedEnableInApplicationInfo( + const sptr bundleOption, bool &enable) +{ + int userId = SUBSCRIBE_USER_INIT; + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(bundleOption->GetUid(), userId); + + if (userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && userId <= SUBSCRIBE_USER_SYSTEM_END) { + enable = true; + } else { + enable = BundleManagerHelper::GetInstance()->GetDistributedNotificationEnabled( + bundleOption->GetBundleName(), userId); + } + + return ERR_OK; +} +#endif + +ErrCode AdvancedNotificationService::PrepereContinuousTaskNotificationRequest( + const sptr &request, const int &uid) +{ + int pid = IPCSkeleton::GetCallingPid(); + request->SetCreatorUid(uid); + request->SetCreatorPid(pid); + + ErrCode result = CheckPictureSize(request); + return result; +} + +ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templateName, bool &support) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + support = false; + result = NotificationPreferences::GetInstance().GetTemplateSupported(templateName, support); + })); + return result; +} + +bool AdvancedNotificationService::GetActiveUserId(int& userId) +{ + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + if (iter.GetIsActived()) { + userId = iter.GetLocalId(); + return true; + } + } + return false; +} + +void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + if (request == nullptr || request->GetRemovalWantAgent() == nullptr) { + return; + } + OHOS::Notification::WantAgent::TriggerInfo triggerInfo; + std::shared_ptr agent = request->GetRemovalWantAgent(); + WantAgent::WantAgentHelper::TriggerWantAgent(agent, nullptr, triggerInfo); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index f361f3d16dd85ace767b35d953c3838444d5afe4..56f052fb8b4cf0c10e32d58b47c6ebed42223f8d 100644 --- a/services/ans/src/advanced_notification_service_ability.cpp +++ b/services/ans/src/advanced_notification_service_ability.cpp @@ -17,7 +17,6 @@ namespace OHOS { namespace Notification { - namespace { REGISTER_SYSTEM_ABILITY_BY_ID(AdvancedNotificationServiceAbility, ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID, true); } @@ -45,6 +44,5 @@ void AdvancedNotificationServiceAbility::OnStop() { service_ = nullptr; } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index a02c7f20a7cf1b6ad36e34733a4db79c67b03f0d..ff21b58a708791ac97703f58bbf1fc0fa2dbfdab 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -19,9 +19,11 @@ #include "iservice_registry.h" #include "system_ability_definition.h" +#include "ans_const_define.h" +#include "ans_log_wrapper.h" + namespace OHOS { namespace Notification { - BundleManagerHelper::BundleManagerHelper() { deathRecipient_ = @@ -101,7 +103,7 @@ void BundleManagerHelper::Disconnect() } } -int BundleManagerHelper::GetDefaultUidByBundleName(const std::string& bundle) +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle) { int uid = -1; @@ -119,5 +121,25 @@ int BundleManagerHelper::GetDefaultUidByBundleName(const std::string& bundle) return uid; } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) +{ + std::lock_guard lock(connectionMutex_); + + Connect(); + + if (bundleMgr_ != nullptr) { + AppExecFwk::ApplicationInfo appInfo; + if (bundleMgr_->GetApplicationInfo( + bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, userId, appInfo)) { + ANS_LOGD("APPLICATION_INFO distributed enabled %{public}d", appInfo.distributedNotificationEnabled); + return appInfo.distributedNotificationEnabled; + } + } + + ANS_LOGD("APPLICATION_INFO distributed enabled is default"); + return DEFAULT_DISTRIBUTED_ENABLE_IN_APPLICATION_INFO; +} +#endif } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp deleted file mode 100644 index d5ebca7ba27ab60c321eff48361fc5e415368a24..0000000000000000000000000000000000000000 --- a/services/ans/src/disturb_filter.cpp +++ /dev/null @@ -1,81 +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 "disturb_filter.h" - -#include "ans_inner_errors.h" -#include "notification_preferences.h" - -namespace OHOS { -namespace Notification { - -void DisturbFilter::OnStart() -{} - -void DisturbFilter::OnStop() -{} - -ErrCode DisturbFilter::OnPublish(const std::shared_ptr &record) -{ - NotificationConstant::DisturbMode mode; - ErrCode result = NotificationPreferences::GetInstance().GetDisturbMode(mode); - if (result != ERR_OK) { - return result; - } - - bool disturb = false; - - switch (mode) { - case NotificationConstant::DisturbMode::ALLOW_ALARMS: - if (record->request->GetClassification() == NotificationRequest::CLASSIFICATION_ALARM) { - disturb = true; - } else { - if (record->slot == nullptr) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; - break; - } - disturb = record->slot->IsEnableBypassDnd(); - } - break; - case NotificationConstant::DisturbMode::ALLOW_ALL: - disturb = true; - break; - case NotificationConstant::DisturbMode::ALLOW_NONE: - if (record->slot == nullptr) { - result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOT_NOT_EXIST; - break; - } - disturb = record->slot->IsEnableBypassDnd(); - break; - case NotificationConstant::DisturbMode::ALLOW_PRIORITY: - break; - case NotificationConstant::DisturbMode::ALLOW_UNKNOWN: - // DO NOTHING - break; - default: - break; - } - - if (!disturb) { - record->notification->SetEnableLight(false); - record->notification->SetEnableSound(false); - record->notification->SetEnableViration(false); - } - - return result; -} - -} // namespace Notification -} // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index dc3ebcb9b7e32ff62def86d7468aab6312d15eff..4dd6b400855747c82bd40459731103674ecf162c 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -15,13 +15,16 @@ #include "notification_preferences.h" +#include + #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "nlohmann/json.hpp" +#include "os_account_manager.h" namespace OHOS { namespace Notification { - NotificationPreferences::NotificationPreferences() { preferncesDB_ = std::make_unique(); @@ -39,7 +42,6 @@ NotificationPreferences &NotificationPreferences::GetInstance() ErrCode NotificationPreferences::AddNotificationSlots( const sptr &bundleOption, const std::vector> &slots) { - ANS_LOGD("%{public}s", __FUNCTION__); if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || slots.empty()) { return ERR_ANS_INVALID_PARAM; @@ -53,7 +55,8 @@ ErrCode NotificationPreferences::AddNotificationSlots( } } - if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(GenerateBundleKey(bundleOption), slots))) { + if (result == ERR_OK && + (!preferncesDB_->PutSlotsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), slots))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -80,7 +83,8 @@ ErrCode NotificationPreferences::AddNotificationSlotGroups( } } - if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(GenerateBundleKey(bundleOption), groups))) { + if (result == ERR_OK && + (!preferncesDB_->PutGroupsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), groups))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -119,7 +123,6 @@ ErrCode NotificationPreferences::RemoveNotificationSlot( NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = ERR_OK; result = CheckSlotForRemoveSlot(bundleOption, slotType, preferencesInfo); - if (result == ERR_OK && (!preferncesDB_->RemoveSlotFromDisturbeDB(GenerateBundleKey(bundleOption), slotType))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -223,7 +226,8 @@ ErrCode NotificationPreferences::UpdateNotificationSlots( } } - if (result == ERR_OK && (!preferncesDB_->PutSlotsToDisturbeDB(GenerateBundleKey(bundleOption), slots))) { + if (result == ERR_OK && + (!preferncesDB_->PutSlotsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), slots))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -237,7 +241,6 @@ ErrCode NotificationPreferences::UpdateNotificationSlots( ErrCode NotificationPreferences::UpdateNotificationSlotGroups( const sptr &bundleOption, const std::vector> &groups) { - ANS_LOGD("%{public}s", __FUNCTION__); if (bundleOption == nullptr || bundleOption->GetBundleName().empty() || groups.empty()) { return ERR_ANS_INVALID_PARAM; @@ -252,7 +255,8 @@ ErrCode NotificationPreferences::UpdateNotificationSlotGroups( } } - if (result == ERR_OK && (!preferncesDB_->PutGroupsToDisturbeDB(GenerateBundleKey(bundleOption), groups))) { + if (result == ERR_OK && + (!preferncesDB_->PutGroupsToDisturbeDB(bundleOption->GetBundleName(), bundleOption->GetUid(), groups))) { return ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -295,7 +299,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlots( if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.GetAllSlots(slots); } else { - ANS_LOGE("Notification bundle does not exsit."); + ANS_LOGW("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } @@ -333,7 +337,7 @@ ErrCode NotificationPreferences::GetNotificationSlotGroup( result = ERR_ANS_PREFERENCES_NOTIFICATION_SLOTGROUP_NOT_EXIST; } } else { - ANS_LOGE("Notification bundle does not exsit."); + ANS_LOGW("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; @@ -351,7 +355,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlotGroups( if (preferencesInfo_.GetBundleInfo(bundleOption, bundleInfo)) { bundleInfo.GetAllGroups(groups); } else { - ANS_LOGE("Notification bundle does not exsit."); + ANS_LOGW("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; @@ -369,7 +373,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup(const sptr osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + if (iter.GetIsActived()) { + userId = iter.GetLocalId(); + return true; + } + } + return false; } -ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) +ErrCode NotificationPreferences::GetNotificationsEnabled( + const sptr &bundleOption, bool &enabled) { + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + int userId = SUBSCRIBE_USER_INIT; + (void)GetActiveUserId(userId); + + ErrCode result = ERR_OK; + if (!preferencesInfo_.GetEnabledAllNotification(userId, enabled)) { + result = ERR_ANS_INVALID_PARAM; + } + return result; +} + +ErrCode NotificationPreferences::SetNotificationsEnabled( + const sptr &bundleOption, const bool &enabled) +{ + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + int userId = SUBSCRIBE_USER_INIT; + (void)GetActiveUserId(userId); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - preferencesInfo.SetEnabledAllNotification(enabled); + preferencesInfo.SetEnabledAllNotification(userId, enabled); ErrCode result = ERR_OK; - if (!preferncesDB_->PutNotificationsEnabled(enabled)) { + if (!preferncesDB_->PutNotificationsEnabled(userId, enabled)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -512,18 +548,39 @@ ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) return result; } -ErrCode NotificationPreferences::GetDisturbMode(NotificationConstant::DisturbMode &mode) +ErrCode NotificationPreferences::GetDoNotDisturbDate( + const sptr &bundleOption, sptr &date) { - mode = preferencesInfo_.GetDisturbMode(); - return ERR_OK; + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + int userId = SUBSCRIBE_USER_INIT; + (void)GetActiveUserId(userId); + + ErrCode result = ERR_OK; + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; + if (!preferencesInfo.GetDoNotDisturbDate(userId, date)) { + result = ERR_ANS_INVALID_PARAM; + } + return result; } -ErrCode NotificationPreferences::SetDisturbMode(const NotificationConstant::DisturbMode &mode) +ErrCode NotificationPreferences::SetDoNotDisturbDate( + const sptr &bundleOption, const sptr date) { + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + int userId = SUBSCRIBE_USER_INIT; + (void)GetActiveUserId(userId); + NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - preferencesInfo.SetDisturbMode(mode); + preferencesInfo.SetDoNotDisturbDate(userId, date); + ErrCode result = ERR_OK; - if (!preferncesDB_->PutDisturbMode(mode)) { + if (!preferncesDB_->PutDoNotDisturbDate(userId, date)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -608,7 +665,7 @@ ErrCode NotificationPreferences::CheckSlotForRemoveSlot(const sptrPutImportance(bundleOption->GetBundleName(), value); + storeDBResult = preferncesDB_->PutImportance(bundleInfo, value); break; case BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE: bundleInfo.SetBadgeTotalNum(value); - storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleOption->GetBundleName(), value); + storeDBResult = preferncesDB_->PutTotalBadgeNums(bundleInfo, value); break; case BundleType::BUNDLE_SHOW_BADGE_TYPE: bundleInfo.SetIsShowBadge(value); - storeDBResult = preferncesDB_->PutShowBadge(bundleOption->GetBundleName(), value); + storeDBResult = preferncesDB_->PutShowBadge(bundleInfo, value); break; case BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE: bundleInfo.SetIsPrivateAllowed(value); - storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleOption->GetBundleName(), value); + storeDBResult = preferncesDB_->PutPrivateNotificationsAllowed(bundleInfo, value); break; case BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE: bundleInfo.SetEnableNotification(value); - storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleOption->GetBundleName(), value); + storeDBResult = preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, value); break; default: break; @@ -760,7 +817,7 @@ ErrCode NotificationPreferences::GetBundleProperty( break; } } else { - ANS_LOGE("Notification bundle does not exsit."); + ANS_LOGW("Notification bundle does not exsit."); result = ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST; } return result; @@ -779,5 +836,35 @@ void NotificationPreferences::OnDistributedKvStoreDeathRecipient() } } +ErrCode NotificationPreferences::GetTemplateSupported(const std::string& templateName, bool &support) +{ + if (templateName.length() == 0) { + ANS_LOGE("template name is null."); + return ERR_ANS_INVALID_PARAM; + } + + std::ifstream inFile; + inFile.open(DEFAULT_TEMPLATE_PATH.c_str(), std::ios::in); + if (!inFile.is_open()) { + ANS_LOGE("read template config error."); + return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED; + } + + nlohmann::json jsonObj; + inFile >> jsonObj; + if (jsonObj.is_discarded()) { + ANS_LOGE("template json discarded error."); + inFile.close(); + return ERR_ANS_PREFERENCES_NOTIFICATION_READ_TEMPLATE_CONFIG_FAILED; + } + + if (jsonObj.contains(templateName)) { + support = true; + } + + jsonObj.clear(); + inFile.close(); + return ERR_OK; +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index d9e16a85fef4f2eeeafe0a5f4a49e2f5c8e13dd6..966e69a71df7ae695dfc6e972522edebabc6e7b8 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -14,16 +14,13 @@ */ #include "notification_preferences_database.h" -#include -#include -#include - +#include "ans_const_define.h" #include "ans_log_wrapper.h" +#include "os_account_manager.h" #include "uri.h" namespace OHOS { namespace Notification { - const std::map &, std::string &)>> NotificationPreferencesDatabase::slotMap_ = { @@ -78,7 +75,7 @@ const std::map - singleKvStore) { - status = paramStatus; - if (status != OHOS::DistributedKv::Status::SUCCESS) { - ANS_LOGE("Return error: %{public}d.", status); - return; - } - { - kvStorePtr_ = std::move(singleKvStore); - } - ANS_LOGD("Get kvStore success."); - }); + auto status = dataManager_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); + if (status != OHOS::DistributedKv::Status::SUCCESS) { + ANS_LOGE("Return error: %{public}d.", status); + } else { + ANS_LOGD("Get kvStore success."); + } return status; } void NotificationPreferencesDatabase::CloseKvStore() { - dataManager_.CloseKvStore(appId_, std::move(kvStorePtr_)); + dataManager_.CloseKvStore(appId_, kvStorePtr_); } bool NotificationPreferencesDatabase::CheckKvStore() @@ -181,10 +172,10 @@ bool NotificationPreferencesDatabase::CheckKvStore() } bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( - const std::string &bundleKey, const std::vector> &slots) + const std::string &bundleName, const int &bundleUid, const std::vector> &slots) { ANS_LOGD("%{public}s", __FUNCTION__); - if (bundleKey.empty()) { + if (bundleName.empty()) { ANS_LOGE("Bundle name is null."); return false; } @@ -197,7 +188,7 @@ bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( bool result = true; std::vector entries; for (auto iter : slots) { - result = SlotToEntry(bundleKey, iter, entries); + result = SlotToEntry(bundleName, bundleUid, iter, entries); if (!result) { return result; } @@ -212,9 +203,9 @@ bool NotificationPreferencesDatabase::PutSlotsToDisturbeDB( } bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( - const std::string &bundleKey, const std::vector> &groups) + const std::string &bundleName, const int &bundleUid, const std::vector> &groups) { - if (bundleKey.empty()) { + if (bundleName.empty()) { ANS_LOGE("Bundle name is null."); return false; } @@ -227,7 +218,7 @@ bool NotificationPreferencesDatabase::PutGroupsToDisturbeDB( bool result = true; std::vector entries; for (auto iter : groups) { - result = GroupToEntry(bundleKey, iter, entries); + result = GroupToEntry(bundleName, bundleUid, iter, entries); if (!result) { return result; } @@ -254,12 +245,12 @@ bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( return false; } - std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleInfo.GetBundleName(); + std::string bundleKeyStr = KEY_BUNDLE_LABEL + GenerateBundleLablel(bundleInfo); bool result = false; GetValueFromDisturbeDB(bundleKeyStr, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { switch (status) { case OHOS::DistributedKv::Status::KEY_NOT_FOUND: { - result = PutBundleToDisturbeDB(bundleInfo.GetBundleName(), bundleInfo); + result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo); break; } case OHOS::DistributedKv::Status::SUCCESS: { @@ -273,62 +264,71 @@ bool NotificationPreferencesDatabase::PutBundlePropertyToDisturbeDB( return result; } -bool NotificationPreferencesDatabase::PutShowBadge(const std::string &bundleKey, const bool &enable) +bool NotificationPreferencesDatabase::PutShowBadge( + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enable) { - if (bundleKey.empty()) { + if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) { return false; } + + std::string bundleKey = GenerateBundleLablel(bundleInfo); OHOS::DistributedKv::Status status = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_SHOW_BADGE_TYPE, enable); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutImportance(const std::string &bundleKey, const int &importance) +bool NotificationPreferencesDatabase::PutImportance( + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &importance) { - if (bundleKey.empty()) { + if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) { return false; } + + std::string bundleKey = GenerateBundleLablel(bundleInfo); OHOS::DistributedKv::Status status = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_IMPORTANCE_TYPE, importance); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutTotalBadgeNums(const std::string &bundleKey, const int &totalBadgeNum) +bool NotificationPreferencesDatabase::PutTotalBadgeNums( + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const int &totalBadgeNum) { - if (bundleKey.empty()) { + if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) { return false; } - + std::string bundleKey = GenerateBundleLablel(bundleInfo); OHOS::DistributedKv::Status status = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_BADGE_TOTAL_NUM_TYPE, totalBadgeNum); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std::string &bundleKey, const bool &allow) +bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed( + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &allow) { - if (bundleKey.empty()) { + if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) { return false; } + std::string bundleKey = GenerateBundleLablel(bundleInfo); OHOS::DistributedKv::Status status = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_PRIVATE_ALLOWED_TYPE, allow); @@ -336,30 +336,33 @@ bool NotificationPreferencesDatabase::PutPrivateNotificationsAllowed(const std:: } bool NotificationPreferencesDatabase::PutNotificationsEnabledForBundle( - const std::string &bundleKey, const bool &enabled) + const NotificationPreferencesInfo::BundleInfo &bundleInfo, const bool &enabled) { - if (bundleKey.empty()) { + if (bundleInfo.GetBundleName().empty()) { ANS_LOGE("Bundle name is null."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleInfo.GetBundleName(), bundleInfo.GetBundleUid())) { return false; } + std::string bundleKey = GenerateBundleLablel(bundleInfo); OHOS::DistributedKv::Status status = PutBundlePropertyToDisturbeDB(bundleKey, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); return (status == OHOS::DistributedKv::Status::SUCCESS); } -bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enabled) +bool NotificationPreferencesDatabase::PutNotificationsEnabled(const int32_t &userId, const bool &enabled) { if (!CheckKvStore()) { ANS_LOGE("KvStore is nullptr."); return false; } - OHOS::DistributedKv::Key enableKey(KEY_ENABLE_ALL_NOTIFICATION); + std::string typeKey = + std::string().append(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId)); + OHOS::DistributedKv::Key enableKey(typeKey); OHOS::DistributedKv::Value enableValue(std::to_string(enabled)); OHOS::DistributedKv::Status status; status = kvStorePtr_->Put(enableKey, enableValue); @@ -370,21 +373,49 @@ bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enable return true; } -bool NotificationPreferencesDatabase::PutDisturbMode(const NotificationConstant::DisturbMode &mode) +bool NotificationPreferencesDatabase::PutDoNotDisturbDate( + const int32_t &userId, const sptr &date) { + if (date == nullptr) { + ANS_LOGE("Invalid date."); + return false; + } + if (!CheckKvStore()) { ANS_LOGE("KvStore is nullptr."); return false; } - OHOS::DistributedKv::Key disturbModeKey(KEY_DISTURB_MODE); - OHOS::DistributedKv::Value disturbModeValue(std::to_string(mode)); - OHOS::DistributedKv::Status status; - status = kvStorePtr_->Put(disturbModeKey, disturbModeValue); + OHOS::DistributedKv::Entry type; + std::string typeKey = + std::string().append(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + type.key = OHOS::DistributedKv::Key(typeKey); + type.value = OHOS::DistributedKv::Value(std::to_string((int)date->GetDoNotDisturbType())); + + OHOS::DistributedKv::Entry beginDate; + std::string beginDateKey = + std::string().append(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + beginDate.key = OHOS::DistributedKv::Key(beginDateKey); + beginDate.value = OHOS::DistributedKv::Value(std::to_string(date->GetBeginDate())); + + OHOS::DistributedKv::Entry endDate; + std::string endDateKey = + std::string().append(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + endDate.key = OHOS::DistributedKv::Key(endDateKey); + endDate.value = OHOS::DistributedKv::Value(std::to_string(date->GetEndDate())); + + std::vector entries = { + type, + beginDate, + endDate, + }; + + OHOS::DistributedKv::Status status = kvStorePtr_->PutBatch(entries); if (status != OHOS::DistributedKv::Status::SUCCESS) { - ANS_LOGE("Store disturbe modeFailed. %{public}d", status); + ANS_LOGE("Store DoNotDisturbDate failed. %{public}d", status); return false; } + return true; } @@ -427,16 +458,18 @@ void NotificationPreferencesDatabase::GetValueFromDisturbeDB( funcion(status, value); } -bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleKey) +bool NotificationPreferencesDatabase::CheckBundle(const std::string &bundleName, const int &bundleUid) { - std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleKey; + std::string bundleKeyStr = KEY_BUNDLE_LABEL + bundleName + std::to_string(bundleUid); + ANS_LOGD("CheckBundle bundleKeyStr %{public}s", bundleKeyStr.c_str()); bool result = true; GetValueFromDisturbeDB(bundleKeyStr, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { switch (status) { case OHOS::DistributedKv::Status::KEY_NOT_FOUND: { NotificationPreferencesInfo::BundleInfo bundleInfo; - bundleInfo.SetBundleName(bundleKey); - result = PutBundleToDisturbeDB(bundleKey, bundleInfo); + bundleInfo.SetBundleName(bundleName); + bundleInfo.SetBundleUid(bundleUid); + result = PutBundleToDisturbeDB(bundleKeyStr, bundleInfo); break; } case OHOS::DistributedKv::Status::SUCCESS: { @@ -455,8 +488,8 @@ bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( const NotificationPreferencesInfo::BundleInfo &bundleInfo) { std::vector entries; - std::string bundleKey = bundleInfo.GetBundleName(); - GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_NAME), bundleKey, entries); + std::string bundleKey = bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid())); + GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_NAME), bundleInfo.GetBundleName(), entries); GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_BADGE_TOTAL_NUM), std::to_string(bundleInfo.GetBadgeTotalNum()), entries); @@ -470,6 +503,7 @@ bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_ENABLE_NOTIFICATION), std::to_string(bundleInfo.GetEnableNotification()), entries); + GenerateEntry(GenerateBundleKey(bundleKey, KEY_BUNDLE_UID), std::to_string(bundleInfo.GetBundleUid()), entries); if (!CheckKvStore()) { ANS_LOGE("KvStore is nullptr."); return false; @@ -485,7 +519,9 @@ bool NotificationPreferencesDatabase::PutBundlePropertyValueToDisturbeDB( bool NotificationPreferencesDatabase::ParseFromDisturbeDB(NotificationPreferencesInfo &info) { ANS_LOGD("%{public}s", __FUNCTION__); - ParseDisturbeMode(info); + ParseDoNotDisturbType(info); + ParseDoNotDisturbBeginDate(info); + ParseDoNotDisturbEndDate(info); ParseEnableAllNotification(info); if (!CheckKvStore()) { @@ -720,8 +756,8 @@ bool NotificationPreferencesDatabase::PutBundleToDisturbeDB( } ANS_LOGD("Key not fund, so create a bundle, bundle key is %{public}s.", bundleKey.c_str()); - OHOS::DistributedKv::Key bundleDBKey(KEY_BUNDLE_LABEL + bundleKey); - OHOS::DistributedKv::Value bundleValue(bundleKey); + OHOS::DistributedKv::Key bundleDBKey(bundleKey); + OHOS::DistributedKv::Value bundleValue(GenerateBundleLablel(bundleInfo)); if (kvStorePtr_->Put(bundleDBKey, bundleValue) != OHOS::DistributedKv::Status::SUCCESS) { ANS_LOGE("Store bundle name to db is failed."); return false; @@ -745,18 +781,19 @@ void NotificationPreferencesDatabase::GenerateEntry( entries.push_back(entry); } -bool NotificationPreferencesDatabase::SlotToEntry( - const std::string &bundleKey, const sptr &slot, std::vector &entries) +bool NotificationPreferencesDatabase::SlotToEntry(const std::string &bundleName, const int &bundleUid, + const sptr &slot, std::vector &entries) { if (slot == nullptr) { ANS_LOGE("Notification group is nullptr."); return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleName, bundleUid)) { return false; } + std::string bundleKey = bundleName + std::to_string(bundleUid); GenerateSlotEntry(bundleKey, slot, entries); return true; } @@ -784,7 +821,7 @@ void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundl std::to_string(static_cast(slot->GetLockScreenVisibleness())), entries); GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_SOUND), slot->GetSound().ToString(), entries); - GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE), + GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_ENABLE_BYPASS_DND), std::to_string(slot->IsEnableBypassDnd()), entries); GenerateEntry(GenerateSlotKey(bundleKey, slotType, KEY_SLOT_VIBRATION_STYLE), @@ -792,7 +829,7 @@ void NotificationPreferencesDatabase::GenerateSlotEntry(const std::string &bundl entries); } -bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleKey, +bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleName, const int &bundleUid, const sptr &group, std::vector &entries) { @@ -801,10 +838,11 @@ bool NotificationPreferencesDatabase::GroupToEntry(const std::string &bundleKey, return false; } - if (!CheckBundle(bundleKey)) { + if (!CheckBundle(bundleName, bundleUid)) { return false; } + std::string bundleKey = bundleName + std::to_string(bundleUid); GenerateGroupEntry(bundleKey, group, entries); return true; } @@ -919,6 +957,11 @@ void NotificationPreferencesDatabase::ParseSlot( auto func = iter->second; func(this, slot, valueStr); } + + if (!typeStr.compare(KEY_SLOT_VIBRATION_STYLE)) { + GetValueFromDisturbeDB(findString + KEY_SLOT_ENABLE_VRBRATION, + [&](OHOS::DistributedKv::Value &value) { ParseSlotEnableVrbration(slot, value.ToString()); }); + } } std::string NotificationPreferencesDatabase::FindLastString( @@ -962,6 +1005,15 @@ int NotificationPreferencesDatabase::StringToInt(const std::string &str) const return value; } +int64_t NotificationPreferencesDatabase::StringToInt64(const std::string &str) const +{ + int value = 0; + if (!str.empty()) { + value = stoll(str, nullptr); + } + return value; +} + bool NotificationPreferencesDatabase::IsSlotKey(const std::string &bundleKey, const std::string &key) const { std::string tempStr = FindLastString(bundleKey, key); @@ -1064,36 +1116,48 @@ std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString( return slotType; } -void NotificationPreferencesDatabase::ParseDisturbeMode(NotificationPreferencesInfo &info) +void NotificationPreferencesDatabase::ParseDoNotDisturbType(NotificationPreferencesInfo &info) { - GetValueFromDisturbeDB( - KEY_DISTURB_MODE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDisturbMode(info.GetDisturbMode()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - info.SetDisturbMode(static_cast(StringToInt(value.ToString()))); - } - } else { - ANS_LOGW("Parse disturbe mode failed, use defalut value."); - } - }); + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + int userId = iter.GetLocalId(); + NotificationPreferencesDatabase::GetDoNotDisturbType(info, userId); + } +} + +void NotificationPreferencesDatabase::ParseDoNotDisturbBeginDate(NotificationPreferencesInfo &info) +{ + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + int userId = iter.GetLocalId(); + NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(info, userId); + } +} + +void NotificationPreferencesDatabase::ParseDoNotDisturbEndDate(NotificationPreferencesInfo &info) +{ + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + int userId = iter.GetLocalId(); + NotificationPreferencesDatabase::GetDoNotDisturbEndDate(info, userId); + } } void NotificationPreferencesDatabase::ParseEnableAllNotification(NotificationPreferencesInfo &info) { - GetValueFromDisturbeDB( - KEY_ENABLE_ALL_NOTIFICATION, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutNotificationsEnabled(info.GetEnabledAllNotification()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - info.SetEnabledAllNotification(static_cast(StringToInt(value.ToString()))); - } - } else { - ANS_LOGW("Parse enable all notification failed, use defalut value."); - } - }); + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + int userId = iter.GetLocalId(); + NotificationPreferencesDatabase::GetEnableAllNotification(info, userId); + } } void NotificationPreferencesDatabase::ParseGroupDescription( @@ -1150,6 +1214,13 @@ void NotificationPreferencesDatabase::ParseBundleEnableNotification( bundleInfo.SetEnableNotification(static_cast(StringToInt(value))); } +void NotificationPreferencesDatabase::ParseBundleUid( + NotificationPreferencesInfo::BundleInfo &bundleInfo, const std::string &value) const +{ + ANS_LOGD("SetBundleUid uuid is %{public}s.", value.c_str()); + bundleInfo.SetBundleUid(StringToInt(value)); +} + void NotificationPreferencesDatabase::ParseSlotGroupId(sptr &slot, const std::string &value) const { ANS_LOGD("ParseSlotGroupId slot group id is %{public}s.", value.c_str()); @@ -1213,6 +1284,7 @@ void NotificationPreferencesDatabase::ParseSlotLockscreenVisibleness( void NotificationPreferencesDatabase::ParseSlotSound(sptr &slot, const std::string &value) const { + ANS_LOGD("ParseSlotSound slot sound is %{public}s.", value.c_str()); std::string slotUri = value; Uri uri(slotUri); slot->SetSound(uri); @@ -1221,6 +1293,7 @@ void NotificationPreferencesDatabase::ParseSlotSound(sptr &slo void NotificationPreferencesDatabase::ParseSlotVibrationSytle( sptr &slot, const std::string &value) const { + ANS_LOGD("ParseSlotVibrationSytle slot vibration style is %{public}s.", value.c_str()); std::vector vibrationStyle; StringToVector(value, vibrationStyle); slot->SetVibrationStyle(vibrationStyle); @@ -1233,5 +1306,107 @@ void NotificationPreferencesDatabase::ParseSlotEnableBypassDnd( bool enable = static_cast(StringToInt(value)); slot->EnableBypassDnd(enable); } + +std::string NotificationPreferencesDatabase::GenerateBundleLablel( + const NotificationPreferencesInfo::BundleInfo &bundleInfo) const +{ + return bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid())); +} + +void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreferencesInfo &info, int userId) +{ + std::string key = + std::string().append(KEY_DO_NOT_DISTURB_TYPE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + GetValueFromDisturbeDB( + key, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + sptr disturbDate = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + info.GetDoNotDisturbDate(userId, disturbDate); + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDoNotDisturbDate(userId, disturbDate); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + if (disturbDate != nullptr) { + disturbDate->SetDoNotDisturbType( + (NotificationConstant::DoNotDisturbType)StringToInt(value.ToString())); + } + } + } else { + ANS_LOGW("Parse disturbe mode failed, use defalut value."); + } + info.SetDoNotDisturbDate(userId, disturbDate); + }); +} + +void NotificationPreferencesDatabase::GetDoNotDisturbBeginDate(NotificationPreferencesInfo &info, int userId) +{ + std::string key = + std::string().append(KEY_DO_NOT_DISTURB_BEGIN_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + GetValueFromDisturbeDB( + key, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + sptr disturbDate = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + info.GetDoNotDisturbDate(userId, disturbDate); + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDoNotDisturbDate(userId, disturbDate); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + if (disturbDate != nullptr) { + disturbDate->SetBeginDate(StringToInt64(value.ToString())); + } + } + } else { + ANS_LOGW("Parse disturbe start time failed, use defalut value."); + } + info.SetDoNotDisturbDate(userId, disturbDate); + }); +} + +void NotificationPreferencesDatabase::GetDoNotDisturbEndDate(NotificationPreferencesInfo &info, int userId) +{ + std::string key = + std::string().append(KEY_DO_NOT_DISTURB_END_DATE).append(KEY_UNDER_LINE).append(std::to_string(userId)); + GetValueFromDisturbeDB( + key, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + sptr disturbDate = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + info.GetDoNotDisturbDate(userId, disturbDate); + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDoNotDisturbDate(userId, disturbDate); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + if (disturbDate != nullptr) { + disturbDate->SetEndDate(StringToInt64(value.ToString())); + } + } + } else { + ANS_LOGW("Parse disturbe end time failed, use defalut value."); + } + info.SetDoNotDisturbDate(userId, disturbDate); + }); +} + +void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPreferencesInfo &info, int userId) +{ + std::string key = + std::string().append(KEY_ENABLE_ALL_NOTIFICATION).append(KEY_UNDER_LINE).append(std::to_string(userId)); + GetValueFromDisturbeDB( + key, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + bool enable = true; + if (!info.GetEnabledAllNotification(userId, enable)) { + info.SetEnabledAllNotification(userId, enable); + ANS_LOGW("Enable setting not found, default true."); + } + PutNotificationsEnabled(userId, enable); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + info.SetEnabledAllNotification(userId, static_cast(StringToInt(value.ToString()))); + } + } else { + ANS_LOGW("Parse enable all notification failed, use defalut value."); + } + }); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 9e58416e9fee7dbdc8aeaed8c20f584301c03fbe..586288ac323ca216e3b71f50051294929fb90815 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -16,7 +16,6 @@ namespace OHOS { namespace Notification { - NotificationPreferencesInfo::BundleInfo::BundleInfo() {} NotificationPreferencesInfo::BundleInfo::~BundleInfo() @@ -228,26 +227,6 @@ int NotificationPreferencesInfo::BundleInfo::GetBundleUid() const return uid_; } -void NotificationPreferencesInfo::SetEnabledAllNotification(const bool &value) -{ - isEnabledAllNotification_ = value; -} - -bool NotificationPreferencesInfo::GetEnabledAllNotification() const -{ - return isEnabledAllNotification_; -} - -void NotificationPreferencesInfo::SetDisturbMode(const NotificationConstant::DisturbMode &mode) -{ - disturbMode_ = mode; -} - -NotificationConstant::DisturbMode NotificationPreferencesInfo::GetDisturbMode() const -{ - return disturbMode_; -} - void NotificationPreferencesInfo::SetBundleInfo(const BundleInfo &info) { std::string bundleKey = info.GetBundleName().append(std::to_string(info.GetBundleUid())); @@ -292,5 +271,36 @@ void NotificationPreferencesInfo::ClearBundleInfo() infos_.clear(); } +void NotificationPreferencesInfo::SetDoNotDisturbDate(const int32_t &userId, + const sptr &doNotDisturbDate) +{ + doNotDisturbDate_.insert_or_assign(userId, doNotDisturbDate); +} + +bool NotificationPreferencesInfo::GetDoNotDisturbDate(const int32_t &userId, + sptr &doNotDisturbDate) const +{ + auto iter = doNotDisturbDate_.find(userId); + if (iter != doNotDisturbDate_.end()) { + doNotDisturbDate = iter->second; + return true; + } + return false; +} + +void NotificationPreferencesInfo::SetEnabledAllNotification(const int32_t &userId, const bool &enable) +{ + isEnabledAllNotification_.insert_or_assign(userId, enable); +} + +bool NotificationPreferencesInfo::GetEnabledAllNotification(const int32_t &userId, bool &enable) const +{ + auto iter = isEnabledAllNotification_.find(userId); + if (iter != isEnabledAllNotification_.end()) { + enable = iter->second; + return true; + } + return false; +} } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp index d59d1d181ee1fbf38621f09547dd0c1dbb3066f7..9b4c59e6dc9bc00b3f4de75f86f22d73978e752d 100644 --- a/services/ans/src/notification_slot_filter.cpp +++ b/services/ans/src/notification_slot_filter.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - void NotificationSlotFilter::OnStart() {} @@ -63,6 +62,5 @@ ErrCode NotificationSlotFilter::OnPublish(const std::shared_ptr #include +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ipc_skeleton.h" +#include "os_account_manager.h" #include "remote_death_recipient.h" namespace OHOS { namespace Notification { - struct NotificationSubscriberManager::SubscriberRecord { sptr subscriber {nullptr}; std::set bundleList_ {}; bool subscribedAll {false}; + int32_t userId {SUBSCRIBE_USER_INIT}; }; NotificationSubscriberManager::NotificationSubscriberManager() @@ -53,13 +56,24 @@ ErrCode NotificationSubscriberManager::AddSubscriber( return ERR_ANS_INVALID_PARAM; } - AppExecFwk::EventHandler::Callback addSubscriberFunc = - std::bind(&NotificationSubscriberManager::AddSubscriberInner, this, subscriber, subscribeInfo); + sptr subInfo = subscribeInfo; + if (subInfo == nullptr) { + subInfo = new (std::nothrow) NotificationSubscribeInfo(); + if (subInfo == nullptr) { + ANS_LOGE("Failed to create NotificationSubscribeInfo ptr."); + return ERR_ANS_NO_MEMORY; + } - if (!handler_->PostTask(addSubscriberFunc, AppExecFwk::EventQueue::Priority::HIGH)) { - return ERR_ANS_TASK_ERR; + int userId = SUBSCRIBE_USER_ALL; + subInfo->AddAppUserId(userId); } - return ERR_OK; + + ErrCode result = ERR_ANS_TASK_ERR; + handler_->PostSyncTask(std::bind([this, &subscriber, &subInfo, &result]() { + result = this->AddSubscriberInner(subscriber, subInfo); + }), + AppExecFwk::EventQueue::Priority::HIGH); + return result; } ErrCode NotificationSubscriberManager::RemoveSubscriber( @@ -70,13 +84,12 @@ ErrCode NotificationSubscriberManager::RemoveSubscriber( return ERR_ANS_INVALID_PARAM; } - AppExecFwk::EventHandler::Callback removeSubscriberFunc = - std::bind(&NotificationSubscriberManager::RemoveSubscriberInner, this, subscriber, subscribeInfo); - - if (!handler_->PostTask(removeSubscriberFunc, AppExecFwk::EventQueue::Priority::HIGH)) { - return ERR_ANS_TASK_ERR; - } - return ERR_OK; + ErrCode result = ERR_ANS_TASK_ERR; + handler_->PostSyncTask(std::bind([this, &subscriber, &subscribeInfo, &result]() { + result = this->RemoveSubscriberInner(subscriber, subscribeInfo); + }), + AppExecFwk::EventQueue::Priority::HIGH); + return result; } void NotificationSubscriberManager::NotifyConsumed( @@ -86,7 +99,6 @@ void NotificationSubscriberManager::NotifyConsumed( ANS_LOGE("handler is nullptr"); return; } - AppExecFwk::EventHandler::Callback NotifyConsumedFunc = std::bind(&NotificationSubscriberManager::NotifyConsumedInner, this, notification, notificationMap); @@ -120,17 +132,17 @@ void NotificationSubscriberManager::NotifyUpdated(const sptrPostTask(NotifyUpdatedFunc); } -void NotificationSubscriberManager::NotifyDisturbModeChanged(const NotificationConstant::DisturbMode &mode) +void NotificationSubscriberManager::NotifyDoNotDisturbDateChanged(const sptr &date) { if (handler_ == nullptr) { ANS_LOGE("handler is nullptr"); return; } - AppExecFwk::EventHandler::Callback NotifyDisturbModeChangedFunc = - std::bind(&NotificationSubscriberManager::NotifyDisturbModeChangedInner, this, mode); + AppExecFwk::EventHandler::Callback func = + std::bind(&NotificationSubscriberManager::NotifyDoNotDisturbDateChangedInner, this, date); - handler_->PostTask(NotifyDisturbModeChangedFunc); + handler_->PostTask(func); } void NotificationSubscriberManager::OnRemoteDied(const wptr &object) @@ -187,9 +199,14 @@ void NotificationSubscriberManager::AddRecordInfo( { if (subscribeInfo != nullptr) { record->bundleList_.clear(); - record->subscribedAll = false; + record->subscribedAll = true; for (auto bundle : subscribeInfo->GetAppNames()) { record->bundleList_.insert(bundle); + record->subscribedAll = false; + } + record->userId = subscribeInfo->GetAppUserId(); + if (record->userId == SUBSCRIBE_USER_INIT) { + record->userId = SUBSCRIBE_USER_ALL; } } else { record->bundleList_.clear(); @@ -214,40 +231,37 @@ void NotificationSubscriberManager::RemoveRecordInfo( } } -void NotificationSubscriberManager::AddSubscriberInner( +ErrCode NotificationSubscriberManager::AddSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo) { std::shared_ptr record = FindSubscriberRecord(subscriber); - if (record == nullptr) { record = CreateSubscriberRecord(subscriber); if (record == nullptr) { ANS_LOGE("CreateSubscriberRecord failed."); - subscriber->OnSubscribeResult(NotificationConstant::RESOURCES_FAIL); - return; + return ERR_ANS_NO_MEMORY; } subscriberRecordList_.push_back(record); record->subscriber->AsObject()->AddDeathRecipient(recipient_); - record->subscriber->OnSubscribeResult(NotificationConstant::SUCCESS); + record->subscriber->OnConnected(); ANS_LOGI("subscriber is connected."); } AddRecordInfo(record, subscribeInfo); - return; + return ERR_OK; } -void NotificationSubscriberManager::RemoveSubscriberInner( +ErrCode NotificationSubscriberManager::RemoveSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo) { std::shared_ptr record = FindSubscriberRecord(subscriber); if (record == nullptr) { ANS_LOGE("subscriber not found."); - subscriber->OnUnsubscribeResult(NotificationConstant::SUCCESS); - return; + return ERR_ANS_INVALID_PARAM; } RemoveRecordInfo(record, subscribeInfo); @@ -257,21 +271,25 @@ void NotificationSubscriberManager::RemoveSubscriberInner( subscriberRecordList_.remove(record); - record->subscriber->OnUnsubscribeResult(NotificationConstant::SUCCESS); + record->subscriber->OnDisconnected(); ANS_LOGI("subscriber is disconnected."); } - return; + return ERR_OK; } void NotificationSubscriberManager::NotifyConsumedInner( const sptr ¬ification, const sptr ¬ificationMap) { + ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); for (auto record : subscriberRecordList_) { + ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); auto BundleNames = notification->GetBundleName(); - auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); - if (!record->subscribedAll == (iter != record->bundleList_.end())) { + if (!record->subscribedAll == (iter != record->bundleList_.end()) && + (notification->GetUserId() == record->userId || + notification->GetUserId() == SUBSCRIBE_USER_ALL || + record->userId == SUBSCRIBE_USER_ALL)) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } @@ -281,11 +299,13 @@ void NotificationSubscriberManager::NotifyConsumedInner( void NotificationSubscriberManager::NotifyCanceledInner( const sptr ¬ification, const sptr ¬ificationMap, int deleteReason) { + ANS_LOGD("%{public}s notification->GetUserId <%{public}d>", __FUNCTION__, notification->GetUserId()); for (auto record : subscriberRecordList_) { + ANS_LOGD("%{public}s record->userId = <%{public}d>", __FUNCTION__, record->userId); auto BundleNames = notification->GetBundleName(); - auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); - if (!record->subscribedAll == (iter != record->bundleList_.end())) { + if (!record->subscribedAll == (iter != record->bundleList_.end()) && + (notification->GetUserId() == record->userId || notification->GetUserId() == SUBSCRIBE_USER_ALL)) { record->subscriber->OnCanceled(notification, notificationMap, deleteReason); record->subscriber->OnCanceled(notification); } @@ -299,13 +319,11 @@ void NotificationSubscriberManager::NotifyUpdatedInner(const sptr &date) { for (auto record : subscriberRecordList_) { - - record->subscriber->OnDisturbModeChanged(mode); + record->subscriber->OnDoNotDisturbDateChange(date); } } - } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index d66946c6c9b92638229969941dca7ead26920e74..9c4a86870cd4a44666ca1c5e5c6b6239bd639618 100644 --- a/services/ans/src/permission_filter.cpp +++ b/services/ans/src/permission_filter.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - void PermissionFilter::OnStart() {} @@ -49,6 +48,5 @@ ErrCode PermissionFilter::OnPublish(const std::shared_ptr &r } return result; } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..18f09d8b6cf6f212a9dbc8c946d9a5a72b52838c --- /dev/null +++ b/services/ans/src/reminder_data_manager.cpp @@ -0,0 +1,1038 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "ans_const_define.h" +#include "common_event_support.h" +#include "notification_slot.h" +#include "reminder_event_manager.h" +#include "time_service_client.h" +#include "singleton.h" + +#include "reminder_data_manager.h" + +namespace OHOS { +namespace Notification { +const int16_t ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM = 2000; +const int16_t ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP = 30; +const uint8_t ReminderDataManager::TIME_ZONE_CHANGE = 0; +const uint8_t ReminderDataManager::DATE_TIME_CHANGE = 1; +std::shared_ptr ReminderDataManager::REMINDER_DATA_MANAGER = nullptr; +std::mutex ReminderDataManager::MUTEX; +std::mutex ReminderDataManager::SHOW_MUTEX; +std::mutex ReminderDataManager::ALERT_MUTEX; + +void ReminderDataManager::PublishReminder(sptr &reminder, + sptr &bundleOption) +{ + if (CheckReminderLimitExceededLocked(bundleOption->GetBundleName())) { + return; + } + UpdateAndSaveReminderLocked(reminder, bundleOption); + StartRecentReminder(); +} + +void ReminderDataManager::CancelReminder( + const int32_t &reminderId, const sptr &bundleOption) +{ + sptr reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName()); + if (reminder == nullptr) { + ANSR_LOGW("Cancel reminder, not find the reminder"); + return; + } + if (activeReminderId_ == reminderId) { + ANSR_LOGD("Cancel active reminder, id=%{public}d", reminderId); + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + if (alertingReminderId_ == reminderId) { + StopTimerLocked(TimerType::ALERTING_TIMER); + StopSoundAndVibrationLocked(reminder); + } + int32_t id = reminderId; + RemoveReminderLocked(id); + CancelNotification(reminder); + StartRecentReminder(); +} + +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 = FindNotificationBundleOption(reminder->GetReminderId()); + advancedNotificationService_->CancelPreparedNotification( + notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption); +} + +bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bundleName) 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; + } + int8_t count = 0; + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired()) { + continue; + } + auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", (*it)->GetReminderId()); + } else { + if (mit->second->GetBundleName() == bundleName) { + count++; + } + } + } + if (count >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP) { + ANSR_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ + reminder can not be published", MAX_NUM_REMINDER_LIMIT_APP); + return true; + } + return false; +} + +void ReminderDataManager::CancelAllReminders(const sptr &bundleOption) +{ + MUTEX.lock(); + auto it = notificationBundleOptionMap_.find(activeReminderId_); + if (it == notificationBundleOptionMap_.end()) { + ANSR_LOGW("Not get bundle option, reminderId=%{public}d", activeReminderId_); + } else { + if (it->second->GetBundleName() == bundleOption->GetBundleName()) { + StopTimer(TimerType::TRIGGER_TIMER); + } + } + for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { + int32_t reminderId = (*vit)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + ++vit; + continue; + } + if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { + if ((*vit)->IsAlerting()) { + StopAlertingReminder(*vit); + } + CancelNotification(*vit); + ANSR_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); + vit = reminderVector_.erase(vit); + notificationBundleOptionMap_.erase(mit); + totalCount_--; + continue; + } + ++vit; + } + MUTEX.unlock(); + StartRecentReminder(); +} + +void ReminderDataManager::GetValidReminders( + const sptr bundleOption, std::vector> &reminders) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired()) { + continue; + } + int32_t reminderId = (*it)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + } else { + if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { + reminders.push_back(*it); + } + } + } +} + +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; + } + } + ANSR_LOGD("Containers(shownVector) add. reminderId=%{public}d", reminder->GetReminderId()); + showedReminderVector_.push_back(reminder); +} + +void ReminderDataManager::OnProcessDiedLocked(const sptr bundleOption) +{ + std::string bundleName = bundleOption->GetBundleName(); + int32_t uid = bundleOption->GetUid(); + ANSR_LOGI("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { + int32_t reminderId = (*it)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + continue; + } + if (mit->second->GetBundleName() != bundleName || mit->second->GetUid() != uid) { + continue; + } + if ((*it)->IsAlerting()) { + TerminateAlerting((*it), "onProcessDied"); + } else { + CancelNotification(*it); + (*it)->OnClose(false); + ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminderId); + showedReminderVector_.erase(it); + --it; + } + } +} + +std::shared_ptr ReminderDataManager::CreateTimerInfo(TimerType type) const +{ + auto sharedTimerInfo = std::make_shared(); + sharedTimerInfo->SetType(sharedTimerInfo->TIMER_TYPE_WAKEUP|sharedTimerInfo->TIMER_TYPE_EXACT); + sharedTimerInfo->SetRepeat(false); + sharedTimerInfo->SetInterval(0); + + int requestCode = 10; + std::vector flags; + flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + auto want = std::make_shared(); + + switch (type) { + case (TimerType::TRIGGER_TIMER): { + want->SetAction(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + 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); + want->SetParam(ReminderRequest::PARAM_REMINDER_ID, alertingReminderId_); + break; + } + default: + ANSR_LOGE("TimerType not support"); + break; + } + std::vector> wants; + wants.push_back(want); + WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, + wants, + nullptr + ); + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); + 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; + } + auto bundleOption = FindNotificationBundleOption(reminderId); + if (bundleOption == nullptr) { + ANSR_LOGW("Not find the reminder due to bundle info is null"); + return nullptr; + } + if (bundleOption -> GetBundleName() != pkgName) { + ANSR_LOGW("Not find the reminder due to package name not match"); + return nullptr; + } + return reminder; +} + +sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) const +{ + auto it = notificationBundleOptionMap_.find(reminderId); + if (it == notificationBundleOptionMap_.end()) { + return nullptr; + } else { + return it->second; + } +} + +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("Invilate reminder id: %{public}d", reminderId); + return; + } + CloseReminder(reminder, cancelNotification); +} + +void ReminderDataManager::CloseReminder(const sptr &reminder, bool cancelNotification) +{ + int32_t reminderId = reminder->GetReminderId(); + if (activeReminderId_ == reminderId) { + ANSR_LOGD("Stop active reminder due to CloseReminder"); + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + if (alertingReminderId_ == reminderId) { + StopTimerLocked(TimerType::ALERTING_TIMER); + StopSoundAndVibrationLocked(reminder); + } + reminder->OnClose(true); + RemoveFromShowedReminders(reminder); + if (cancelNotification) { + CancelNotification(reminder); + } + StartRecentReminder(); +} + +std::shared_ptr ReminderDataManager::GetInstance() +{ + if (REMINDER_DATA_MANAGER == nullptr) { + REMINDER_DATA_MANAGER = std::make_shared(); + ReminderEventManager reminderEventManager(REMINDER_DATA_MANAGER); + } + return REMINDER_DATA_MANAGER; +} + +void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) +{ + 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"); + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + std::vector> showImmediately = RefreshRemindersLocked(type); + if (!showImmediately.empty()) { + ANSR_LOGD("Refresh all reminders, show expired reminders immediately"); + HandleImmediatelyShow(showImmediately, true); + } + 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("Invilate reminder id: %{public}d", reminderId); + return; + } + TerminateAlerting(reminder, "timeOut"); +} + +void ReminderDataManager::TerminateAlerting(const uint16_t waitInMilli, const sptr &reminder) +{ + sleep(waitInMilli); + TerminateAlerting(reminder, "waitInMillis"); +} + +void ReminderDataManager::TerminateAlerting(const sptr &reminder, const std::string &reason) +{ + ANSR_LOGI("Terminate the alerting reminder, %{public}s, called by %{public}s", + reminder->Dump().c_str(), reason.c_str()); + StopAlertingReminder(reminder); + + if (reminder == nullptr) { + ANSR_LOGE("TerminateAlerting illegal."); + return; + } + if (!reminder->OnTerminate()) { + return; + } + int32_t reminderId = reminder->GetReminderId(); + sptr bundleOption = FindNotificationBundleOption(reminderId); + 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); + advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); +} + +void ReminderDataManager::UpdateAndSaveReminderLocked( + const sptr &reminder, const sptr &bundleOption) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + reminder->InitReminderId(); + int32_t reminderId = reminder->GetReminderId(); + ANSR_LOGD("Containers(map) add. reminderId=%{public}d", reminderId); + auto ret = notificationBundleOptionMap_.insert( + std::pair>(reminderId, bundleOption)); + if (!ret.second) { + ANSR_LOGE("Containers add to map error"); + return; + } + ANSR_LOGD("Containers(vector) add. reminderId=%{public}d", reminderId); + reminderVector_.push_back(reminder); + totalCount_++; +} + +void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotificationService) +{ + advancedNotificationService_ = advancedNotificationService; +} + +void ReminderDataManager::ShowActiveReminder() +{ + ANSR_LOGI("Begin to show reminder."); + if (activeReminderId_ == -1) { + ANSR_LOGE("Active reminder not exist"); + return; + } + if (HandleSysTimeChange(activeReminder_)) { + ResetStates(TimerType::TRIGGER_TIMER); + return; + } + ShowActiveReminderExtendLocked(activeReminder_); + ResetStates(TimerType::TRIGGER_TIMER); + 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(); + activeReminder_ = reminder; + } +} + +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; + } +} + +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; + } + if ((*it)->GetTriggerTimeInMilli() - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { + continue; + } + if (!isAlerting) { + playSoundReminder = (*it); + isAlerting = true; + } else { + ShowReminder((*it), false, false, false, false); + } + } + if (playSoundReminder != nullptr) { + ShowReminder(playSoundReminder, true, false, false, true); + } +} + +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 = FindNotificationBundleOption(reminderId); + 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); + return; + } + if (isNeedToPlaySound) { // todo if shouldAlert + PlaySoundAndVibration(reminder); // play sound and vibration + reminder->OnShow(true, isSysTimeChanged, true); + if (needScheduleTimeout) { + StartTimer(reminder, TimerType::ALERTING_TIMER); + } else { + TerminateAlerting(ReminderRequest::MILLI_SECONDS, reminder); + } + } else { + reminder->OnShow(false, isSysTimeChanged, true); + } + AddToShowedReminders(reminder); + ANSR_LOGD("publish notification.(reminderId=%{public}d)", reminder->GetReminderId()); + UpdateNotification(reminder); // this should be called after OnShow + ErrCode errCode + = advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + if (errCode != ERR_OK) { + reminder->OnShowFail(); + RemoveFromShowedReminders(reminder); + } else { + HandleSameNotificationIdShowing(reminder); + } + if (isNeedToStartNext) { + StartRecentReminder(); + } +} + +void ReminderDataManager::UpdateNotification(const sptr &reminder) +{ + 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, ""); +} + +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("Invilate reminder id: %{public}d", reminderId); + return; + } + SnoozeReminderImpl(reminder); +} + +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_); + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + + // 1) Snooze the reminder by manual + if (alertingReminderId_ == reminder->GetReminderId()) { + StopTimerLocked(TimerType::ALERTING_TIMER); + StopSoundAndVibrationLocked(reminder); + } + reminder->OnSnooze(); + + // 2) Show the notification dialog in the systemUI + sptr bundleOption = FindNotificationBundleOption(reminderId); + 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); + advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); + StartRecentReminder(); +} + +// snoozeReminder(bool snoozeAll) + +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) { + StopTimerLocked(TimerType::TRIGGER_TIMER); + activeReminder_->OnStop(); + } + ANSR_LOGI("Start recent reminder"); + StartTimerLocked(reminder, TimerType::TRIGGER_TIMER); + reminder->OnStart(); + SetActiveReminder(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; + } + int32_t reminderId = (*it)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Dump get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + continue; + } + std::string bundleName = mit->second->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()); + 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); + auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); + if (mit == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", + (*it)->GetReminderId()); + } else { + ANSR_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); + notificationBundleOptionMap_.erase(mit); + } + it = reminderVector_.erase(it); + totalCount_--; + } + return nullptr; +} + +std::vector> ReminderDataManager::GetSameBundleRemindersLocked(std::string &bundleName) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + std::vector> reminders; + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + sptr bundleOption = FindNotificationBundleOption((*it)->GetReminderId()); + if (bundleOption == nullptr) { + ANSR_LOGW("GetSameBundleRemindersLocked get notificationBundleOption(reminderId=%{public}d) fail", + (*it)->GetReminderId()); + continue; + } + if (bundleName == bundleOption->GetBundleName()) { + reminders.push_back((*it)); + } + } + return reminders; +} + +void ReminderDataManager::HandleImmediatelyShow( + std::vector> &showImmediately, bool isSysTimeChanged) +{ + bool isAlerting = false; + for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { + if (!isAlerting) { + ShowReminder((*it), true, false, isSysTimeChanged, false); + isAlerting = true; + } else { + ShowReminder((*it), false, false, isSysTimeChanged, false); + } + } +} + +sptr ReminderDataManager::HandleRefreshReminder(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); + } + return nullptr; + } else { + 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; + } + sptr bundleOption = FindNotificationBundleOption(tmpId); + if (bundleOption == nullptr) { + ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); + continue; + } + if (notificationId == (*it)->GetNotificationId() && + IsBelongToSameApp(reminder, bundleOption->GetBundleName(), 0)) { + if ((*it)->IsAlerting()) { + StopAlertingReminder(*it); + } + (*it)->OnSameNotificationIdCovered(); + RemoveFromShowedReminders(*it); + } + } +} + +bool ReminderDataManager::IsBelongToSameApp( + const sptr reminder, const std::string otherPkgName, const int otherUserId) +{ + ANSR_LOGD("otherUserId=%{public}d, (currently, userId not support)", otherUserId); + int32_t reminderId = reminder->GetReminderId(); + sptr bundleOption = FindNotificationBundleOption(reminderId); + if (bundleOption == nullptr) { + ANSR_LOGW("IsBelongToSameApp get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + return false; + } + if (bundleOption->GetBundleName() == otherPkgName) { + return true; + } + return false; +} + +void ReminderDataManager::PlaySoundAndVibrationLocked(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::ALERT_MUTEX); // todo check died lock + PlaySoundAndVibration(reminder); +} + +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()); + if (soundPlayer_ == nullptr) { + soundPlayer_ = Media::PlayerFactory::CreatePlayer(); + } + std::string uri = GetSoundUri(reminder); + ANSR_LOGD("uri:%{public}s", uri.c_str()); + soundPlayer_->SetSource(uri); + soundPlayer_->SetLooping(true); + soundPlayer_->Prepare(); + soundPlayer_->Play(); + SetAlertingReminder(reminder); +} + +std::string ReminderDataManager::GetSoundUri(const sptr &reminder) +{ + sptr bundle = FindNotificationBundleOption(reminder->GetReminderId()); + std::vector> slots; + ErrCode errCode = advancedNotificationService_->GetSlotsByBundle(bundle, slots); + Uri uri = DEFAULT_NOTIFICATION_SOUND; + 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."); + return; + } + ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); + soundPlayer_->Stop(); + soundPlayer_->Release(); + soundPlayer_ = nullptr; + 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; + } + } +} + +std::vector> ReminderDataManager::RefreshRemindersLocked(uint8_t type) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + std::vector> showImmediately; + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + sptr reminder = HandleRefreshReminder(type, (*it)); + if (reminder != nullptr) { + showImmediately.push_back(reminder); + } + } + return showImmediately; +} + +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_--; + break; + } else { + ++it; + } + } + auto it = notificationBundleOptionMap_.find(reminderId); + if (it == notificationBundleOptionMap_.end()) { + ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); + } else { + ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); + notificationBundleOptionMap_.erase(it); + } +} + +void ReminderDataManager::StartTimerLocked(const sptr &reminderRequest, TimerType type) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + StartTimer(reminderRequest, type); +} + +void ReminderDataManager::StartTimer(const sptr &reminderRequest, TimerType type) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + time_t now; + (void)time(&now); // unit is seconds. + uint64_t triggerTime = 0; + switch (type) { + case TimerType::TRIGGER_TIMER: { + if (timerId_ != 0) { + ANSR_LOGE("Trigger timer has already started."); + break; + } + triggerTime = reminderRequest->GetTriggerTimeInMilli(); + timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type)); + timer->StartTimer(timerId_, triggerTime); + SetActiveReminder(reminderRequest); + ANSR_LOGD("Start timing (next triggerTime), timerId=%{public}llu", (unsigned long long)timerId_); + break; + } + case TimerType::ALERTING_TIMER: { + if (timerIdAlerting_ != 0) { + ANSR_LOGE("Alerting time out timer has already started."); + break; + } + triggerTime = now * ReminderRequest::MILLI_SECONDS + + static_cast(reminderRequest->GetRingDuration() * ReminderRequest::MILLI_SECONDS); + timerIdAlerting_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo(type)); + timer->StartTimer(timerIdAlerting_, triggerTime); + ANSR_LOGD( + "Start timing (alerting time out), timerId=%{public}llu", (unsigned long long)timerIdAlerting_); + break; + } + default: { + ANSR_LOGE("TimerType not support"); + break; + } + } + if (triggerTime == 0) { + ANSR_LOGW("Start timer fail"); + } else { + ANSR_LOGD("Timing info: now:(%{public}lld), tar:(%{public}llu)", + (long long)(now * ReminderRequest::MILLI_SECONDS), (unsigned long long)(triggerTime)); + } +} + +void ReminderDataManager::StopTimerLocked(TimerType type) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + StopTimer(type); +} + +void ReminderDataManager::StopTimer(TimerType type) +{ + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + 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}llu", (unsigned long long)timerId); + timer->StopTimer(timerId); + ResetStates(type); +} + +void ReminderDataManager::ResetStates(TimerType type) +{ + switch (type) { + case TimerType::TRIGGER_TIMER: { + ANSR_LOGD("ResetStates(activeReminder)"); + timerId_ = 0; + activeReminderId_ = -1; + break; + } + case TimerType::ALERTING_TIMER: { + ANSR_LOGD("ResetStates(alertingReminder)"); + timerIdAlerting_ = 0; + alertingReminderId_ = -1; + break; + } + default: { + ANSR_LOGE("TimerType not support"); + break; + } + } +} +} +} \ No newline at end of file diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d085adff048081db48272588c9c02c2fa3b4621d --- /dev/null +++ b/services/ans/src/reminder_event_manager.cpp @@ -0,0 +1,149 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "appmgr/app_mgr_constants.h" +#include "bundle_mgr_interface.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "bundle_constants.h" +#include "if_system_ability_manager.h" +#include "iservice_registry.h" +#include "system_ability_definition.h" + +#include "reminder_event_manager.h" + +using namespace OHOS::EventFwk; +namespace OHOS { +namespace Notification { +ReminderEventManager::ReminderEventManager(std::shared_ptr &reminderDataManager) +{ + init(reminderDataManager); +} + +void ReminderEventManager::init(std::shared_ptr &reminderDataManager) const +{ + MatchingSkills matchingSkills; + matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); + matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_ALERT_TIMEOUT); + matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_CLOSE_ALERT); + matchingSkills.AddEvent(ReminderRequest::REMINDER_EVENT_SNOOZE_ALERT); + 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); + CommonEventSubscribeInfo subscriberInfo(matchingSkills); + auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); + if (CommonEventManager::SubscribeCommonEvent(subscriber)) { + ANSR_LOGD("SubscribeCommonEvent ok"); + } else { + ANSR_LOGD("SubscribeCommonEvent fail"); + } +} + +ReminderEventManager::ReminderEventSubscriber::ReminderEventSubscriber( + const CommonEventSubscribeInfo &subscriberInfo, + std::shared_ptr &reminderDataManager) : CommonEventSubscriber(subscriberInfo) +{ + reminderDataManager_ = reminderDataManager; +} + +void ReminderEventManager::ReminderEventSubscriber::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(); + 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_REMOVE_NOTIFICATION) { + reminderDataManager_->CloseReminder(want, false); + 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; + } +} + +void ReminderEventManager::ReminderEventSubscriber::HandlePackageRemove(OHOS::EventFwk::Want &want) const +{ + sptr bundleOption = GetBundleOption(want); + reminderDataManager_->CancelAllReminders(bundleOption); +} + +void ReminderEventManager::ReminderEventSubscriber::HandleProcessDied(OHOS::EventFwk::Want &want) const +{ + sptr bundleOption = GetBundleOption(want); + reminderDataManager_->OnProcessDiedLocked(bundleOption); +} + +sptr ReminderEventManager::ReminderEventSubscriber::GetBundleOption( + const OHOS::EventFwk::Want &want) const +{ + OHOS::AppExecFwk::ElementName ele = want.GetElement(); + std::string bundleName = ele.GetBundleName(); + int userId = want.GetIntParam(OHOS::AppExecFwk::Constants::USER_ID, -1); + int32_t uid = GetUid(userId, bundleName); + ANSR_LOGD("bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + return bundleOption; +} + +int32_t ReminderEventManager::ReminderEventSubscriber::GetUid(const int userId, const std::string bundleName) const +{ + AppExecFwk::ApplicationInfo info; + OHOS::sptr systemAbilityManager + = OHOS::SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + OHOS::sptr remoteObject + = systemAbilityManager->GetSystemAbility(OHOS::BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + OHOS::sptr bundleMgr + = OHOS::iface_cast(remoteObject); + bundleMgr->GetApplicationInfo(bundleName, AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO, + static_cast(userId), info); + return static_cast(info.uid); +} +} // namespace OHOS +} // namespace Notification diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..486ae1d0012ab1a48769c51e9361ca785fdad3c3 --- /dev/null +++ b/services/ans/src/reminder_timer_info.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 "ans_log_wrapper.h" +#include "common_event_manager.h" +#include "reminder_request.h" + +#include "reminder_timer_info.h" + +using namespace OHOS::EventFwk; +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/services/ans/src/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 959e85f80e9dbf9c559497a5259ff22ad50636f9..c910e429943bf0babdc76a03d03c30f7d2b6eb81 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -21,11 +21,14 @@ namespace OHOS { namespace Notification { - SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callbacks_(callbacks) { EventFwk::MatchingSkills matchingSkills; matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON); + matchingSkills.AddEvent(EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF); +#endif EventFwk::CommonEventSubscribeInfo commonEventSubscribeInfo(matchingSkills); subscriber_ = std::make_shared( @@ -51,8 +54,17 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) sptr bundleOption = new NotificationBundleOption(bundleName, uid); callbacks_.onBundleRemoved(bundleOption); } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_ON) { + if (callbacks_.onScreenOn != nullptr) { + callbacks_.onScreenOn(); + } + } else if (action == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_OFF) { + if (callbacks_.onScreenOff != nullptr) { + callbacks_.onScreenOff(); + } +#endif } } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index d94e670afa18ad9f085830dfff38a1b9e5d842b2..3e976bf56a1f295330d56fc59548900f35c51736 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -22,38 +22,29 @@ ohos_unittest("ans_unit_test") { include_dirs = [ ".", "include", - "//foundation/appexecfwk/standard/libs/libeventhandler/src", - "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//utils/native/base/include", "//utils/system/safwk/native/include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/dfx", - "//developtools/bytrace_standard/interfaces/innerkits/native/include", ] + defines = [] + sources = [ "${services_path}/ans/src/advanced_notification_service.cpp", "${services_path}/ans/src/advanced_notification_service_ability.cpp", - "${services_path}/ans/src/disturb_filter.cpp", "${services_path}/ans/src/notification_preferences.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", "${services_path}/ans/src/notification_preferences_info.cpp", "${services_path}/ans/src/notification_slot_filter.cpp", "${services_path}/ans/src/notification_subscriber_manager.cpp", "${services_path}/ans/src/permission_filter.cpp", + "${services_path}/ans/src/reminder_data_manager.cpp", + "${services_path}/ans/src/reminder_event_manager.cpp", + "${services_path}/ans/src/reminder_timer_info.cpp", "${services_path}/ans/src/system_event_observer.cpp", - "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/src/ikvstore_snapshot.cpp", - "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/autils/src/constant.cpp", "advanced_notification_service_ability_test.cpp", "advanced_notification_service_test.cpp", - "disturb_filter_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager_helper.cpp", @@ -73,22 +64,35 @@ ohos_unittest("ans_unit_test") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", + "ability_runtime:abilitykit_native", + "ability_runtime:app_manager", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_innerkits", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", + "multimedia_media_standard:media_client", + "os_account_standard:os_account_innerkits", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", + "time_native:time_service", ] subsystem_name = "notification" diff --git a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp index a13769aa91a7dcacf035df2ba7f4cc4777570d8e..fce488e4deb216ecf38d0bedb7b53cd15aace5ad 100644 --- a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -22,18 +22,17 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class AdvancedNotificationServiceAbilityTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; }; /** * @tc.number : AdvancedNotificationServiceAbilityTest_00100 - * @tc.name : AMS_ANS_AdvancedNotificationServiceAbility_0100 + * @tc.name : ANS_AdvancedNotificationServiceAbility_0100 * @tc.desc : Structure AdvancedNotificationServiceAbility with systemAbilityId and runOnCreate */ HWTEST_F( @@ -43,6 +42,5 @@ HWTEST_F( bool runOnCreate = true; AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); } - } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index f79dc6a38fbb6d3ca24a017f98a34403f8eb23e4..441a16cfd72bcff86cbcda95678a0bbb4288d751 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -22,6 +22,7 @@ #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_ut_constant.h" @@ -34,7 +35,6 @@ using namespace OHOS::Media; namespace OHOS { namespace Notification { - class AdvancedNotificationServiceTest : public testing::Test { public: static void SetUpTestCase(); @@ -80,15 +80,15 @@ inline void SleepForFC() class TestAnsSubscriber : public NotificationSubscriber { public: - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + void OnConnected() override {} - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + void OnDisconnected() override {} void OnDied() override {} void OnUpdate(const std::shared_ptr &sortingMap) override {} - void OnDisturbModeChanged(int disturbMode) override + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override {} void OnCanceled(const std::shared_ptr &request) override {} @@ -119,7 +119,7 @@ void AdvancedNotificationServiceTest::TestAddSlotGroup() } /** - * @tc.number : AMS_ANS_Publish_00100 + * @tc.number : ANS_Publish_00100 * @tc.name : ANSPublish00100 * @tc.desc : Publish a normal text type notification. */ @@ -143,7 +143,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00100, } /** - * @tc.number : AMS_ANS_Publish_00200 + * @tc.number : ANS_Publish_00200 * @tc.name : ANSPublish00200 * @tc.desc : Publish a normal text type notification twice. */ @@ -168,7 +168,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00200, } /** - * @tc.number : AMS_ANS_Publish_00300 + * @tc.number : ANS_Publish_00300 * @tc.name : ANSPublish00300 * @tc.desc : When slotType is CUSTOM and not systemApp, the notification publish fails, * and the notification publish interface returns ERR_ANS_NON_SYSTEM_APP. @@ -193,7 +193,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00300, } /** - * @tc.number : AMS_ANS_Publish_00400 + * @tc.number : ANS_Publish_00400 * @tc.name : ANSPublish00400 * @tc.desc : When the obtained bundleName is empty, the notification publish interface returns * ERR_ANS_INVALID_BUNDLE. @@ -218,7 +218,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00400, } /** - * @tc.number : AMS_ANS_Publish_00500 + * @tc.number : ANS_Publish_00500 * @tc.name : ANSPublish00500 * @tc.desc : When the obtained bundleName does not have a corresponding slot in the database, * create the corresponding slot and publish a notification. @@ -243,7 +243,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00500, } /** - * @tc.number : AMS_ANS_Publish_00600 + * @tc.number : ANS_Publish_00600 * @tc.name : ANSPublish00600 * @tc.desc : When the obtained bundleName have a corresponding slot in the database, * the test publish interface can successfully publish a notification of normal text type. @@ -268,7 +268,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00600, } /** - * @tc.number : AMS_ANS_Publish_00700 + * @tc.number : ANS_Publish_00700 * @tc.name : ANSPublish00700 * @tc.desc : When the obtained bundleName have a corresponding slot in the database, * create the corresponding slot and publish a notification. @@ -292,7 +292,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00700, } /** - * @tc.number : AMS_ANS_Publish_00800 + * @tc.number : ANS_Publish_00800 * @tc.name : ANSPublish00800 * @tc.desc : Create a slot of type SOCIAL_COMMUNICATION and successfully publish a notification */ @@ -316,7 +316,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00800, } /** - * @tc.number : AMS_ANS_Publish_00900 + * @tc.number : ANS_Publish_00900 * @tc.name : ANSPublish00900 * @tc.desc : Create a slot of type SERVICE_REMINDER and successfully publish a notification */ @@ -340,7 +340,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_00900, } /** - * @tc.number : AMS_ANS_Publish_01000 + * @tc.number : ANS_Publish_01000 * @tc.name : ANSPublish01000 * @tc.desc : Create a slot of type CONTENT_INFORMATION and successfully publish a notification */ @@ -364,7 +364,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01000, } /** - * @tc.number : AMS_ANS_Publish_01100 + * @tc.number : ANS_Publish_01100 * @tc.name : ANSPublish01100 * @tc.desc : Create a slot of type OTHER and successfully publish a notification */ @@ -388,7 +388,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01100, } /** - * @tc.number : AMS_ANS_Publish_01200 + * @tc.number : ANS_Publish_01200 * @tc.name : ANSPublish01200 * @tc.desc : Create a slot of type CUSTOM and successfully publish a notification */ @@ -412,7 +412,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01200, } /** - * @tc.number : AMS_ANS_Publish_01300 + * @tc.number : ANS_Publish_01300 * @tc.name : ANSPublish01300 * @tc.desc : When a bundle is not allowed to publish a notification, the notification publishing interface returns @@ -441,7 +441,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01300, } /** - * @tc.number : AMS_ANS_Publish_01400 + * @tc.number : ANS_Publish_01400 * @tc.name : ANSPublish01400 * @tc.desc : */ @@ -455,7 +455,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01400, /** * @tc.number : AdvancedNotificationServiceTest_01600 - * @tc.name : AMS_ANS_GetSlot_0200 + * @tc.name : ANS_GetSlot_0200 * @tc.desc : Test GetSlots function when add two identical data */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, Function | SmallTest | Level1) @@ -474,7 +474,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01600, /** * @tc.number : AdvancedNotificationServiceTest_01700 - * @tc.name : AMS_ANS_GetSlotGroup_0100 + * @tc.name : ANS_GetSlotGroup_0100 * @tc.desc : Test GetSlotGroup function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, Function | SmallTest | Level1) @@ -493,7 +493,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01700, /** * @tc.number : AdvancedNotificationServiceTest_01800 - * @tc.name : AMS_ANS_SetNotificationBadgeNum_0100 + * @tc.name : ANS_SetNotificationBadgeNum_0100 * @tc.desc : Test SetNotificationBadgeNum function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, Function | SmallTest | Level1) @@ -504,7 +504,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01800, /** * @tc.number : AdvancedNotificationServiceTest_01900 - * @tc.name : AMS_ANS_GetBundleImportance_0100 + * @tc.name : ANS_GetBundleImportance_0100 * @tc.desc : Test GetBundleImportance function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, Function | SmallTest | Level1) @@ -516,7 +516,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_01900, /** * @tc.number : AdvancedNotificationServiceTest_02000 - * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0100 + * @tc.name : ANS_SetPrivateNotificationsAllowed_0100 * @tc.desc : Test SetPrivateNotificationsAllowed function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, Function | SmallTest | Level1) @@ -527,7 +527,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02000, /** * @tc.number : AdvancedNotificationServiceTest_02100 - * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 + * @tc.name : ANS_GetPrivateNotificationsAllowed_0100 * @tc.desc : Test GetPrivateNotificationsAllowed function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, Function | SmallTest | Level1) @@ -541,7 +541,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02100, /** * @tc.number : AdvancedNotificationServiceTest_02200 - * @tc.name : AMS_ANS_UpdateSlots_0100 + * @tc.name : ANS_UpdateSlots_0100 * @tc.desc : Test UpdateSlots function when no slot */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, Function | SmallTest | Level1) @@ -557,7 +557,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02200, /** * @tc.number : AdvancedNotificationServiceTest_02300 - * @tc.name : AMS_ANS_UpdateSlots_0200 + * @tc.name : ANS_UpdateSlots_0200 * @tc.desc : Test UpdateSlots function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, Function | SmallTest | Level1) @@ -573,7 +573,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02300, /** * @tc.number : AdvancedNotificationServiceTest_02400 - * @tc.name : AMS_ANS_UpdateSlotGroups_0100 + * @tc.name : ANS_UpdateSlotGroups_0100 * @tc.desc : Test UpdateSlotGroups function when no group */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02400, Function | SmallTest | Level1) @@ -589,7 +589,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02400, /** * @tc.number : AdvancedNotificationServiceTest_02500 - * @tc.name : AMS_ANS_UpdateSlotGroups_0200 + * @tc.name : ANS_UpdateSlotGroups_0200 * @tc.desc : Test UpdateSlotGroups function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02500, Function | SmallTest | Level1) @@ -605,7 +605,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02500, /** * @tc.number : AdvancedNotificationServiceTest_02700 - * @tc.name : AMS_ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, Function | SmallTest | Level1) @@ -617,20 +617,24 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, /** * @tc.number : AdvancedNotificationServiceTest_02800 - * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.desc : Test GetShowBadgeEnabledForBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) { + EXPECT_EQ(advancedNotificationService_->SetShowBadgeEnabledForBundle( + new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), true), + (int)ERR_OK); bool allow = false; EXPECT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); + EXPECT_TRUE(allow); } /** * @tc.number : AdvancedNotificationServiceTest_02900 - * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.name : ANS_GetActiveNotifications_0100 * @tc.desc : Test GetActiveNotifications function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, Function | SmallTest | Level1) @@ -639,34 +643,9 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02900, EXPECT_EQ((int)advancedNotificationService_->GetActiveNotifications(notifications), (int)ERR_OK); } -/** - * @tc.number : AdvancedNotificationServiceTest_03400 - * @tc.name : AMS_ANS_SetDisturbMode_0100 - * @tc.desc : Test SetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03400, Function | SmallTest | Level1) -{ - EXPECT_EQ( - (int)advancedNotificationService_->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE), (int)ERR_OK); -} - -/** - * @tc.number : AdvancedNotificationServiceTest_03500 - * @tc.name : AMS_ANS_GetDisturbMode_0100 - * @tc.desc : Test GetDisturbMode function - */ -HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03500, Function | SmallTest | Level1) -{ - EXPECT_EQ( - (int)advancedNotificationService_->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE), (int)ERR_OK); - NotificationConstant::DisturbMode mode; - EXPECT_EQ((int)advancedNotificationService_->GetDisturbMode(mode), (int)ERR_OK); - EXPECT_EQ(mode, NotificationConstant::DisturbMode::ALLOW_NONE); -} - /** * @tc.number : AdvancedNotificationServiceTest_03700 - * @tc.name : AMS_ANS_Delete_0100 + * @tc.name : ANS_Delete_0100 * @tc.desc : Test Delete function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, Function | SmallTest | Level1) @@ -677,7 +656,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03700, /** * @tc.number : AdvancedNotificationServiceTest_03800 - * @tc.name : AMS_ANS_DeleteByBundle_0100 + * @tc.name : ANS_DeleteByBundle_0100 * @tc.desc : Test DeleteByBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, Function | SmallTest | Level1) @@ -689,7 +668,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03800, /** * @tc.number : AdvancedNotificationServiceTest_03900 - * @tc.name : AMS_ANS_DeleteAll_0100 + * @tc.name : ANS_DeleteAll_0100 * @tc.desc : Test DeleteAll function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, Function | SmallTest | Level1) @@ -699,7 +678,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_03900, /** * @tc.number : AdvancedNotificationServiceTest_04000 - * @tc.name : AMS_ANS_GetSlotsByBundle_0100 + * @tc.name : ANS_GetSlotsByBundle_0100 * @tc.desc : Test GetSlotsByBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, Function | SmallTest | Level1) @@ -714,7 +693,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04000, /** * @tc.number : AdvancedNotificationServiceTest_04100 - * @tc.name : AMS_ANS_GetSpecialActiveNotifications_0100 + * @tc.name : ANS_GetSpecialActiveNotifications_0100 * @tc.desc : Test GetSpecialActiveNotifications function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04100, Function | SmallTest | Level1) @@ -750,7 +729,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04100, /** * @tc.number : AdvancedNotificationServiceTest_04600 - * @tc.name : AMS_ANS_Publish_0500 + * @tc.name : ANS_Publish_0500 * @tc.desc : publish function when NotificationsEnabled is false */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04600, Function | SmallTest | Level1) @@ -766,7 +745,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04600, /** * @tc.number : AdvancedNotificationServiceTest_04700 - * @tc.name : AMS_ANS_Cancel_0100 + * @tc.name : ANS_Cancel_0100 * @tc.desc : public two notification to cancel one of them */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04700, Function | SmallTest | Level1) @@ -790,7 +769,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04700, /** * @tc.number : AdvancedNotificationServiceTest_04800 - * @tc.name : AMS_ANS_Cancel_0200 + * @tc.name : ANS_Cancel_0200 * @tc.desc : Test Cancel function when notification no exists */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04800, Function | SmallTest | Level1) @@ -802,7 +781,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04800, /** * @tc.number : AdvancedNotificationServiceTest_04900 - * @tc.name : AMS_ANS_CancelAll_0100 + * @tc.name : ANS_CancelAll_0100 * @tc.desc : Test CancelAll function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04900, Function | SmallTest | Level1) @@ -815,7 +794,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_04900, /** * @tc.number : AdvancedNotificationServiceTest_05000 - * @tc.name : AMS_ANS_Cancel_0100 + * @tc.name : ANS_Cancel_0100 * @tc.desc : Test Cancel function when unremovable is true */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05000, Function | SmallTest | Level1) @@ -833,7 +812,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05000, /** * @tc.number : AdvancedNotificationServiceTest_05100 - * @tc.name : AMS_ANS_AddSlots_0100 + * @tc.name : ANS_AddSlots_0100 * @tc.desc : Test AddSlots function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, Function | SmallTest | Level1) @@ -848,7 +827,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05100, /** * @tc.number : AdvancedNotificationServiceTest_05200 - * @tc.name : AMS_ANS_RemoveSlotByType_0100 + * @tc.name : ANS_RemoveSlotByType_0100 * @tc.desc : Test RemoveSlotByType function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, Function | SmallTest | Level1) @@ -859,7 +838,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05200, /** * @tc.number : AdvancedNotificationServiceTest_05300 - * @tc.name : AMS_ANS_RemoveSlotByType_0200 + * @tc.name : ANS_RemoveSlotByType_0200 * @tc.desc : Test RemoveSlotByType function when no type */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, Function | SmallTest | Level1) @@ -871,7 +850,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05300, /** * @tc.number : AdvancedNotificationServiceTest_05400 - * @tc.name : AMS_ANS_AddSlotGroups_0100 + * @tc.name : ANS_AddSlotGroups_0100 * @tc.desc : Test AddSlotGroups function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05400, Function | SmallTest | Level1) @@ -886,7 +865,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05400, /** * @tc.number : AdvancedNotificationServiceTest_05500 - * @tc.name : AMS_ANS_RemoveSlotGroups_0100 + * @tc.name : ANS_RemoveSlotGroups_0100 * @tc.desc : Test RemoveSlotGroups function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05500, Function | SmallTest | Level1) @@ -899,7 +878,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05500, /** * @tc.number : AdvancedNotificationServiceTest_05600 - * @tc.name : AMS_ANS_GetSlot_0100 + * @tc.name : ANS_GetSlot_0100 * @tc.desc : Test GetSlot function for data */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, Function | SmallTest | Level1) @@ -917,7 +896,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05600, /** * @tc.number : AdvancedNotificationServiceTest_05800 - * @tc.name : AMS_ANS_GetSlotGroup_0100 + * @tc.name : ANS_GetSlotGroup_0100 * @tc.desc : Test GetSlotGroup function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05800, Function | SmallTest | Level1) @@ -936,7 +915,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05800, /** * @tc.number : AdvancedNotificationServiceTest_05900 - * @tc.name : AMS_ANS_SetNotificationBadgeNum_0100 + * @tc.name : ANS_SetNotificationBadgeNum_0100 * @tc.desc : Test SetNotificationBadgeNum function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05900, Function | SmallTest | Level1) @@ -947,7 +926,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_05900, /** * @tc.number : AdvancedNotificationServiceTest_06000 - * @tc.name : AMS_ANS_GetBundleImportance_0100 + * @tc.name : ANS_GetBundleImportance_0100 * @tc.desc : Test GetBundleImportance function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06000, Function | SmallTest | Level1) @@ -959,7 +938,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06000, /** * @tc.number : AdvancedNotificationServiceTest_06100 - * @tc.name : AMS_ANS_SetPrivateNotificationsAllowed_0100 + * @tc.name : ANS_SetPrivateNotificationsAllowed_0100 * @tc.desc : Test SetPrivateNotificationsAllowed function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06100, Function | SmallTest | Level1) @@ -970,7 +949,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06100, /** * @tc.number : AdvancedNotificationServiceTest_06200 - * @tc.name : AMS_ANS_GetPrivateNotificationsAllowed_0100 + * @tc.name : ANS_GetPrivateNotificationsAllowed_0100 * @tc.desc : Test GetPrivateNotificationsAllowed function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06200, Function | SmallTest | Level1) @@ -984,7 +963,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06200, /** * @tc.number : AdvancedNotificationServiceTest_06300 - * @tc.name : AMS_ANS_UpdateSlots_0100 + * @tc.name : ANS_UpdateSlots_0100 * @tc.desc : Test UpdateSlots function when no slot */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06300, Function | SmallTest | Level1) @@ -1000,7 +979,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06300, /** * @tc.number : AdvancedNotificationServiceTest_06400 - * @tc.name : AMS_ANS_UpdateSlots_0200 + * @tc.name : ANS_UpdateSlots_0200 * @tc.desc : Test UpdateSlots function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06400, Function | SmallTest | Level1) @@ -1016,7 +995,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06400, /** * @tc.number : AdvancedNotificationServiceTest_06500 - * @tc.name : AMS_ANS_UpdateSlotGroups_0100 + * @tc.name : ANS_UpdateSlotGroups_0100 * @tc.desc : Test UpdateSlotGroups function when no group */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06500, Function | SmallTest | Level1) @@ -1032,7 +1011,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06500, /** * @tc.number : AdvancedNotificationServiceTest_06600 - * @tc.name : AMS_ANS_UpdateSlotGroups_0200 + * @tc.name : ANS_UpdateSlotGroups_0200 * @tc.desc : Test UpdateSlotGroups function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06600, Function | SmallTest | Level1) @@ -1048,7 +1027,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06600, /** * @tc.number : AdvancedNotificationServiceTest_06800 - * @tc.name : AMS_ANS_SetShowBadgeEnabledForBundle_0100 + * @tc.name : ANS_SetShowBadgeEnabledForBundle_0100 * @tc.desc : Test the SetShowBadgeEnabledForBundle function when the parameter is wrong */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06800, Function | SmallTest | Level1) @@ -1060,7 +1039,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06800, /** * @tc.number : AdvancedNotificationServiceTest_06900 - * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, Function | SmallTest | Level1) @@ -1068,12 +1047,12 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, bool allow = false; EXPECT_EQ((int)advancedNotificationService_->GetShowBadgeEnabledForBundle( new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), allow), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); } /** * @tc.number : AdvancedNotificationServiceTest_07000 - * @tc.name : AMS_ANS_GetActiveNotifications_0100 + * @tc.name : ANS_GetActiveNotifications_0100 * @tc.desc : Test GetActiveNotifications function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07000, Function | SmallTest | Level1) @@ -1084,7 +1063,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07000, /** * @tc.number : AdvancedNotificationServiceTest_07800 - * @tc.name : AMS_ANS_Delete_0100 + * @tc.name : ANS_Delete_0100 * @tc.desc : Test Delete function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07800, Function | SmallTest | Level1) @@ -1095,7 +1074,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07800, /** * @tc.number : AdvancedNotificationServiceTest_07900 - * @tc.name : AMS_ANS_DeleteByBundle_0100 + * @tc.name : ANS_DeleteByBundle_0100 * @tc.desc : Test DeleteByBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07900, Function | SmallTest | Level1) @@ -1107,7 +1086,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_07900, /** * @tc.number : AdvancedNotificationServiceTest_08000 - * @tc.name : AMS_ANS_DeleteAll_0100 + * @tc.name : ANS_DeleteAll_0100 * @tc.desc : Test DeleteAll function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08000, Function | SmallTest | Level1) @@ -1117,7 +1096,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08000, /** * @tc.number : AdvancedNotificationServiceTest_08300 - * @tc.name : AMS_ANS_Subscribe_0100 + * @tc.name : ANS_Subscribe_0100 * @tc.desc : Test Subscribe function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08300, Function | SmallTest | Level1) @@ -1130,7 +1109,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08300, /** * @tc.number : AdvancedNotificationServiceTest_08600 - * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0200 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0200 * @tc.desc : Test GetShowBadgeEnabledForBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08600, Function | SmallTest | Level1) @@ -1148,7 +1127,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08600, /** * @tc.number : AdvancedNotificationServiceTest_08700 - * @tc.name : AMS_ANS_GetSlotByType_0100 + * @tc.name : ANS_GetSlotByType_0100 * @tc.desc : Test GetSlotByType function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08700, Function | SmallTest | Level1) @@ -1161,7 +1140,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08700, /** * @tc.number : AdvancedNotificationServiceTest_08900 - * @tc.name : AMS_ANS_GetSlotGroups_0100 + * @tc.name : ANS_GetSlotGroups_0100 * @tc.desc : Test GetSlotGroups function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08900, Function | SmallTest | Level1) @@ -1178,7 +1157,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_08900, /** * @tc.number : AdvancedNotificationServiceTest_09000 - * @tc.name : AMS_ANS_GetAllActiveNotifications_0100 + * @tc.name : ANS_GetAllActiveNotifications_0100 * @tc.desc : Test GetAllActiveNotifications function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09000, Function | SmallTest | Level1) @@ -1189,7 +1168,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09000, /** * @tc.number : AdvancedNotificationServiceTest_09200 - * @tc.name : AMS_ANS_SetNotificationsEnabledForAllBundles_0200 + * @tc.name : ANS_SetNotificationsEnabledForAllBundles_0200 * @tc.desc : Test SetNotificationsEnabledForAllBundles function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09200, Function | SmallTest | Level1) @@ -1200,7 +1179,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09200, /** * @tc.number : AdvancedNotificationServiceTest_09300 - * @tc.name : AMS_ANS_SetNotificationsEnabledForSpecialBundle_0100 + * @tc.name : ANS_SetNotificationsEnabledForSpecialBundle_0100 * @tc.desc : Test SetNotificationsEnabledForSpecialBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, Function | SmallTest | Level1) @@ -1214,7 +1193,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09300, /** * @tc.number : AdvancedNotificationServiceTest_09600 - * @tc.name : AMS_ANS_IsAllowedNotify_0200 + * @tc.name : ANS_IsAllowedNotify_0200 * @tc.desc : Test IsAllowedNotify function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, Function | SmallTest | Level1) @@ -1228,7 +1207,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09600, /** * @tc.number : AdvancedNotificationServiceTest_09700 - * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0100 + * @tc.name : ANS_IsSpecialBundleAllowedNotify_0100 * @tc.desc : Test IsSpecialBundleAllowedNotify function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09700, Function | SmallTest | Level1) @@ -1242,7 +1221,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09700, /** * @tc.number : AdvancedNotificationServiceTest_09800 - * @tc.name : AMS_ANS_IsSpecialBundleAllowedNotify_0200 + * @tc.name : ANS_IsSpecialBundleAllowedNotify_0200 * @tc.desc : Test IsSpecialBundleAllowedNotify function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, Function | SmallTest | Level1) @@ -1251,12 +1230,12 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, bool allowed = true; EXPECT_EQ((int)advancedNotificationService_->IsSpecialBundleAllowedNotify( new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); } /** * @tc.number : AdvancedNotificationServiceTest_09900 - * @tc.name : AMS_ANS_GetSlotsByBundle_0200 + * @tc.name : ANS_GetSlotsByBundle_0200 * @tc.desc : Test GetSlotsByBundle function when no bundle */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, Function | SmallTest | Level1) @@ -1264,7 +1243,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09900, std::vector> slots; EXPECT_EQ((int)advancedNotificationService_->GetSlotsByBundle( new NotificationBundleOption(TEST_DEFUALT_BUNDLE, NON_SYSTEM_APP_UID), slots), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); } inline std::shared_ptr MakePixelMap(int32_t width, int32_t height) @@ -1291,7 +1270,7 @@ inline std::shared_ptr MakePixelMap(int32_t width, int32_t height) /** * @tc.number : AdvancedNotificationServiceTest_10000 - * @tc.name : AMS_ANS_Publish_With_PixelMap + * @tc.name : ANS_Publish_With_PixelMap * @tc.desc : Publish a notification with pixelMap. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10000, Function | SmallTest | Level1) @@ -1323,7 +1302,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10000, /** * @tc.number : AdvancedNotificationServiceTest_10100 - * @tc.name : AMS_ANS_Publish_With_PixelMap_Oversize_00100 + * @tc.name : ANS_Publish_With_PixelMap_Oversize_00100 * @tc.desc : Publish a notification with oversize pixelMap. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10100, Function | SmallTest | Level1) @@ -1355,7 +1334,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10100, /** * @tc.number : AdvancedNotificationServiceTest_10200 - * @tc.name : AMS_ANS_Publish_With_PixelMap_Oversize_00200 + * @tc.name : ANS_Publish_With_PixelMap_Oversize_00200 * @tc.desc : Publish a notification with oversize pixelMap. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10200, Function | SmallTest | Level1) @@ -1385,5 +1364,267 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10200, EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_ANS_ICON_OVER_SIZE); } +/** + * @tc.number : AdvancedNotificationServiceTest_10300 + * @tc.name : ANS_Cancel_By_Group_10300 + * @tc.desc : Cancel notification by group name. + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10300, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(1); + ASSERT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("label"); + std::shared_ptr normalContent = std::make_shared(); + ASSERT_NE(normalContent, nullptr); + normalContent->SetText("text"); + normalContent->SetTitle("title"); + std::shared_ptr content = std::make_shared(normalContent); + ASSERT_NE(content, nullptr); + req->SetContent(content); + std::string groupName = "group"; + req->SetGroupName(groupName); + EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_OK); + EXPECT_EQ(advancedNotificationService_->CancelGroup(groupName), (int)ERR_OK); + SleepForFC(); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_10400 + * @tc.name : ANS_Remove_By_Group_10400 + * @tc.desc : Remove notification by group name. + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10400, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(1); + ASSERT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("label"); + std::shared_ptr normalContent = std::make_shared(); + ASSERT_NE(normalContent, nullptr); + normalContent->SetText("text"); + normalContent->SetTitle("title"); + std::shared_ptr content = std::make_shared(normalContent); + ASSERT_NE(content, nullptr); + req->SetContent(content); + std::string groupName = "group"; + req->SetGroupName(groupName); + EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_OK); + sptr bundleOption = new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID); + EXPECT_EQ(advancedNotificationService_->RemoveGroupByBundle(bundleOption, groupName), (int)ERR_OK); + SleepForFC(); +} + +/** + * @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); + EXPECT_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); + EXPECT_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); + EXPECT_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); + EXPECT_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); + + EXPECT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + EXPECT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + EXPECT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::NONE); + EXPECT_EQ(result->GetBeginDate(), 0); + EXPECT_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); + EXPECT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + EXPECT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + EXPECT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::ONCE); + EXPECT_EQ(result->GetBeginDate(), beginDate); + EXPECT_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); + + EXPECT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + sptr result = nullptr; + EXPECT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + EXPECT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + EXPECT_EQ(result->GetBeginDate(), beginDate); + EXPECT_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); + EXPECT_EQ((int)advancedNotificationService_->SetDoNotDisturbDate(date), (int)ERR_OK); + + sptr result = nullptr; + EXPECT_EQ((int)advancedNotificationService_->GetDoNotDisturbDate(result), (int)ERR_OK); + ASSERT_NE(result, nullptr); + EXPECT_EQ(result->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::CLEARLY); + EXPECT_EQ(result->GetBeginDate(), beginDate); + EXPECT_EQ(result->GetEndDate(), endDate); +} + +/** + * @tc.number : ANS_Publish_01500 + * @tc.name : ANSPublish01500 + * @tc.desc : publish a continuous task notification + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11000, Function | SmallTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + EXPECT_EQ(advancedNotificationService_->PublishContinuousTaskNotification(req), (int)ERR_OK); + SleepForFC(); +} + +/** + * @tc.number : ANS_Publish_01600 + * @tc.name : ANSPublish01600 + * @tc.desc : publish a continuous task notification + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11100, Function | SmallTest | Level1) +{ + sptr req = new NotificationRequest(); + EXPECT_NE(req, nullptr); + req->SetSlotType(NotificationConstant::SlotType::OTHER); + req->SetLabel("req's label"); + EXPECT_EQ(advancedNotificationService_->PublishContinuousTaskNotification(req), (int)ERR_ANS_NOT_SYSTEM_SERVICE); + SleepForFC(); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_11200 + * @tc.name : ANS_Cancel_0300 + * @tc.desc : public two notification to cancel one of them + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11200, Function | SmallTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + std::string label = "testLabel"; + { + sptr req = new NotificationRequest(1); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + EXPECT_EQ(advancedNotificationService_->PublishContinuousTaskNotification(req), (int)ERR_OK); + } + EXPECT_EQ(advancedNotificationService_->CancelContinuousTaskNotification(label, 1), (int)ERR_OK); +} + +/** + * @tc.number : AdvancedNotificationServiceTest_11300 + * @tc.name : ANS_Cancel_0400 + * @tc.desc : public two notification to cancel one of them + */ +HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11300, Function | SmallTest | Level1) +{ + IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); + std::string label = "testLabel"; + { + sptr req = new NotificationRequest(1); + req->SetSlotType(NotificationConstant::OTHER); + req->SetLabel(label); + EXPECT_EQ(advancedNotificationService_->PublishContinuousTaskNotification(req), (int)ERR_OK); + } + IPCSkeleton::SetCallingUid(SYSTEM_APP_UID); + EXPECT_EQ( + advancedNotificationService_->CancelContinuousTaskNotification(label, 1), (int)ERR_ANS_NOT_SYSTEM_SERVICE); +} } // namespace Notification -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp index 69f6b11f28cf7037f77ac42a0d62147066ed9993..4cde76e92036d47a6ae466ccd74a5c9c11a8cca1 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -25,18 +25,17 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class BundleManagerHelperTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; }; /** * @tc.number : BundleManagerHelperTest_00100 - * @tc.name : AMS_ANS_GetBundleNameByUid_0100 + * @tc.name : ANS_GetBundleNameByUid_0100 * @tc.desc : Test GetBundleNameByUid function */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | SmallTest | Level1) @@ -48,7 +47,7 @@ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00100, Function | Smal /** * @tc.number : BundleManagerHelperTest_00200 - * @tc.name : AMS_ANS_IsSystemApp_0100 + * @tc.name : ANS_IsSystemApp_0100 * @tc.desc : Test IsSystemApp function */ HWTEST_F(BundleManagerHelperTest, BundleManagerHelperTest_00200, Function | SmallTest | Level1) diff --git a/services/ans/test/unittest/mock/blob.cpp b/services/ans/test/unittest/mock/blob.cpp old mode 100755 new mode 100644 index 93d2c34700f2b1d15a38ad135a6299d3450168bb..540888d0f6f0bddd56e2f06b1af89b6658802a38 --- a/services/ans/test/unittest/mock/blob.cpp +++ b/services/ans/test/unittest/mock/blob.cpp @@ -17,7 +17,6 @@ #include "blob.h" #include -#include "log_print.h" namespace OHOS { namespace DistributedKv { @@ -111,7 +110,6 @@ bool Blob::Empty() const uint8_t Blob::operator[](size_t n) const { if (n >= Size()) { - ZLOGE("Trying to get a out-of-range Blob member."); return 0; } return blob_[n]; diff --git a/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp index d755b0151ac19b60f4e18e540bc2c2488c1895fc..8e348f6da1da13a12045515e8a0970e3bbbeb32f 100644 --- a/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp +++ b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp @@ -16,7 +16,6 @@ #define LOG_TAG "DistributedKvDataManager" #include "distributed_kv_data_manager.h" -#include "constant.h" #include "mock_single_kv_store.h" #include "types.h" @@ -28,22 +27,20 @@ DistributedKvDataManager::DistributedKvDataManager() DistributedKvDataManager::~DistributedKvDataManager() {} -void DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, - std::function)> callback) +Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const AppId &appId, const StoreId &storeId, + std::shared_ptr &kvStore) { - std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - Status status = Status::SUCCESS; - std::unique_ptr proxyTmp = std::make_unique(); - callback(status, std::move(proxyTmp)); + std::string storeIdTmp = storeId.storeId; + kvStore = std::make_shared(); + return Status::SUCCESS; } -Status DistributedKvDataManager::CloseKvStore( - const AppId &appId, const StoreId &storeId, std::unique_ptr kvStorePtr) +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, const StoreId &storeId) { return Status::SUCCESS; } -Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::unique_ptr kvStorePtr) +Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_ptr &kvStorePtr) { return Status::SUCCESS; } diff --git a/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h b/services/ans/test/unittest/mock/include/mock_ipc_skeleton.h old mode 100755 new mode 100644 diff --git a/services/ans/test/unittest/mock/include/mock_single_kv_store.h b/services/ans/test/unittest/mock/include/mock_single_kv_store.h index f32d46b6d956a2f74d36fe83ab828276143b4c3a..18a139986b2bbd73a9abc763e47be1781e347e09 100644 --- a/services/ans/test/unittest/mock/include/mock_single_kv_store.h +++ b/services/ans/test/unittest/mock/include/mock_single_kv_store.h @@ -39,23 +39,22 @@ public: virtual Status GetEntriesWithQuery(const DataQuery &query, std::vector &entries) const override; - virtual void GetResultSet( - const Key &prefixKey, std::function)> callback) const override; + virtual Status GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const override; - virtual void GetResultSetWithQuery(const std::string &query, - std::function)> callback) const override; + virtual Status GetResultSetWithQuery(const std::string &query, + std::shared_ptr &resultSet) const override; - virtual void GetResultSetWithQuery( - const DataQuery &query, std::function)> callback) const override; + virtual Status GetResultSetWithQuery(const DataQuery &query, + std::shared_ptr &resultSet) const override; - virtual Status CloseResultSet(std::unique_ptr resultSet) override; + virtual Status CloseResultSet(std::shared_ptr &resultSet) override; virtual Status GetCountWithQuery(const std::string &query, int &result) const override; virtual Status GetCountWithQuery(const DataQuery &query, int &result) const override; virtual Status Sync( - const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs = 0) override; + const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs = 0) override; virtual Status RemoveDeviceData(const std::string &device) override; @@ -96,8 +95,21 @@ public: virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const override; + virtual Status SyncWithCondition(const std::vector &deviceIds, SyncMode mode, + const DataQuery &query) override; + + virtual Status SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + virtual Status UnSubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) override; + + Status GetKvStoreSnapshot(std::shared_ptr observer, + std::shared_ptr &snapshot) const override; + + Status ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) override; + + Status Clear() override; protected: - KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) override; + KVSTORE_API virtual Status Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) override; }; } // namespace DistributedKv } // namespace OHOS diff --git a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp index efde9364abf099b910403f6fb44b7e646bb97663..53a462d00aa2bda733fa2ef849e3bc4a9532e31f 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace Notification { - BundleManagerHelper::BundleManagerHelper() {} @@ -53,5 +52,11 @@ void BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +bool BundleManagerHelper::GetDistributedNotificationEnabled(const std::string &bundleName, const int userId) +{ + return true; +} +#endif } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/mock/mock_event_handler.cpp b/services/ans/test/unittest/mock/mock_event_handler.cpp index 12a7f65b9d4e00f3c9c65a4a8668e162960cb723..1bdf27e03013d421d5f9d2c1309a586a39401286 100644 --- a/services/ans/test/unittest/mock/mock_event_handler.cpp +++ b/services/ans/test/unittest/mock/mock_event_handler.cpp @@ -14,12 +14,9 @@ */ #include "event_handler.h" -#include "event_handler_utils.h" -#include namespace OHOS { namespace AppExecFwk { - std::shared_ptr EventHandler::Current() { const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); diff --git a/services/ans/test/unittest/mock/mock_single_kv_store.cpp b/services/ans/test/unittest/mock/mock_single_kv_store.cpp index 85aed3fef5427378195420cc7428132c0a21d60d..3f6d34b42d608986da4bfe80f1b132c3f945d069 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace DistributedKv { - Status AnsTestSingleKvStore::GetEntries(const Key &prefixKey, std::vector &entries) const { return Status::SUCCESS; @@ -34,19 +33,24 @@ Status AnsTestSingleKvStore::GetEntriesWithQuery(const DataQuery &query, std::ve return Status::SUCCESS; } -void AnsTestSingleKvStore::GetResultSet( - const Key &prefixKey, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -void AnsTestSingleKvStore::GetResultSetWithQuery( - const std::string &query, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSetWithQuery(const std::string &query, + std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -void AnsTestSingleKvStore::GetResultSetWithQuery( - const DataQuery &query, std::function)> callback) const -{} +Status AnsTestSingleKvStore::GetResultSetWithQuery(const DataQuery &query, + std::shared_ptr &resultSet) const +{ + return Status::SUCCESS; +} -Status AnsTestSingleKvStore::CloseResultSet(std::unique_ptr resultSet) +Status AnsTestSingleKvStore::CloseResultSet(std::shared_ptr &resultSet) { return Status::SUCCESS; } @@ -62,7 +66,7 @@ Status AnsTestSingleKvStore::GetCountWithQuery(const DataQuery &query, int &resu } Status AnsTestSingleKvStore::Sync( - const std::vector &deviceIdList, const SyncMode &mode, uint32_t allowedDelayMs) + const std::vector &deviceIds, SyncMode mode, uint32_t allowedDelayMs) { return Status::SUCCESS; } @@ -165,10 +169,41 @@ Status AnsTestSingleKvStore::GetSecurityLevel(SecurityLevel &securityLevel) cons return Status::SUCCESS; } -Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, sptr &output) +Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam, KvParam &output) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SyncWithCondition(const std::vector &deviceIds, SyncMode mode, + const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::SubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) +{ + return Status::SUCCESS; +} + +Status AnsTestSingleKvStore::UnSubscribeWithQuery(const std::vector &deviceIds, const DataQuery &query) { return Status::SUCCESS; } +Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, + std::shared_ptr &snapshot) const +{ + return Status::NOT_SUPPORT; +} + +Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &snapshot) +{ + return Status::NOT_SUPPORT; +} + +Status AnsTestSingleKvStore::Clear() +{ + return Status::NOT_SUPPORT; +} } // namespace DistributedKv -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index 36f044d30881b80593d47fea34d89f424adeefc2..e4857df84887d65b3e6b5bf94f2146cd7b9e7e28 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -21,15 +21,16 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class NotificationPreferencesDatabaseTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; const std::string bundleName_ = "bundleName"; + const int bundleUid_ = 2001; + int32_t userId = 100; std::unique_ptr preferncesDB_ = std::make_unique(); }; @@ -46,7 +47,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00100, Functi sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); slots.push_back(slot1); slots.push_back(slot2); - EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); + EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, bundleUid_, slots)); } /** @@ -61,7 +62,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00200, Functi sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); slots.push_back(slot1); slots.push_back(slot2); - EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(std::string(), slots)); + EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(std::string(), 0, slots)); } /** @@ -72,7 +73,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00200, Functi HWTEST_F(NotificationPreferencesDatabaseTest, PutSlotsToDisturbeDB_00300, Function | SmallTest | Level1) { std::vector> slots; - EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); + EXPECT_FALSE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, bundleUid_, slots)); } /** @@ -86,7 +87,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00100, Funct std::vector> groups; groups.push_back(slotGroup); - EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); + EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, bundleUid_, groups)); } /** @@ -99,7 +100,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00200, Funct sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector> groups; groups.push_back(slotGroup); - EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(std::string(), groups)); + EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(std::string(), 0, groups)); } /** @@ -110,7 +111,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00200, Funct HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00300, Function | SmallTest | Level1) { std::vector> groups; - EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); + EXPECT_FALSE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, bundleUid_, groups)); } /** @@ -120,8 +121,11 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutGroupsToDisturbeDB_00300, Funct */ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleName_, true)); - EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleName_, false)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleInfo, true)); + EXPECT_TRUE(preferncesDB_->PutShowBadge(bundleInfo, false)); } /** @@ -131,7 +135,9 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00100, Function | Sma */ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00200, Function | SmallTest | Level1) { - EXPECT_FALSE(preferncesDB_->PutShowBadge(std::string(), false)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(std::string()); + EXPECT_FALSE(preferncesDB_->PutShowBadge(bundleInfo, false)); } /** @@ -141,18 +147,22 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutShowBadge_00200, Function | Sma */ HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00100, Function | SmallTest | Level1) { + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE( - preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); + preferncesDB_->PutImportance(bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); EXPECT_TRUE( - preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_MIN)); + preferncesDB_->PutImportance(bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_MIN)); EXPECT_TRUE( - preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_LOW)); + preferncesDB_->PutImportance(bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_LOW)); EXPECT_TRUE(preferncesDB_->PutImportance( - bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_DEFAULT)); + bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_DEFAULT)); EXPECT_TRUE( - preferncesDB_->PutImportance(bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_HIGH)); + preferncesDB_->PutImportance(bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_HIGH)); EXPECT_TRUE(preferncesDB_->PutImportance( - bundleName_, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_UNDEFINED)); + bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_UNDEFINED)); } /** @@ -162,8 +172,12 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00100, Function | Sm */ HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00200, Function | SmallTest | Level1) { - EXPECT_FALSE(preferncesDB_->PutImportance( - std::string(), OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(std::string()); + bundleInfo.SetBundleUid(0); + + EXPECT_FALSE( + preferncesDB_->PutImportance(bundleInfo, OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE)); } /** @@ -173,8 +187,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00200, Function | Sm */ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00100, Function | SmallTest | Level1) { - - EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleName_, 0)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleInfo, 0)); } /** @@ -184,7 +200,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00100, Function */ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00200, Function | SmallTest | Level1) { - EXPECT_FALSE(preferncesDB_->PutTotalBadgeNums(std::string(), 0)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(std::string()); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_FALSE(preferncesDB_->PutTotalBadgeNums(bundleInfo, 0)); } /** @@ -194,8 +213,11 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00200, Function */ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); - EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleInfo, true)); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleInfo, true)); } /** @@ -205,7 +227,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_001 */ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_00200, Function | SmallTest | Level1) { - EXPECT_FALSE(preferncesDB_->PutPrivateNotificationsAllowed(std::string(), false)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(std::string()); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_FALSE(preferncesDB_->PutPrivateNotificationsAllowed(bundleInfo, false)); } /** @@ -215,8 +240,11 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutPrivateNotificationsAllowed_002 */ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleName_, true)); - EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleName_, false)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, true)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, false)); } /** @@ -226,7 +254,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_0 */ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_00200, Function | SmallTest | Level1) { - EXPECT_FALSE(preferncesDB_->PutNotificationsEnabledForBundle(std::string(), false)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(std::string()); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_FALSE(preferncesDB_->PutNotificationsEnabledForBundle(bundleInfo, false)); } /** @@ -236,22 +267,76 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabledForBundle_0 */ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(true)); - EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(false)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(userId, true)); + EXPECT_TRUE(preferncesDB_->PutNotificationsEnabled(userId, false)); +} + +/** + * @tc.number : PutDoNotDisturbDate_00100 + * @tc.name : + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is NONE, return is true. + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00100, Function | SmallTest | Level1) +{ + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); +} + +/** + * @tc.number : PutDoNotDisturbDate_00200 + * @tc.name : + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is ONCE, return is true. + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00200, Function | SmallTest | Level1) +{ + 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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); +} + +/** + * @tc.number : PutDoNotDisturbDate_00300 + * @tc.name : + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is DAILY, return is true. + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00300, Function | SmallTest | Level1) +{ + 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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** - * @tc.number : PutDisturbMode_00100 + * @tc.number : PutDoNotDisturbDate_00400 * @tc.name : - * @tc.desc : Put disturbe mode into disturbe DB, return is true. + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is CLEARLY, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00400, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS)); - EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALL)); - EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_NONE)); - EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_PRIORITY)); - EXPECT_TRUE(preferncesDB_->PutDisturbMode(OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_UNKNOWN)); + 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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); + + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** @@ -261,7 +346,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_00100, Function | S */ HWTEST_F(NotificationPreferencesDatabaseTest, ParseFromDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleName_, true)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutPrivateNotificationsAllowed(bundleInfo, true)); NotificationPreferencesInfo info; EXPECT_TRUE(preferncesDB_->ParseFromDisturbeDB(info)); } @@ -283,7 +371,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveAllDataFromDisturbeDB_00100, */ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveBundleFromDisturbeDB_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleName_, 0)); + NotificationPreferencesInfo::BundleInfo bundleInfo; + bundleInfo.SetBundleName(bundleName_); + bundleInfo.SetBundleUid(bundleUid_); + EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleInfo, 0)); EXPECT_EQ(true, preferncesDB_->RemoveBundleFromDisturbeDB(bundleName_)); } @@ -307,7 +398,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveSlotFromDisturbeDB_00100, Fu std::vector> slots; sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); slots.push_back(slot1); - EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, slots)); + EXPECT_TRUE(preferncesDB_->PutSlotsToDisturbeDB(bundleName_, bundleUid_, slots)); EXPECT_TRUE(preferncesDB_->RemoveSlotFromDisturbeDB( bundleName_, OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION)); @@ -334,7 +425,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, RemoveGroupsFromDisturbeDB_00100, sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector> groups; groups.push_back(slotGroup); - EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, groups)); + EXPECT_TRUE(preferncesDB_->PutGroupsToDisturbeDB(bundleName_, bundleUid_, groups)); std::vector groupIds; groupIds.push_back("id"); EXPECT_TRUE(preferncesDB_->RemoveGroupsFromDisturbeDB(bundleName_, groupIds)); @@ -387,7 +478,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, GetKvStore_00100, Function | Small /** * @tc.name : CheckKvStore_00100 - * @tc.number : + * @tc.number : * @tc.desc : Check disturbe DB is exsit, return is true. */ HWTEST_F(NotificationPreferencesDatabaseTest, CheckKvStore_00100, Function | SmallTest | Level1) @@ -402,7 +493,6 @@ HWTEST_F(NotificationPreferencesDatabaseTest, CheckKvStore_00100, Function | Sma */ HWTEST_F(NotificationPreferencesDatabaseTest, PutBundlePropertyValueToDisturbeDB_00100, Function | SmallTest | Level1) { - NotificationPreferencesInfo::BundleInfo info; EXPECT_EQ(true, preferncesDB_->PutBundlePropertyValueToDisturbeDB(info)); } @@ -416,7 +506,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, ChangeSlotToEntry_00100, Function { sptr slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); std::vector entries; - EXPECT_TRUE(preferncesDB_->SlotToEntry(bundleName_, slot, entries)); + EXPECT_TRUE(preferncesDB_->SlotToEntry(bundleName_, bundleUid_, slot, entries)); } /** @@ -428,7 +518,8 @@ HWTEST_F(NotificationPreferencesDatabaseTest, ChangeGroupToEntry_00100, Function { sptr slotGroup = new NotificationSlotGroup("id", "name"); std::vector entries; - EXPECT_TRUE(preferncesDB_->GroupToEntry(bundleName_, slotGroup, entries)); + + EXPECT_TRUE(preferncesDB_->GroupToEntry(bundleName_, bundleUid_, slotGroup, entries)); } /** @@ -438,8 +529,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, ChangeGroupToEntry_00100, Function */ HWTEST_F(NotificationPreferencesDatabaseTest, CheckBundle_00100, Function | SmallTest | Level1) { - EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName_)); + EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName_, bundleUid_)); } - } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index f2121538389d08dec54c8bb30f75ccbf7caf4f39..c909c9b04fae979823be2b5321d32466c6ede70a 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -22,12 +22,11 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class NotificationPreferencesTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; void TearDown(); void TestAddNotificationSlot(); @@ -127,7 +126,6 @@ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00400, Function | Sma */ HWTEST_F(NotificationPreferencesTest, AddNotificationSlots_00500, Function | SmallTest | Level1) { - sptr slot1 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr slot2 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); @@ -1019,7 +1017,7 @@ HWTEST_F(NotificationPreferencesTest, NotificationPreferencesTest_02900, Functio */ HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); } /** @@ -1029,36 +1027,98 @@ HWTEST_F(NotificationPreferencesTest, SetNotificationsEnabled_00100, Function | */ HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(true), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); bool enable = false; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(enable), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); EXPECT_TRUE(enable); } /** - * @tc.number : SetDisturbMode_00100 + * @tc.number : SetDoNotDisturbDate_00100 * @tc.name : * @tc.desc : Set disturbe mode into disturbe DB, return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, SetDisturbMode_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, SetDoNotDisturbDate_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_ALL), - (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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); + + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); } /** - * @tc.number : GetDisturbMode_00100 + * @tc.number : GetDoNotDisturbDate_00100 * @tc.name : * @tc.desc : Get disturbe mode from disturbe DB, return is ERR_OK */ -HWTEST_F(NotificationPreferencesTest, GetDisturbMode_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00100, Function | SmallTest | Level1) { - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_ALL), - (int)ERR_OK); - NotificationConstant::DisturbMode mode; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDisturbMode(mode), (int)ERR_OK); - EXPECT_EQ((int)NotificationConstant::DisturbMode::ALLOW_ALL, mode); + 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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); + + sptr getDate; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption_, getDate), (int)ERR_OK); + EXPECT_EQ(getDate->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + EXPECT_EQ(getDate->GetBeginDate(), beginDate); + EXPECT_EQ(getDate->GetEndDate(), endDate); +} + +/** + * @tc.number : GetNotificationsEnabled_00200 + * @tc.name : + * @tc.desc : Same user can get enable setting, different user can not get. + */ +HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00200, Function | SmallTest | Level1) +{ + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetNotificationsEnabled(bundleOption_, true), (int)ERR_OK); + bool enable = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); + EXPECT_TRUE(enable); + + enable = false; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetNotificationsEnabled(bundleOption_, enable), (int)ERR_OK); + EXPECT_FALSE(enable); } +/** + * @tc.number : GetDoNotDisturbDate_00200 + * @tc.name : + * @tc.desc : Same user can get DoNotDisturbDate setting, different user can not get. + */ +HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00200, Function | SmallTest | Level1) +{ + 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(); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); + + sptr getDate; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption_, getDate), (int)ERR_OK); + EXPECT_EQ(getDate->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + EXPECT_EQ(getDate->GetBeginDate(), beginDate); + EXPECT_EQ(getDate->GetEndDate(), endDate); + + sptr getExsitDate; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate( + noExsitbundleOption_, getExsitDate), (int)ERR_ANS_INVALID_PARAM); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/notification_slot_filter_test.cpp b/services/ans/test/unittest/notification_slot_filter_test.cpp index 1d8582a23e6c8eca63451a03f117f48042c1b5f1..7cc73fa00702dd8767f0aca584dab062815b25ab 100644 --- a/services/ans/test/unittest/notification_slot_filter_test.cpp +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -21,18 +21,17 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class NotificationSlotFilterTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; + void SetUp() {}; + void TearDown() {}; }; /** * @tc.number : NotificationSlotFilterTest_00100 - * @tc.name : AMS_ANS_OnStart_0100 + * @tc.name : ANS_OnStart_0100 * @tc.desc : Test OnStart function */ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00100, Function | SmallTest | Level1) @@ -43,7 +42,7 @@ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00100, Function /** * @tc.number : NotificationSlotFilterTest_00200 - * @tc.name : AMS_ANS_OnStop_0100 + * @tc.name : ANS_OnStop_0100 * @tc.desc : Test OnStop function */ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00200, Function | SmallTest | Level1) @@ -54,7 +53,7 @@ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00200, Function /** * @tc.number : NotificationSlotFilterTest_00300 - * @tc.name : AMS_ANS_OnPublish_0100 + * @tc.name : ANS_OnPublish_0100 * @tc.desc : Test OnPublish function */ HWTEST_F(NotificationSlotFilterTest, NotificationSlotFilterTest_00300, Function | SmallTest | Level1) diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp index 2c62f96f8bb643e9d1c1268b4736992d4db5c8d6..eb8d6f743b304b824deb98ca8738bc223a9594dd 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -25,7 +25,6 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class NotificationSubscriberManagerTest : public testing::Test { public: static void SetUpTestCase(); @@ -36,15 +35,15 @@ public: private: class TestAnsSubscriber : public NotificationSubscriber { public: - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + void OnConnected() override {} - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + void OnDisconnected() override {} void OnDied() override {} void OnUpdate(const std::shared_ptr &sortingMap) override {} - void OnDisturbModeChanged(int disturbMode) override + void OnDoNotDisturbDateChange(const std::shared_ptr &date) override {} void OnCanceled(const std::shared_ptr &request) override {} @@ -92,7 +91,7 @@ void NotificationSubscriberManagerTest::TearDown() /** * @tc.number : NotificationSubscriberManagerTest_001 - * @tc.name : AMS_ANS_NotifyUpdated_0100 + * @tc.name : ANS_NotifyUpdated_0100 * @tc.desc : Test NotifyUpdated function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_001, Function | SmallTest | Level1) @@ -104,18 +103,19 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_002 - * @tc.name : AMS_ANS_NotifyDisturbModeChanged_0100 + * @tc.name : ANS_NotifyDisturbModeChanged_0100 * @tc.desc : Test NotifyDisturbModeChanged function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_002, Function | SmallTest | Level1) { - NotificationConstant::DisturbMode mode; - notificationSubscriberManager_->NotifyDisturbModeChanged(mode); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + notificationSubscriberManager_->NotifyDoNotDisturbDateChanged(date); } /** * @tc.number : NotificationSubscriberManagerTest_003 - * @tc.name : AMS_ANS_NotifyConsumed_0100 + * @tc.name : ANS_NotifyConsumed_0100 * @tc.desc : Test NotifyConsumed function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_003, Function | SmallTest | Level1) @@ -129,7 +129,7 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_004 - * @tc.name : AMS_ANS_NotifyCanceled_0100 + * @tc.name : ANS_NotifyCanceled_0100 * @tc.desc : Test NotifyCanceled function. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_004, Function | SmallTest | Level1) @@ -144,7 +144,7 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_005 - * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.name : ANS_AddSubscriber_0100 * @tc.desc : Test AddSubscriber function, return is ERR_OK. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_005, Function | SmallTest | Level1) @@ -157,7 +157,7 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_006 - * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.name : ANS_AddSubscriber_0100 * @tc.desc : Test AddSubscriber function when subscriber is nullptr, return is ERR_ANS_INVALID_PARAM. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_006, Function | SmallTest | Level1) @@ -168,7 +168,7 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_007 - * @tc.name : AMS_ANS_RemoveSubscriber_0100 + * @tc.name : ANS_RemoveSubscriber_0100 * @tc.desc : Test RemoveSubscriber function, return is ERR_OK. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_007, Function | SmallTest | Level1) @@ -180,7 +180,7 @@ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_00 /** * @tc.number : NotificationSubscriberManagerTest_006 - * @tc.name : AMS_ANS_AddSubscriber_0100 + * @tc.name : ANS_AddSubscriber_0100 * @tc.desc : Test RemoveSubscriber function when subscriber is nullptr, return is ERR_ANS_INVALID_PARAM. */ HWTEST_F(NotificationSubscriberManagerTest, NotificationSubscriberManagerTest_008, Function | SmallTest | Level1) diff --git a/services/ans/test/unittest/permission_filter_test.cpp b/services/ans/test/unittest/permission_filter_test.cpp index 6472f51756f1afe51ebbc294500c466261d2b4d3..f1010e09320c16b8a054c734e50864c2334d8af9 100644 --- a/services/ans/test/unittest/permission_filter_test.cpp +++ b/services/ans/test/unittest/permission_filter_test.cpp @@ -26,11 +26,10 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - class PermissionFilterTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; + static void SetUpTestCase() {}; + static void TearDownTestCase() {}; void SetUp(); void TearDown(); }; @@ -47,7 +46,7 @@ void PermissionFilterTest::TearDown() /** * @tc.number : PermissionFilterTest_00100 - * @tc.name : AMS_ANS_OnStop_0100 + * @tc.name : ANS_OnStop_0100 * @tc.desc : Test OnStart function */ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00100, Function | SmallTest | Level1) @@ -58,7 +57,7 @@ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00100, Function | SmallTest /** * @tc.number : PermissionFilterTest_00200 - * @tc.name : AMS_ANS_OnStop_0100 + * @tc.name : ANS_OnStop_0100 * @tc.desc : Test OnStop function */ HWTEST_F(PermissionFilterTest, PermissionFilterTest_00200, Function | SmallTest | Level1) diff --git a/services/distributed/BUILD.gn b/services/distributed/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..22c67f691853cbde82f7a4662f034882ef9b87ad --- /dev/null +++ b/services/distributed/BUILD.gn @@ -0,0 +1,60 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") + +config("ans_distributed_config") { + include_dirs = [ + "${services_path}/distributed/include", + "//utils/native/base/include", + ] +} + +ohos_shared_library("libans_distributed") { + sources = [ + "src/distributed_database.cpp", + "src/distributed_database_callback.cpp", + "src/distributed_device_callback.cpp", + "src/distributed_flow_control.cpp", + "src/distributed_notification_manager.cpp", + "src/distributed_preferences.cpp", + "src/distributed_preferences_database.cpp", + "src/distributed_preferences_info.cpp", + "src/distributed_screen_status_manager.cpp", + ] + + include_dirs = [ "include" ] + + configs = [ + ":ans_distributed_config", + "${core_path}:public_ans_core_config", + "${frameworks_path}/ans/native:ans_innerkits_public_config", + ] + + deps = [ "${core_path}:ans_core" ] + + external_deps = [ + "ability_runtime:want", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimedia_image_standard:image_native", + "utils_base:utils", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/services/distributed/include/distributed_database.h b/services/distributed/include/distributed_database.h new file mode 100644 index 0000000000000000000000000000000000000000..6286769a00ce929d2d378975bb0a5148bc771d2d --- /dev/null +++ b/services/distributed/include/distributed_database.h @@ -0,0 +1,71 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_H + +#include +#include +#include +#include + +#include "distributed_kv_data_manager.h" +#include "singleton.h" + +#include "distributed_database_callback.h" +#include "distributed_device_callback.h" +#include "distributed_flow_control.h" + +namespace OHOS { +namespace Notification { +class DistributedDatabase : private DistributedFlowControl { +public: + using Entry = DistributedKv::Entry; + using DeviceInfo = DistributedKv::DeviceInfo; + DistributedDatabase( + std::shared_ptr databaseCb, std::shared_ptr deviceCb); + ~DistributedDatabase(); + + bool PutToDistributedDB(const std::string &key, const std::string &value); + bool GetFromDistributedDB(const std::string &key, std::string &value); + bool GetEntriesFromDistributedDB(const std::string &prefixKey, std::vector &entries); + bool DeleteToDistributedDB(const std::string &key); + bool ClearDataByDevice(const std::string &deviceId); + bool GetLocalDeviceId(std::string &deviceId); + bool GetLocalDeviceInfo(DeviceInfo &localInfo); + bool GetDeviceInfoList(std::vector &deviceList); + bool RecreateDistributedDB(); + +private: + void GetKvDataManager(void); + bool CheckKvDataManager(void); + void GetKvStore(void); + bool CheckKvStore(void); + +private: + std::mutex mutex_; + std::unique_ptr kvDataManager_; + std::shared_ptr kvStore_; + std::shared_ptr databaseCb_; + std::shared_ptr deviceCb_; + + std::string localDeviceId_; + + DISALLOW_COPY_AND_MOVE(DistributedDatabase); +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_database_callback.h b/services/distributed/include/distributed_database_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..672b55617faa0e51359b599f86ec7175aaaff824 --- /dev/null +++ b/services/distributed/include/distributed_database_callback.h @@ -0,0 +1,45 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_CALLBACK_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_CALLBACK_H + +#include + +#include "kvstore_observer.h" + +namespace OHOS { +namespace Notification { +class DistributedDatabaseCallback : public DistributedKv::KvStoreObserver { +public: + struct IDatabaseChange { + std::function OnInsert; + std::function OnUpdate; + std::function OnDelete; + }; + explicit DistributedDatabaseCallback(const IDatabaseChange &callback); + ~DistributedDatabaseCallback(); +private: + void OnChange(const DistributedKv::ChangeNotification &changeNotification, + std::shared_ptr snapshot) override; + void OnChange(const DistributedKv::ChangeNotification &changeNotification) override; + +private: + IDatabaseChange callback_; +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_CALLBACK_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_device_callback.h b/services/distributed/include/distributed_device_callback.h new file mode 100644 index 0000000000000000000000000000000000000000..33000b45604becf489bb938bade6d95f8339346f --- /dev/null +++ b/services/distributed/include/distributed_device_callback.h @@ -0,0 +1,45 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DEVICE_CALLBACK_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DEVICE_CALLBACK_H + +#include + +#include "device_status_change_listener.h" + +namespace OHOS { +namespace Notification { +class DistributedDeviceCallback : public DistributedKv::DeviceStatusChangeListener { +public: + struct IDeviceChange { + std::function OnConnected; + std::function OnDisconnected; + }; + explicit DistributedDeviceCallback(const IDeviceChange &callback); + ~DistributedDeviceCallback(); + +private: + void OnDeviceChanged( + const DistributedKv::DeviceInfo &info, const DistributedKv::DeviceChangeType &type) const override; + DistributedKv::DeviceFilterStrategy GetFilterStrategy() const override; + +private: + IDeviceChange callback_; +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DEVICE_CALLBACK_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_flow_control.h b/services/distributed/include/distributed_flow_control.h new file mode 100644 index 0000000000000000000000000000000000000000..435381491d58798e95af0b2718034071acecc74e --- /dev/null +++ b/services/distributed/include/distributed_flow_control.h @@ -0,0 +1,52 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_FLOW_CONTROL_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_FLOW_CONTROL_H + +#include +#include + +namespace OHOS { +namespace Notification { +class DistributedFlowControl { +public: + DistributedFlowControl(int kvManagerSecondMaxinum = KVMANAGER_MAXINUM_PER_SECOND, + int kvManagerMinuteMaxinum = KVMANAGER_MAXINUM_PER_MINUTE, + int kvStoreSecondMaxinum = KVSTORE_MAXINUM_PER_SECOND, + int kvStoreMinuteMaxinum = KVSTORE_MAXINUM_PER_MINUTE); + bool KvManagerFlowControl(void); + bool KvStoreFlowControl(void); + void KvManagerFlowControlClear(void); + void KvStoreFlowControlClear(void); + +protected: + static const int KVMANAGER_MAXINUM_PER_SECOND = 50; + static const int KVMANAGER_MAXINUM_PER_MINUTE = 500; + static const int KVSTORE_MAXINUM_PER_SECOND = 1000; + static const int KVSTORE_MAXINUM_PER_MINUTE = 10000; + +private: + int kvManagerSecondMaxinum_; + int kvManagerMinuteMaxinum_; + int kvStoreSecondMaxinum_; + int kvStoreMinuteMaxinum_; + std::list kvDataManagerTimestampList_; + std::list kvStoreTimestampList_; +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_FLOW_CONTROL_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_notification_manager.h b/services/distributed/include/distributed_notification_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..edcc0a973a0436d4b231befbd1b239f26c6bfa0d --- /dev/null +++ b/services/distributed/include/distributed_notification_manager.h @@ -0,0 +1,104 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_NOTIFICATION_MANAGER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_NOTIFICATION_MANAGER_H + +#include + +#include "singleton.h" + +#include "event_handler.h" +#include "event_runner.h" + +#include "distributed_database.h" +#include "distributed_database_callback.h" +#include "distributed_device_callback.h" +#include "notification_request.h" + +namespace OHOS { +namespace Notification { +class DistributedNotificationManager : public DelayedSingleton { +public: + struct IDistributedCallback { + std::function &request)> + OnPublish; + std::function &request)> + OnUpdate; + std::function + OnDelete; + }; + + ErrCode Publish( + const std::string &bundleName, const std::string &label, int32_t id, const sptr &request); + ErrCode Update( + const std::string &bundleName, const std::string &label, int32_t id, const sptr &request); + ErrCode Delete(const std::string &bundleName, const std::string &label, int32_t id); + ErrCode DeleteRemoteNotification( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id); + ErrCode RegisterCallback(const IDistributedCallback &callback); + ErrCode UngegisterCallback(void); + ErrCode GetCurrentDistributedNotification(std::vector> &requestList); + ErrCode GetLocalDeviceInfo(DistributedDatabase::DeviceInfo &deviceInfo); + ErrCode OnDistributedKvStoreDeathRecipient(); + +private: + void OnDatabaseInsert(const std::string &deviceId, const std::string &key, const std::string &value); + void OnDatabaseUpdate(const std::string &deviceId, const std::string &key, const std::string &value); + void OnDatabaseDelete(const std::string &deviceId, const std::string &key, const std::string &value); + void OnDeviceConnected(const std::string &deviceId); + void OnDeviceDisconnected(const std::string &deviceId); + +private: + struct ResolveKey { + std::string deviceId; + std::string bundleName; + std::string label; + int32_t id = 0; + }; + + void GenerateDistributedKey(const std::string &deviceId, const std::string &bundleName, const std::string &label, + int32_t id, std::string &key); + bool GenerateLocalDistributedKey( + const std::string &bundleName, const std::string &label, int32_t id, std::string &key); + bool ResolveDistributedKey(const std::string &key, ResolveKey &resolveKey); + bool GetDeviceIdFromKey(const std::string &key, std::string &deviceId); + bool CheckDeviceId(const std::string &deviceId, const std::string &key); + + bool PublishCallback( + const std::string &deviceId, const std::string &bundleName, sptr &request); + bool UpdateCallback(const std::string &deviceId, const std::string &bundleName, sptr &request); + bool DeleteCallback( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id); + +private: + std::shared_ptr runner_ = nullptr; + std::shared_ptr handler_ = nullptr; + std::shared_ptr database_ = nullptr; + + std::shared_ptr databaseCb_; + std::shared_ptr deviceCb_; + IDistributedCallback callback_ = {0}; + + DECLARE_DELAYED_SINGLETON(DistributedNotificationManager); + DISALLOW_COPY_AND_MOVE(DistributedNotificationManager); +}; +} // namespace Notification +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_NOTIFICATION_MANAGER_H \ No newline at end of file diff --git a/services/distributed/include/distributed_preferences.h b/services/distributed/include/distributed_preferences.h new file mode 100644 index 0000000000000000000000000000000000000000..44d6d8991b69100e42bae83c54711b11040c14c2 --- /dev/null +++ b/services/distributed/include/distributed_preferences.h @@ -0,0 +1,61 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_H + +#include +#include + +#include "singleton.h" +#include "refbase.h" + +#include "ans_inner_errors.h" +#include "distributed_preferences_database.h" +#include "distributed_preferences_info.h" +#include "notification_bundle_option.h" + +namespace OHOS { +namespace Notification { +class DistributedPreferences : public DelayedSingleton { +public: + ErrCode SetDistributedEnable(bool isEnable); + ErrCode GetDistributedEnable(bool &isEnable); + ErrCode SetDistributedBundleEnable(const sptr &bundleOption, bool isEnable); + ErrCode GetDistributedBundleEnable(const sptr &bundleOption, bool &isEnable); + ErrCode DeleteDistributedBundleInfo(const sptr &bundleOption); + ErrCode ClearDataInRestoreFactorySettings(); + +private: + struct ResolveKey { + bool isMainKey = false; + std::string bundleName; + int32_t uid = 0; + }; + bool InitDistributedAllInfo(void); + void GetDistributedMainKey(std::string &key); + void GetDistributedBundleKey(const sptr &bundleOption, std::string &key); + bool ResolveDistributedKey(const std::string &key, ResolveKey &resolveKey); + +private: + std::unique_ptr preferencesInfo_ = nullptr; + std::unique_ptr database_ = nullptr; + + DECLARE_DELAYED_SINGLETON(DistributedPreferences); + DISALLOW_COPY_AND_MOVE(DistributedPreferences); +}; +} // namespace Notification +} // namespace OHOS +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_H */ diff --git a/services/distributed/include/distributed_preferences_database.h b/services/distributed/include/distributed_preferences_database.h new file mode 100644 index 0000000000000000000000000000000000000000..92b80d1f2d0059ebcd4d7b88d2e9feb184421a39 --- /dev/null +++ b/services/distributed/include/distributed_preferences_database.h @@ -0,0 +1,61 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_DATABASE_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_DATABASE_H + +#include +#include +#include + +#include "distributed_kv_data_manager.h" +#include "singleton.h" + +#include "distributed_database_callback.h" +#include "distributed_device_callback.h" +#include "distributed_flow_control.h" + +namespace OHOS { +namespace Notification { +class DistributedPreferencesDatabase : private DistributedFlowControl { +public: + using Entry = DistributedKv::Entry; + + DistributedPreferencesDatabase(); + ~DistributedPreferencesDatabase(); + + bool PutToDistributedDB(const std::string &key, const std::string &value); + bool GetFromDistributedDB(const std::string &key, std::string &value); + bool GetEntriesFromDistributedDB(const std::string &prefixKey, std::vector &entries); + bool DeleteToDistributedDB(const std::string &key); + bool ClearDatabase(void); + +private: + void GetKvDataManager(void); + bool CheckKvDataManager(void); + void GetKvStore(void); + bool CheckKvStore(void); + +private: + std::mutex mutex_; + std::unique_ptr kvDataManager_; + std::shared_ptr kvStore_; + + DISALLOW_COPY_AND_MOVE(DistributedPreferencesDatabase); +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_DATABASE_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_preferences_info.h b/services/distributed/include/distributed_preferences_info.h new file mode 100644 index 0000000000000000000000000000000000000000..840d3c95f2dd05b054d5837b05ce7df7c26b6a53 --- /dev/null +++ b/services/distributed/include/distributed_preferences_info.h @@ -0,0 +1,41 @@ +/* + * 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_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_INFO_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_INFO_H + +#include +#include + +namespace OHOS { +namespace Notification { +class DistributedPreferencesInfo { +public: + DistributedPreferencesInfo(); + ~DistributedPreferencesInfo(); + void SetDistributedEnable(bool enable); + bool GetDistributedEnable(void); + void SetDistributedBundleEnable(const std::string &bundleName, int32_t uid, bool enable); + bool GetDistributedBundleEnable(const std::string &bundleName, int32_t uid); + void DeleteDistributedBundleInfo(const std::string &bundleName, int32_t uid); + +private: + bool distributedEnable_ = true; + std::map, bool> bundleEnable_; +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_PREFERENCES_INFO_H */ \ No newline at end of file diff --git a/services/distributed/include/distributed_screen_status_manager.h b/services/distributed/include/distributed_screen_status_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..9ac03bb99f9eca015b7a88ba2fe9df324179d461 --- /dev/null +++ b/services/distributed/include/distributed_screen_status_manager.h @@ -0,0 +1,64 @@ +/* + * 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_DISTRIBUTED_INCLUDE_DISTRIBUTED_SCREEN_STATUS_MANAGER_H +#define BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_SCREEN_STATUS_MANAGER_H + +#include + +#include "distributed_kv_data_manager.h" +#include "event_handler.h" +#include "event_runner.h" +#include "singleton.h" + +#include "distributed_device_callback.h" +#include "distributed_flow_control.h" + +namespace OHOS { +namespace Notification { +class DistributedScreenStatusManager : private DistributedFlowControl, + public DelayedSingleton { +public: + ErrCode CheckRemoteDevicesIsUsing(bool &isUsing); + ErrCode SetLocalScreenStatus(bool screenOn); + +private: + void OnDeviceConnected(const std::string &deviceId); + void OnDeviceDisconnected(const std::string &deviceId); + + void GetKvDataManager(void); + bool CheckKvDataManager(void); + void GetKvStore(void); + bool CheckKvStore(void); + + std::string GenerateDistributedKey(const std::string &deviceId); + +private: + std::recursive_mutex mutex_; + std::shared_ptr runner_ = nullptr; + std::shared_ptr handler_ = nullptr; + std::unique_ptr kvDataManager_ = nullptr; + std::shared_ptr kvStore_ = nullptr; + std::shared_ptr deviceCb_ = nullptr; + + bool localScreenOn_ = false; + + DECLARE_DELAYED_SINGLETON(DistributedScreenStatusManager); + DISALLOW_COPY_AND_MOVE(DistributedScreenStatusManager); +}; +} // namespace Notification +} // namespace OHOS + +#endif /* BASE_NOTIFICATION_ANS_STANDARD_SERVICES_DISTRIBUTED_INCLUDE_DISTRIBUTED_SCREEN_STATUS_MANAGER_H */ diff --git a/services/distributed/src/distributed_database.cpp b/services/distributed/src/distributed_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..4b60727714d2f98101373a90123b666f4bdbf5ca --- /dev/null +++ b/services/distributed/src/distributed_database.cpp @@ -0,0 +1,322 @@ +/* + * 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 "distributed_database.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string APP_ID = "advanced_notification_service"; +const std::string STORE_ID = "distributed_notification"; +} // namespace + +DistributedDatabase::DistributedDatabase( + std::shared_ptr databaseCb, std::shared_ptr deviceCb) + : DistributedFlowControl(), databaseCb_(databaseCb), deviceCb_(deviceCb) +{ + GetKvDataManager(); + GetKvStore(); +} + +DistributedDatabase::~DistributedDatabase() +{} + +void DistributedDatabase::GetKvDataManager(void) +{ + kvDataManager_ = std::make_unique(); + if (kvDataManager_ != nullptr) { + DistributedKv::Status status = kvDataManager_->StartWatchDeviceChange(deviceCb_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGW("kvDataManager StartWatchDeviceChange failed ret = 0x%{public}x", status); + kvDataManager_.reset(); + } + } + + KvManagerFlowControlClear(); +} + +bool DistributedDatabase::CheckKvDataManager(void) +{ + if (kvDataManager_ == nullptr) { + GetKvDataManager(); + } + if (kvDataManager_ == nullptr) { + ANS_LOGE("kvDataManager is nullptr."); + return false; + } + return true; +} + +void DistributedDatabase::GetKvStore(void) +{ + if (!CheckKvDataManager()) { + return; + } + + DistributedKv::Options options; + options.createIfMissing = true; + options.autoSync = true; + options.kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION; + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + DistributedKv::Status status = kvDataManager_->GetSingleKvStore(options, appId, storeId, kvStore_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetSingleKvStore failed ret = 0x%{public}x", status); + kvStore_.reset(); + kvDataManager_->StopWatchDeviceChange(deviceCb_); + kvDataManager_.reset(); + return; + } + + if (kvStore_ != nullptr) { + status = kvStore_->SubscribeKvStore(DistributedKv::SubscribeType::SUBSCRIBE_TYPE_REMOTE, databaseCb_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore SubscribeKvStore failed ret = 0x%{public}x", status); + kvStore_.reset(); + } + } + + KvStoreFlowControlClear(); +} + +bool DistributedDatabase::CheckKvStore(void) +{ + if (kvStore_ == nullptr) { + GetKvStore(); + } + if (kvStore_ == nullptr) { + ANS_LOGE("kvStore is nullptr."); + return false; + } + return true; +} + +bool DistributedDatabase::PutToDistributedDB(const std::string &key, const std::string &value) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("KvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Value kvStoreValue(value); + DistributedKv::Status status = kvStore_->Put(kvStoreKey, kvStoreValue); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Put() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::GetFromDistributedDB(const std::string &key, std::string &value) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("KvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Value kvStoreValue; + DistributedKv::Status status = kvStore_->Get(kvStoreKey, kvStoreValue); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Get() failed ret = 0x%{public}x", status); + return false; + } + + value = kvStoreValue.ToString(); + + return true; +} + +bool DistributedDatabase::GetEntriesFromDistributedDB(const std::string &prefixKey, std::vector &entries) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("KvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(prefixKey); + DistributedKv::Status status = kvStore_->GetEntries(kvStoreKey, entries); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore GetEntries() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::DeleteToDistributedDB(const std::string &key) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("KvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Status status = kvStore_->Delete(kvStoreKey); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Delete() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::ClearDataByDevice(const std::string &deviceId) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("KvStore flow control."); + return false; + } + + DistributedKv::Status status = kvStore_->RemoveDeviceData(deviceId); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore RemoveDeviceData() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::GetLocalDeviceId(std::string &deviceId) +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager()) { + return false; + } + + if (KvManagerFlowControl()) { + DistributedKv::DeviceInfo deviceInfo; + DistributedKv::Status status = kvDataManager_->GetLocalDevice(deviceInfo); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetLocalDevice() failed ret = 0x%{public}x", status); + return false; + } + + localDeviceId_ = deviceInfo.deviceId; + } + + if (localDeviceId_.empty()) { + return false; + } + + deviceId = localDeviceId_; + + return true; +} + +bool DistributedDatabase::GetLocalDeviceInfo(DeviceInfo &localInfo) +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager()) { + return false; + } + + if (!KvManagerFlowControl()) { + ANS_LOGE("KvManager flow control."); + return false; + } + + DistributedKv::Status status = kvDataManager_->GetLocalDevice(localInfo); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetLocalDevice() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::GetDeviceInfoList(std::vector &deviceList) +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager()) { + return false; + } + + if (!KvManagerFlowControl()) { + ANS_LOGE("KvManager flow control."); + return false; + } + + DistributedKv::Status status = + kvDataManager_->GetDeviceList(deviceList, DistributedKv::DeviceFilterStrategy::NO_FILTER); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetDeviceList() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedDatabase::RecreateDistributedDB() +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager()) { + return false; + } + + if (!KvManagerFlowControl()) { + ANS_LOGE("KvManager flow control."); + return false; + } + + kvStore_.reset(); + + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + DistributedKv::Status status = kvDataManager_->DeleteKvStore(appId, storeId); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager DeleteKvStore() failed ret = 0x%{public}x", status); + return false; + } + + GetKvStore(); + return true; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_database_callback.cpp b/services/distributed/src/distributed_database_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..53bab4807e9034fde3c293f43d2a7a85b3eee165 --- /dev/null +++ b/services/distributed/src/distributed_database_callback.cpp @@ -0,0 +1,64 @@ +/* + * 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 "distributed_database_callback.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +DistributedDatabaseCallback::DistributedDatabaseCallback(const IDatabaseChange &callback) : callback_(callback) +{} + +DistributedDatabaseCallback::~DistributedDatabaseCallback() +{} + +void DistributedDatabaseCallback::OnChange(const DistributedKv::ChangeNotification &changeNotification, + std::shared_ptr snapshot) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + return; +} +void DistributedDatabaseCallback::OnChange(const DistributedKv::ChangeNotification &changeNotification) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + // const std::vector entryList; + + if (callback_.OnInsert) { + const std::vector &entryList = changeNotification.GetInsertEntries(); + ANS_LOGI("GetInsertEntries count %{public}zu", entryList.size()); + for (auto entry : entryList) { + callback_.OnInsert(changeNotification.GetDeviceId(), entry.key.ToString(), entry.value.ToString()); + } + } + + if (callback_.OnUpdate) { + const std::vector &entryList = changeNotification.GetUpdateEntries(); + ANS_LOGI("GetUpdateEntries count %{public}zu", entryList.size()); + for (auto entry : entryList) { + callback_.OnUpdate(changeNotification.GetDeviceId(), entry.key.ToString(), entry.value.ToString()); + } + } + + if (callback_.OnDelete) { + const std::vector &entryList = changeNotification.GetDeleteEntries(); + ANS_LOGI("GetDeleteEntries count %{public}zu", entryList.size()); + for (auto entry : entryList) { + callback_.OnDelete(changeNotification.GetDeviceId(), entry.key.ToString(), entry.value.ToString()); + } + } +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_device_callback.cpp b/services/distributed/src/distributed_device_callback.cpp new file mode 100644 index 0000000000000000000000000000000000000000..6a556ec8a0b1cb420f1215a39d02aa21f8944cb4 --- /dev/null +++ b/services/distributed/src/distributed_device_callback.cpp @@ -0,0 +1,50 @@ +/* + * 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 "distributed_device_callback.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +DistributedDeviceCallback::DistributedDeviceCallback(const IDeviceChange &callback) : callback_(callback) +{} +DistributedDeviceCallback::~DistributedDeviceCallback() +{} + +void DistributedDeviceCallback::OnDeviceChanged( + const DistributedKv::DeviceInfo &info, const DistributedKv::DeviceChangeType &type) const +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + if (type == DistributedKv::DeviceChangeType::DEVICE_ONLINE) { + ANS_LOGI("device %{public}s is ONLINE", info.deviceId.c_str()); + if (callback_.OnConnected) { + callback_.OnConnected(info.deviceId); + } + } + + if (type == DistributedKv::DeviceChangeType::DEVICE_OFFLINE) { + ANS_LOGI("device %{public}s is OFFLINE", info.deviceId.c_str()); + if (callback_.OnDisconnected) { + callback_.OnDisconnected(info.deviceId); + } + } +} +DistributedKv::DeviceFilterStrategy DistributedDeviceCallback::GetFilterStrategy() const +{ + return DistributedKv::DeviceFilterStrategy::NO_FILTER; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_flow_control.cpp b/services/distributed/src/distributed_flow_control.cpp new file mode 100644 index 0000000000000000000000000000000000000000..fabe5b589777f392bc4f4ac568a45253657f65a7 --- /dev/null +++ b/services/distributed/src/distributed_flow_control.cpp @@ -0,0 +1,94 @@ +/* + * 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 "distributed_flow_control.h" + +namespace OHOS { +namespace Notification { +DistributedFlowControl::DistributedFlowControl( + int kvManagerSecondMaxinum, int kvManagerMinuteMaxinum, int kvStoreSecondMaxinum, int kvStoreMinuteMaxinum) + : kvManagerSecondMaxinum_(kvManagerSecondMaxinum), + kvManagerMinuteMaxinum_(kvManagerMinuteMaxinum), + kvStoreSecondMaxinum_(kvStoreSecondMaxinum), + kvStoreMinuteMaxinum_(kvStoreMinuteMaxinum) +{} + +bool DistributedFlowControl::KvManagerFlowControl(void) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + kvDataManagerTimestampList_.remove_if([&](const std::chrono::system_clock::time_point &value) -> bool { + return now - value > std::chrono::minutes(1); + }); + + int listSize = kvStoreTimestampList_.size(); + if (listSize >= kvManagerMinuteMaxinum_) { + return false; + } + + int count = 0; + for (auto value : kvDataManagerTimestampList_) { + if (now - value > std::chrono::seconds(1)) { + if (count >= kvManagerSecondMaxinum_) { + return false; + } else { + break; + } + } + count++; + } + + kvDataManagerTimestampList_.push_front(now); + return true; +} + +bool DistributedFlowControl::KvStoreFlowControl(void) +{ + std::chrono::system_clock::time_point now = std::chrono::system_clock::now(); + kvStoreTimestampList_.remove_if([&](const std::chrono::system_clock::time_point &value) -> bool { + return now - value > std::chrono::minutes(1); + }); + + int listSize = kvStoreTimestampList_.size(); + if (listSize >= kvStoreMinuteMaxinum_) { + return false; + } + + int count = 0; + for (auto value : kvStoreTimestampList_) { + if (now - value > std::chrono::seconds(1)) { + if (count >= kvStoreSecondMaxinum_) { + return false; + } else { + break; + } + } + count++; + } + + kvStoreTimestampList_.push_front(now); + return true; +} + +void DistributedFlowControl::KvManagerFlowControlClear(void) +{ + kvDataManagerTimestampList_.clear(); +} + +void DistributedFlowControl::KvStoreFlowControlClear(void) +{ + kvStoreTimestampList_.clear(); +} +} // namespace Notification +} // namespace OHOS diff --git a/services/distributed/src/distributed_notification_manager.cpp b/services/distributed/src/distributed_notification_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..be2dba32af65c19d111c4783ef1904f6560a2528 --- /dev/null +++ b/services/distributed/src/distributed_notification_manager.cpp @@ -0,0 +1,424 @@ +/* + * 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 "distributed_notification_manager.h" + +#include + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string DELIMITER = "|"; +} // namespace + +DistributedNotificationManager::DistributedNotificationManager() +{ + runner_ = OHOS::AppExecFwk::EventRunner::Create(); + handler_ = std::make_shared(runner_); + + DistributedDatabaseCallback::IDatabaseChange databaseCallback = { + .OnInsert = std::bind(&DistributedNotificationManager::OnDatabaseInsert, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnUpdate = std::bind(&DistributedNotificationManager::OnDatabaseUpdate, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnDelete = std::bind(&DistributedNotificationManager::OnDatabaseDelete, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + }; + databaseCb_ = std::make_shared(databaseCallback); + + DistributedDeviceCallback::IDeviceChange deviceCallback = { + .OnConnected = std::bind(&DistributedNotificationManager::OnDeviceConnected, this, std::placeholders::_1), + .OnDisconnected = std::bind(&DistributedNotificationManager::OnDeviceDisconnected, this, std::placeholders::_1), + }; + deviceCb_ = std::make_shared(deviceCallback); + + database_ = std::make_shared(databaseCb_, deviceCb_); + if (database_ == nullptr) { + ANS_LOGE("database_ is nullptr."); + return; + } + database_->RecreateDistributedDB(); +} + +DistributedNotificationManager::~DistributedNotificationManager() +{ + handler_->PostSyncTask(std::bind([&]() { callback_ = {}; }), AppExecFwk::EventHandler::Priority::HIGH); +} + +void DistributedNotificationManager::GenerateDistributedKey( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id, std::string &key) +{ + key = deviceId + DELIMITER + bundleName + DELIMITER + label + DELIMITER + ToString(id); +} + +bool DistributedNotificationManager::GenerateLocalDistributedKey( + const std::string &bundleName, const std::string &label, int32_t id, std::string &key) +{ + std::string deviceId; + if (!database_->GetLocalDeviceId(deviceId)) { + return false; + } + + GenerateDistributedKey(deviceId, bundleName, label, id, key); + return true; +} + +bool DistributedNotificationManager::ResolveDistributedKey(const std::string &key, ResolveKey &resolveKey) +{ + std::size_t deviceIdPosition = 0; + std::size_t deviceIdEndPosition = key.find(DELIMITER, deviceIdPosition); + if (deviceIdEndPosition == std::string::npos) { + return false; + } + std::size_t bundleNamePosition = deviceIdEndPosition + DELIMITER.size(); + std::size_t bundleNameEndPosition = key.find(DELIMITER, bundleNamePosition); + if (bundleNameEndPosition == std::string::npos) { + return false; + } + std::size_t labelPosition = bundleNameEndPosition + DELIMITER.size(); + std::size_t labelEndPosition = key.find_last_of(DELIMITER) - DELIMITER.size() + 1; + if (labelEndPosition < labelPosition) { + return false; + } + std::size_t idPosition = key.find_last_of(DELIMITER) + DELIMITER.size(); + + resolveKey.deviceId = key.substr(deviceIdPosition, deviceIdEndPosition - deviceIdPosition); + resolveKey.bundleName = key.substr(bundleNamePosition, bundleNameEndPosition - bundleNamePosition); + resolveKey.label = key.substr(labelPosition, labelEndPosition - labelPosition); + resolveKey.id = atoi(&key[idPosition]); + + return true; +} + +bool DistributedNotificationManager::CheckDeviceId(const std::string &deviceId, const std::string &key) +{ + ResolveKey resolveKey; + if (!ResolveDistributedKey(key, resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", key.c_str()); + return false; + } + + return deviceId == resolveKey.deviceId; +} + +void DistributedNotificationManager::OnDatabaseInsert( + const std::string &deviceId, const std::string &key, const std::string &value) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask(std::bind([=]() { + if (!CheckDeviceId(deviceId, key)) { + ANS_LOGW("device id are not the same. deviceId:%{public}s key:%{public}s", deviceId.c_str(), key.c_str()); + } + + ResolveKey resolveKey; + if (!ResolveDistributedKey(key, resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", key.c_str()); + return; + } + + sptr request = + NotificationJsonConverter::ConvertFromJosnString(value); + if (request == nullptr) { + ANS_LOGE("convert json to request failed. key:%{public}s", key.c_str()); + return; + } + + PublishCallback(resolveKey.deviceId, resolveKey.bundleName, request); + })); +} + +void DistributedNotificationManager::OnDatabaseUpdate( + const std::string &deviceId, const std::string &key, const std::string &value) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask(std::bind([=]() { + if (!CheckDeviceId(deviceId, key)) { + ANS_LOGW("device id are not the same. deviceId:%{public}s key:%{public}s", deviceId.c_str(), key.c_str()); + } + + ResolveKey resolveKey; + if (!ResolveDistributedKey(key, resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", key.c_str()); + return; + } + + sptr request = + NotificationJsonConverter::ConvertFromJosnString(value); + if (request == nullptr) { + ANS_LOGE("convert json to request failed. key:%{public}s", key.c_str()); + return; + } + + UpdateCallback(resolveKey.deviceId, resolveKey.bundleName, request); + })); +} + +void DistributedNotificationManager::OnDatabaseDelete( + const std::string &deviceId, const std::string &key, const std::string &value) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask(std::bind([=]() { + if (!CheckDeviceId(deviceId, key)) { + ANS_LOGW("device id are not the same. deviceId:%{public}s key:%{public}s", deviceId.c_str(), key.c_str()); + } + + ResolveKey resolveKey; + if (!ResolveDistributedKey(key, resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", key.c_str()); + return; + } + + DeleteCallback(resolveKey.deviceId, resolveKey.bundleName, resolveKey.label, resolveKey.id); + })); +} + +void DistributedNotificationManager::OnDeviceConnected(const std::string &deviceId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + handler_->PostTask(std::bind([=]() {})); + return; +} + +void DistributedNotificationManager::OnDeviceDisconnected(const std::string &deviceId) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + handler_->PostTask(std::bind([=]() { + std::string prefixKey = deviceId + DELIMITER; + std::vector entries; + if (!database_->GetEntriesFromDistributedDB(prefixKey, entries)) { + ANS_LOGE("GetEntriesFromDistributedDB failed."); + return; + } + + for (auto index : entries) { + ResolveKey resolveKey; + if (!ResolveDistributedKey(index.key.ToString(), resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", index.key.ToString().c_str()); + continue; + } + + DeleteCallback(resolveKey.deviceId, resolveKey.bundleName, resolveKey.label, resolveKey.id); + } + + database_->ClearDataByDevice(deviceId); + + std::vector deviceList; + if (database_->GetDeviceInfoList(deviceList) == ERR_OK && deviceList.empty()) { + database_->RecreateDistributedDB(); + } + })); + return; +} + +bool DistributedNotificationManager::PublishCallback( + const std::string &deviceId, const std::string &bundleName, sptr &request) +{ + ANS_LOGI("callback_.OnPublish start."); + if (callback_.OnPublish) { + callback_.OnPublish(deviceId, bundleName, request); + } + ANS_LOGI("callback_.OnPublish end."); + + return true; +} + +bool DistributedNotificationManager::UpdateCallback( + const std::string &deviceId, const std::string &bundleName, sptr &request) +{ + ANS_LOGI("callback_.OnUpdate start."); + if (callback_.OnUpdate) { + callback_.OnUpdate(deviceId, bundleName, request); + } + ANS_LOGI("callback_.OnUpdate end."); + + return true; +} + +bool DistributedNotificationManager::DeleteCallback( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id) +{ + ANS_LOGI("callback_.OnDelete start."); + if (callback_.OnDelete) { + callback_.OnDelete(deviceId, bundleName, label, id); + } + ANS_LOGI("callback_.OnDelete end."); + + return true; +} + +ErrCode DistributedNotificationManager::Publish( + const std::string &bundleName, const std::string &label, int32_t id, const sptr &request) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + std::string key; + if (!GenerateLocalDistributedKey(bundleName, label, id, key)) { + ANS_LOGE("Generate distributed key failed."); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + std::string value; + if (!NotificationJsonConverter::ConvertToJosnString(request, value)) { + ANS_LOGE("convert request to json failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + if (!database_->PutToDistributedDB(key, value)) { + ANS_LOGE("put to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + return ERR_OK; +} + +ErrCode DistributedNotificationManager::Update( + const std::string &bundleName, const std::string &label, int32_t id, const sptr &request) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + std::string key; + if (!GenerateLocalDistributedKey(bundleName, label, id, key)) { + ANS_LOGE("Generate distributed key failed."); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + std::string value; + if (!NotificationJsonConverter::ConvertToJosnString(request, value)) { + ANS_LOGE("convert request to json failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + if (!database_->PutToDistributedDB(key, value)) { + ANS_LOGE("put to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + return ERR_OK; +} + +ErrCode DistributedNotificationManager::Delete(const std::string &bundleName, const std::string &label, int32_t id) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + std::string key; + if (!GenerateLocalDistributedKey(bundleName, label, id, key)) { + ANS_LOGE("Generate distributed key failed."); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + if (!database_->DeleteToDistributedDB(key)) { + ANS_LOGE("delete to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + return ERR_OK; +} + +ErrCode DistributedNotificationManager::DeleteRemoteNotification( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + + std::string key; + GenerateDistributedKey(deviceId, bundleName, label, id, key); + + if (!database_->DeleteToDistributedDB(key)) { + ANS_LOGE("delete to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + return ERR_OK; +} + +ErrCode DistributedNotificationManager::RegisterCallback(const IDistributedCallback &callback) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + handler_->PostSyncTask(std::bind([&]() { callback_ = callback; }), AppExecFwk::EventHandler::Priority::HIGH); + return ERR_OK; +} + +ErrCode DistributedNotificationManager::UngegisterCallback(void) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + handler_->PostSyncTask(std::bind([&]() { callback_ = {}; }), AppExecFwk::EventHandler::Priority::HIGH); + return ERR_OK; +} + +ErrCode DistributedNotificationManager::GetCurrentDistributedNotification( + std::vector> &requestList) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + std::string prefixKey = ""; + std::vector entries; + if (!database_->GetEntriesFromDistributedDB(prefixKey, entries)) { + ANS_LOGE("GetEntriesFromDistributedDB failed."); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + for (auto index : entries) { + ResolveKey resolveKey; + if (!ResolveDistributedKey(index.key.ToString(), resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", index.key.ToString().c_str()); + continue; + } + + sptr request = + NotificationJsonConverter::ConvertFromJosnString(index.value.ToString()); + if (request == nullptr) { + ANS_LOGE("convert json to request failed. key:%{public}s", index.key.ToString().c_str()); + continue; + } + + PublishCallback(resolveKey.deviceId, resolveKey.bundleName, request); + } + + return ERR_OK; +} + +ErrCode DistributedNotificationManager::GetLocalDeviceInfo(DistributedDatabase::DeviceInfo &deviceInfo) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + + if (!database_->GetLocalDeviceInfo(deviceInfo)) { + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + return ERR_OK; +} + +ErrCode DistributedNotificationManager::OnDistributedKvStoreDeathRecipient() +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + + database_ = std::make_shared(databaseCb_, deviceCb_); + if (database_ == nullptr) { + ANS_LOGE("database_ is nullptr."); + return ERR_ANS_NO_MEMORY; + } + if (!database_->RecreateDistributedDB()) { + ANS_LOGE("RecreateDistributedDB failed."); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + return ERR_OK; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_preferences.cpp b/services/distributed/src/distributed_preferences.cpp new file mode 100644 index 0000000000000000000000000000000000000000..551fb0f1c605aa46f6326d96574c9e2f511a6f46 --- /dev/null +++ b/services/distributed/src/distributed_preferences.cpp @@ -0,0 +1,216 @@ +/* + * 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 "distributed_preferences.h" + +#include + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string DISTRIBUTED_LABEL = "distributed"; +const std::string DELIMITER = "|"; +const std::string MAIN_LABEL = "ans_main"; +const std::string BUNDLE_LABEL = "bundle"; +} // namespace + +inline bool GetBoolFromString(const std::string &str) +{ + return static_cast(atoi(str.data())); +} + +DistributedPreferences::DistributedPreferences() +{ + database_ = std::make_unique(); + + preferencesInfo_ = std::make_unique(); + InitDistributedAllInfo(); +} + +DistributedPreferences::~DistributedPreferences() +{} + +bool DistributedPreferences::InitDistributedAllInfo(void) +{ + std::vector entries; + if (!database_->GetEntriesFromDistributedDB(DISTRIBUTED_LABEL, entries)) { + return false; + } + + for (auto entry : entries) { + ResolveKey resolveKey; + if (!ResolveDistributedKey(entry.key.ToString(), resolveKey)) { + ANS_LOGE("key <%{public}s> is invalid.", entry.key.ToString().c_str()); + continue; + } + + if (resolveKey.isMainKey) { + int value = atoi(entry.value.ToString().data()); + preferencesInfo_->SetDistributedEnable(static_cast(value)); + } else { + preferencesInfo_->SetDistributedBundleEnable( + resolveKey.bundleName, resolveKey.uid, GetBoolFromString(entry.value.ToString())); + } + } + + return true; +} + +void DistributedPreferences::GetDistributedMainKey(std::string &key) +{ + key = DISTRIBUTED_LABEL + DELIMITER + MAIN_LABEL + DELIMITER; +} + +void DistributedPreferences::GetDistributedBundleKey( + const sptr &bundleOption, std::string &key) +{ + key = DISTRIBUTED_LABEL + DELIMITER + BUNDLE_LABEL + DELIMITER + bundleOption->GetBundleName() + DELIMITER + + std::to_string(bundleOption->GetUid()); +} + +bool DistributedPreferences::ResolveDistributedKey(const std::string &key, ResolveKey &resolveKey) +{ + std::size_t distributedLabelPosition = 0; + std::size_t distributedLabelEndPosition = key.find(DELIMITER, distributedLabelPosition); + if (distributedLabelEndPosition == std::string::npos) { + return false; + } + std::size_t typeLabelPosition = distributedLabelEndPosition + DELIMITER.size(); + std::size_t typeLabelEndPosition = key.find(DELIMITER, typeLabelPosition); + if (typeLabelPosition == std::string::npos) { + return false; + } + + if (key.substr(typeLabelPosition, typeLabelEndPosition - typeLabelPosition).compare(MAIN_LABEL) == 0) { + resolveKey.isMainKey = true; + return true; + } + + std::size_t bundleNamePosition = typeLabelEndPosition + DELIMITER.size(); + std::size_t bundleNameEndPosition = key.find(DELIMITER, bundleNamePosition); + if (bundleNameEndPosition == std::string::npos) { + return false; + } + + std::size_t uidPosition = key.find_last_of(DELIMITER) + DELIMITER.size(); + if (uidPosition < bundleNameEndPosition) { + return false; + } + + resolveKey.isMainKey = false; + resolveKey.bundleName = key.substr(bundleNamePosition, bundleNameEndPosition - bundleNamePosition); + resolveKey.uid = atoi(&key[uidPosition]); + + return true; +} + +ErrCode DistributedPreferences::SetDistributedEnable(bool isEnable) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + std::string key; + GetDistributedMainKey(key); + + if (!database_->PutToDistributedDB(key, std::to_string(isEnable))) { + ANS_LOGE("put to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + preferencesInfo_->SetDistributedEnable(isEnable); + + return ERR_OK; +} + +ErrCode DistributedPreferences::GetDistributedEnable(bool &isEnable) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + + isEnable = preferencesInfo_->GetDistributedEnable(); + + return ERR_OK; +} + +ErrCode DistributedPreferences::SetDistributedBundleEnable( + const sptr &bundleOption, bool isEnable) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + std::string key; + GetDistributedBundleKey(bundleOption, key); + + if (!database_->PutToDistributedDB(key, std::to_string(isEnable))) { + ANS_LOGE("put to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + preferencesInfo_->SetDistributedBundleEnable(bundleOption->GetBundleName(), bundleOption->GetUid(), isEnable); + + return ERR_OK; +} + +ErrCode DistributedPreferences::GetDistributedBundleEnable( + const sptr &bundleOption, bool &isEnable) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + isEnable = preferencesInfo_->GetDistributedBundleEnable(bundleOption->GetBundleName(), bundleOption->GetUid()); + + return ERR_OK; +} + +ErrCode DistributedPreferences::DeleteDistributedBundleInfo(const sptr &bundleOption) +{ + ANS_LOGI("%{public}s start", __FUNCTION__); + if (bundleOption == nullptr) { + ANS_LOGE("bundleOption is nullptr."); + return ERR_ANS_INVALID_PARAM; + } + + std::string key; + GetDistributedBundleKey(bundleOption, key); + + if (!database_->DeleteToDistributedDB(key)) { + ANS_LOGE("delete to distributed DB failed. key:%{public}s", key.c_str()); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + preferencesInfo_->DeleteDistributedBundleInfo(bundleOption->GetBundleName(), bundleOption->GetUid()); + + return ERR_OK; +} + +ErrCode DistributedPreferences::ClearDataInRestoreFactorySettings() +{ + if (!database_->ClearDatabase()) { + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + SetDistributedEnable(false); + + preferencesInfo_ = std::make_unique(); + + return ERR_OK; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_preferences_database.cpp b/services/distributed/src/distributed_preferences_database.cpp new file mode 100644 index 0000000000000000000000000000000000000000..535bcda40e9d7cb726310ff5383d2a3175bccfd8 --- /dev/null +++ b/services/distributed/src/distributed_preferences_database.cpp @@ -0,0 +1,215 @@ +/* + * 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 "distributed_preferences_database.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string APP_ID = "advanced_notification_service"; +const std::string STORE_ID = "distributed_preferences"; +} // namespace + +DistributedPreferencesDatabase::DistributedPreferencesDatabase() : DistributedFlowControl() +{ + GetKvDataManager(); + GetKvStore(); +} + +DistributedPreferencesDatabase::~DistributedPreferencesDatabase() +{} + +void DistributedPreferencesDatabase::GetKvDataManager(void) +{ + kvDataManager_ = std::make_unique(); + + KvManagerFlowControlClear(); +} + +bool DistributedPreferencesDatabase::CheckKvDataManager(void) +{ + if (kvDataManager_ == nullptr) { + GetKvDataManager(); + } + if (kvDataManager_ == nullptr) { + return false; + } + return true; +} + +void DistributedPreferencesDatabase::GetKvStore(void) +{ + if (!CheckKvDataManager()) { + return; + } + + DistributedKv::Status status; + DistributedKv::Options options; + options.createIfMissing = true; + options.autoSync = false; + options.kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION; + + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + status = kvDataManager_->GetSingleKvStore(options, appId, storeId, kvStore_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetSingleKvStore failed ret = 0x%{public}x", status); + kvStore_.reset(); + kvDataManager_.reset(); + } + + KvStoreFlowControlClear(); +} + +bool DistributedPreferencesDatabase::CheckKvStore(void) +{ + if (kvStore_ == nullptr) { + GetKvStore(); + } + if (kvStore_ == nullptr) { + return false; + } + return true; +} + +bool DistributedPreferencesDatabase::PutToDistributedDB(const std::string &key, const std::string &value) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("kvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Value kvStoreValue(value); + DistributedKv::Status status = kvStore_->Put(kvStoreKey, kvStoreValue); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Put() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedPreferencesDatabase::GetFromDistributedDB(const std::string &key, std::string &value) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("kvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Value kvStoreValue; + DistributedKv::Status status = kvStore_->Get(kvStoreKey, kvStoreValue); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Get() failed ret = 0x%{public}x", status); + return false; + } + + value = kvStoreValue.ToString(); + + return true; +} + +bool DistributedPreferencesDatabase::GetEntriesFromDistributedDB( + const std::string &prefixKey, std::vector &entries) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("kvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(prefixKey); + DistributedKv::Status status = kvStore_->GetEntries(kvStoreKey, entries); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore GetEntries() failed ret = 0x%{public}x", status); + return false; + } + + return true; +} + +bool DistributedPreferencesDatabase::DeleteToDistributedDB(const std::string &key) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvStore()) { + return false; + } + + if (!KvStoreFlowControl()) { + ANS_LOGE("kvStore flow control."); + return false; + } + + DistributedKv::Key kvStoreKey(key); + DistributedKv::Value kvStoreValue; + DistributedKv::Status status = kvStore_->Delete(kvStoreKey); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Delete() failed ret = 0x%{public}x", status); + return false; + } + return true; +} + +bool DistributedPreferencesDatabase::ClearDatabase(void) +{ + std::lock_guard lock(mutex_); + + if (!CheckKvDataManager()) { + return false; + } + + if (!KvManagerFlowControl()) { + ANS_LOGE("kvDataManager flow control."); + return false; + } + + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + DistributedKv::Status status = kvDataManager_->CloseKvStore(appId, storeId); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager CloseKvStore() failed ret = 0x%{public}x", status); + return false; + } + + status = kvDataManager_->DeleteKvStore(appId, storeId); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager DeleteKvStore() failed ret = 0x%{public}x", status); + return false; + } + return true; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_preferences_info.cpp b/services/distributed/src/distributed_preferences_info.cpp new file mode 100644 index 0000000000000000000000000000000000000000..1e43052f77fe5df326a6da43c43817b565f2d19f --- /dev/null +++ b/services/distributed/src/distributed_preferences_info.cpp @@ -0,0 +1,59 @@ +/* + * 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 "distributed_preferences_info.h" + +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +DistributedPreferencesInfo::DistributedPreferencesInfo() +{} + +DistributedPreferencesInfo::~DistributedPreferencesInfo() +{} + +void DistributedPreferencesInfo::SetDistributedEnable(bool enable) +{ + distributedEnable_ = enable; +} + +bool DistributedPreferencesInfo::GetDistributedEnable(void) +{ + return distributedEnable_; +} + +void DistributedPreferencesInfo::SetDistributedBundleEnable(const std::string &bundleName, int32_t uid, bool enable) +{ + bundleEnable_[std::make_pair(bundleName, uid)] = enable; +} + +bool DistributedPreferencesInfo::GetDistributedBundleEnable(const std::string &bundleName, int32_t uid) +{ + auto iter = bundleEnable_.find(std::make_pair(bundleName, uid)); + if (iter == bundleEnable_.end()) { + ANS_LOGW("bundle %{public}s(%{public}d) not found.", bundleName.c_str(), uid); + return true; + } + + return iter->second; +} + +void DistributedPreferencesInfo::DeleteDistributedBundleInfo(const std::string &bundleName, int32_t uid) +{ + bundleEnable_.erase(std::make_pair(bundleName, uid)); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/src/distributed_screen_status_manager.cpp b/services/distributed/src/distributed_screen_status_manager.cpp new file mode 100644 index 0000000000000000000000000000000000000000..a1dddb7bd93e9442aef5310dfe5d8c020d2c279b --- /dev/null +++ b/services/distributed/src/distributed_screen_status_manager.cpp @@ -0,0 +1,235 @@ +/* + * 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 "distributed_screen_status_manager.h" + +#include "ans_inner_errors.h" +#include "ans_log_wrapper.h" + +namespace OHOS { +namespace Notification { +namespace { +const std::string APP_ID = "advanced_notification_service"; +const std::string STORE_ID = "distributed_screen_status"; +const std::string DELIMITER = "|"; +const std::string SCREEN_STATUS_LABEL = "screen_status"; +const std::string SCREEN_STATUS_VALUE_ON = "on"; +const std::string SCREEN_STATUS_VALUE_OFF = "off"; +} // namespace + +DistributedScreenStatusManager::DistributedScreenStatusManager() : DistributedFlowControl() +{ + DistributedDeviceCallback::IDeviceChange callback = { + .OnConnected = std::bind(&DistributedScreenStatusManager::OnDeviceConnected, this, std::placeholders::_1), + .OnDisconnected = std::bind(&DistributedScreenStatusManager::OnDeviceDisconnected, this, std::placeholders::_1), + }; + deviceCb_ = std::make_shared(callback); + GetKvDataManager(); + GetKvStore(); +} + +DistributedScreenStatusManager::~DistributedScreenStatusManager() +{} + +void DistributedScreenStatusManager::OnDeviceConnected(const std::string &deviceId) +{ + ANS_LOGI("deviceId:%{public}s", deviceId.c_str()); +} + +void DistributedScreenStatusManager::OnDeviceDisconnected(const std::string &deviceId) +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager()) { + return; + } + + std::vector devInfoList; + DistributedKv::Status status = + kvDataManager_->GetDeviceList(devInfoList, DistributedKv::DeviceFilterStrategy::NO_FILTER); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetDeviceList() failed ret = 0x%{public}x", status); + kvDataManager_.reset(); + return; + } + + if (!devInfoList.empty()) { + return; + } + + kvStore_.reset(); + + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + kvDataManager_->DeleteKvStore(appId, storeId); + + if (!CheckKvStore()) { + return; + } + + SetLocalScreenStatus(localScreenOn_); +} + +void DistributedScreenStatusManager::GetKvDataManager(void) +{ + kvDataManager_ = std::make_unique(); + if (kvDataManager_ != nullptr) { + DistributedKv::Status status = kvDataManager_->StartWatchDeviceChange(deviceCb_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGW("kvDataManager StartWatchDeviceChange failed ret = 0x%{public}x", status); + kvDataManager_.reset(); + } + } + + KvManagerFlowControlClear(); +} + +bool DistributedScreenStatusManager::CheckKvDataManager(void) +{ + if (kvDataManager_ == nullptr) { + GetKvDataManager(); + } + if (kvDataManager_ == nullptr) { + ANS_LOGE("kvDataManager is nullptr."); + return false; + } + return true; +} + +void DistributedScreenStatusManager::GetKvStore(void) +{ + if (!CheckKvDataManager()) { + return; + } + + DistributedKv::Status status; + DistributedKv::Options options; + options.createIfMissing = true; + options.autoSync = true; + options.kvStoreType = DistributedKv::KvStoreType::SINGLE_VERSION; + + DistributedKv::AppId appId = {.appId = APP_ID}; + DistributedKv::StoreId storeId = {.storeId = STORE_ID}; + status = kvDataManager_->GetSingleKvStore(options, appId, storeId, kvStore_); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetSingleKvStore failed ret = 0x%{public}x", status); + kvStore_.reset(); + kvDataManager_->StopWatchDeviceChange(deviceCb_); + kvDataManager_.reset(); + return; + } + + KvStoreFlowControlClear(); +} + +bool DistributedScreenStatusManager::CheckKvStore(void) +{ + if (kvStore_ == nullptr) { + GetKvStore(); + } + if (kvStore_ == nullptr) { + ANS_LOGE("kvStore is nullptr."); + return false; + } + return true; +} + +std::string DistributedScreenStatusManager::GenerateDistributedKey(const std::string &deviceId) +{ + return deviceId + DELIMITER + SCREEN_STATUS_LABEL; +} + +ErrCode DistributedScreenStatusManager::CheckRemoteDevicesIsUsing(bool &isUsing) +{ + std::lock_guard lock(mutex_); + if (!CheckKvDataManager() || !CheckKvStore()) { + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + if (!KvManagerFlowControl() || !KvStoreFlowControl()) { + ANS_LOGE("flow control."); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + std::vector devInfoList; + DistributedKv::Status status = + kvDataManager_->GetDeviceList(devInfoList, DistributedKv::DeviceFilterStrategy::NO_FILTER); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetDeviceList() failed ret = 0x%{public}x", status); + kvDataManager_.reset(); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + DistributedKv::Key prefixKey(""); + std::vector entries; + status = kvStore_->GetEntries(prefixKey, entries); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore GetEntries() failed ret = 0x%{public}x", status); + kvStore_.reset(); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + for (auto entry : entries) { + std::string key = entry.key.ToString(); + std::string deviceId = key.substr(0, key.find_first_of(DELIMITER)); + ANS_LOGD("key-deviceId:%{public}s, value:%{public}s", deviceId.c_str(), entry.value.ToString().c_str()); + for (auto devInfo : devInfoList) { + ANS_LOGD("list-deviceId:%{public}s", devInfo.deviceId.c_str()); + if (devInfo.deviceId == deviceId) { + isUsing = isUsing || (entry.value.ToString() == SCREEN_STATUS_VALUE_ON); + break; + } + } + if (isUsing) { + break; + } + } + + ANS_LOGI("%{public}s, isUsing:%{public}s", __FUNCTION__, isUsing ? "true" : "false"); + return ERR_OK; +} + +ErrCode DistributedScreenStatusManager::SetLocalScreenStatus(bool screenOn) +{ + std::lock_guard lock(mutex_); + ANS_LOGI("%{public}s, screenOn:%{public}s", __FUNCTION__, screenOn ? "true" : "false"); + localScreenOn_ = screenOn; + if (!CheckKvStore()) { + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + if (!KvManagerFlowControl() || !KvStoreFlowControl()) { + ANS_LOGE("flow control."); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + DistributedKv::DeviceInfo localDevice; + DistributedKv::Status status = kvDataManager_->GetLocalDevice(localDevice); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvDataManager GetLocalDevice() failed ret = 0x%{public}x", status); + return ERR_ANS_DISTRIBUTED_GET_INFO_FAILED; + } + + DistributedKv::Key kvStoreKey = GenerateDistributedKey(localDevice.deviceId); + DistributedKv::Value kvStoreValue = screenOn ? SCREEN_STATUS_VALUE_ON : SCREEN_STATUS_VALUE_OFF; + status = kvStore_->Put(kvStoreKey, kvStoreValue); + if (status != DistributedKv::Status::SUCCESS) { + ANS_LOGE("kvStore Put() failed ret = 0x%{public}x", status); + return ERR_ANS_DISTRIBUTED_OPERATION_FAILED; + } + + return ERR_OK; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/test/unittest/BUILD.gn b/services/distributed/test/unittest/BUILD.gn new file mode 100644 index 0000000000000000000000000000000000000000..934c13331449282f544f764a2e1657e705f5dbd2 --- /dev/null +++ b/services/distributed/test/unittest/BUILD.gn @@ -0,0 +1,82 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/ohos.gni") +import("//build/test.gni") + +group("ans_distributed_unit_test_target") { + testonly = true + deps = [] + + if (distributed_notification_supported) { + deps += [ ":ans_distributed_unit_test" ] + } +} + +ohos_unittest("ans_distributed_unit_test") { + module_out_path = "ans_standard/unittest" + include_dirs = [ + "/${services_path}/distributed/include", + "//utils/native/base/include", + ] + + sources = [ + "${services_path}/distributed/src/distributed_database.cpp", + "${services_path}/distributed/src/distributed_database_callback.cpp", + "${services_path}/distributed/src/distributed_device_callback.cpp", + "${services_path}/distributed/src/distributed_flow_control.cpp", + "${services_path}/distributed/src/distributed_notification_manager.cpp", + "${services_path}/distributed/src/distributed_preferences.cpp", + "${services_path}/distributed/src/distributed_preferences_database.cpp", + "${services_path}/distributed/src/distributed_preferences_info.cpp", + "${services_path}/distributed/src/distributed_screen_status_manager.cpp", + "${services_path}/distributed/test/unittest/distributed_database_test.cpp", + "${services_path}/distributed/test/unittest/distributed_notification_manager_test.cpp", + "${services_path}/distributed/test/unittest/distributed_preferences_test.cpp", + "${services_path}/distributed/test/unittest/distributed_screen_status_manager_test.cpp", + "${services_path}/distributed/test/unittest/mock/ans_test_single_kv_store.cpp", + "${services_path}/distributed/test/unittest/mock/mock_blob.cpp", + "${services_path}/distributed/test/unittest/mock/mock_change_notification.cpp", + "${services_path}/distributed/test/unittest/mock/mock_distributed_kv_data_manager.cpp", + "${services_path}/distributed/test/unittest/mock/mock_event_handler.cpp", + "${services_path}/distributed/test/unittest/mock/mock_event_runner.cpp", + "${services_path}/distributed/test/unittest/mock/mock_inner_event.cpp", + ] + + configs = [ + "${services_path}/distributed/:ans_distributed_config", + "${core_path}:public_ans_core_config", + "${frameworks_path}/ans/native:ans_innerkits_public_config", + ] + + deps = [ + "${core_path}:ans_core", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "ability_runtime:base", + "ability_runtime:want", + "bundle_framework:appexecfwk_base", + "distributeddatamgr:distributeddata_inner", + "hitrace_native:libhitrace", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "multimedia_image_standard:image_native", + ] + + subsystem_name = "notification" + part_name = "ans_standard" +} diff --git a/services/distributed/test/unittest/distributed_database_test.cpp b/services/distributed/test/unittest/distributed_database_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..f94a86995b037121c46699b1fb0f8f63033e66d5 --- /dev/null +++ b/services/distributed/test/unittest/distributed_database_test.cpp @@ -0,0 +1,193 @@ +/* + * 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 "gtest/gtest.h" + +#include "distributed_database.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class DistributedDatabaseTest : public testing::Test { +public: + void SetUp() override; + void TearDown() override; + +public: + virtual void OnInsert(const std::string &deviceId, const std::string &key, const std::string &value); + virtual void OnUpdate(const std::string &deviceId, const std::string &key, const std::string &value); + virtual void OnDelete(const std::string &deviceId, const std::string &key, const std::string &value); + virtual void OnConnected(const std::string &deviceId); + virtual void OnDisconnected(const std::string &deviceId); + +protected: + std::shared_ptr database_; + std::shared_ptr databaseCallback_; + std::shared_ptr deviceCallback_; +}; + +void DistributedDatabaseTest::SetUp() +{ + DistributedDatabaseCallback::IDatabaseChange databaseCallback = { + .OnInsert = std::bind(&DistributedDatabaseTest::OnInsert, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnUpdate = std::bind(&DistributedDatabaseTest::OnUpdate, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + .OnDelete = std::bind(&DistributedDatabaseTest::OnDelete, + this, + std::placeholders::_1, + std::placeholders::_2, + std::placeholders::_3), + }; + DistributedDeviceCallback::IDeviceChange deviceCallback = { + .OnConnected = std::bind(&DistributedDatabaseTest::OnConnected, this, std::placeholders::_1), + .OnDisconnected = std::bind(&DistributedDatabaseTest::OnDisconnected, this, std::placeholders::_1), + }; + + databaseCallback_ = std::make_shared(databaseCallback); + deviceCallback_ = std::make_shared(deviceCallback); + database_ = std::make_shared(databaseCallback_, deviceCallback_); +} + +void DistributedDatabaseTest::TearDown() +{ + database_ = nullptr; + databaseCallback_ = nullptr; + deviceCallback_ = nullptr; +} + +void DistributedDatabaseTest::OnInsert(const std::string &deviceId, const std::string &key, const std::string &value) +{} + +void DistributedDatabaseTest::OnUpdate(const std::string &deviceId, const std::string &key, const std::string &value) +{} + +void DistributedDatabaseTest::OnDelete(const std::string &deviceId, const std::string &key, const std::string &value) +{} + +void DistributedDatabaseTest::OnConnected(const std::string &deviceId) +{} + +void DistributedDatabaseTest::OnDisconnected(const std::string &deviceId) +{} + +/** + * @tc.name : DistributedDatabase_PutToDistributedDB_00100 + * @tc.number : PutToDistributedDB_00100 + * @tc.desc : Put a key-value. + */ +HWTEST_F(DistributedDatabaseTest, PutToDistributedDB_00100, Function | SmallTest | Level1) +{ + std::string key(""); + std::string value(""); + + EXPECT_EQ(database_->PutToDistributedDB(key, value), true); +} + +/** + * @tc.name : DistributedDatabase_GetFromDistributedDB_00100 + * @tc.number : GetFromDistributedDB_00100 + * @tc.desc : Get value by its key. + */ +HWTEST_F(DistributedDatabaseTest, GetFromDistributedDB_00100, Function | SmallTest | Level1) +{ + std::string key(""); + std::string value; + + EXPECT_EQ(database_->GetFromDistributedDB(key, value), true); +} + +/** + * @tc.name : DistributedDatabase_GetFromDistributedDB_00200 + * @tc.number : GetFromDistributedDB_00200 + * @tc.desc : Get all entries which key start with prefixKey. + */ +HWTEST_F(DistributedDatabaseTest, GetFromDistributedDB_00200, Function | SmallTest | Level1) +{ + std::string prifixKey("<"); + std::vector entries; + + EXPECT_EQ(database_->GetEntriesFromDistributedDB(prifixKey, entries), true); +} + +/** + * @tc.name : DistributedDatabase_DeleteToDistributedDB_00100 + * @tc.number : DeleteToDistributedDB_00100 + * @tc.desc : Delete a key-value with its key. + */ +HWTEST_F(DistributedDatabaseTest, DeleteToDistributedDB_00100, Function | SmallTest | Level1) +{ + std::string key(""); + + EXPECT_EQ(database_->DeleteToDistributedDB(key), true); +} + +/** + * @tc.name : DistributedDatabase_ClearDataByDevice_00100 + * @tc.number : ClearDataByDevice_00100 + * @tc.desc : Remove the device data from remote. + */ +HWTEST_F(DistributedDatabaseTest, ClearDataByDevice_00100, Function | SmallTest | Level1) +{ + std::string deviceId(""); + + EXPECT_EQ(database_->ClearDataByDevice(deviceId), true); +} + +/** + * @tc.name : DistributedDatabase_GetLocalDeviceId_00100 + * @tc.number : GetLocalDeviceId_00100 + * @tc.desc : Get local device id. + */ +HWTEST_F(DistributedDatabaseTest, GetLocalDeviceId_00100, Function | SmallTest | Level1) +{ + std::string deviceId; + + EXPECT_EQ(database_->GetLocalDeviceId(deviceId), true); +} + +/** + * @tc.name : DistributedDatabase_GetLocalDeviceInfo_00100 + * @tc.number : GetLocalDeviceInfo_00100 + * @tc.desc : Get local device infomation. + */ +HWTEST_F(DistributedDatabaseTest, GetLocalDeviceInfo_00100, Function | SmallTest | Level1) +{ + DistributedDatabase::DeviceInfo deviceInfo; + + EXPECT_EQ(database_->GetLocalDeviceInfo(deviceInfo), true); +} + +/** + * @tc.name : DistributedDatabase_GetDeviceInfoList_00100 + * @tc.number : GetDeviceInfoList_00100 + * @tc.desc : Get infomations for all devices. + */ +HWTEST_F(DistributedDatabaseTest, GetDeviceInfoList_00100, Function | SmallTest | Level1) +{ + std::vector deviceInfos; + + EXPECT_EQ(database_->GetDeviceInfoList(deviceInfos), true); +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/services/distributed/test/unittest/distributed_notification_manager_test.cpp b/services/distributed/test/unittest/distributed_notification_manager_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c6cac5a4cf871d27f50b2b6dd7ace51a1b93ca8d --- /dev/null +++ b/services/distributed/test/unittest/distributed_notification_manager_test.cpp @@ -0,0 +1,184 @@ +/* + * 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 "gtest/gtest.h" + +#include "distributed_notification_manager.h" + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class DistributedNotificationManagerTest : public testing::Test { +public: + void SetUp() override; + void TearDown() override; + +public: + virtual void OnPublish( + const std::string &deviceId, const std::string &bundleName, sptr &request) {}; + virtual void OnUpdate( + const std::string &deviceId, const std::string &bundleName, sptr &request) {}; + virtual void OnDelete( + const std::string &deviceId, const std::string &bundleName, const std::string &label, int32_t id) {}; + +protected: + std::shared_ptr distributedManager_; +}; + +void DistributedNotificationManagerTest::SetUp() +{ + distributedManager_ = DistributedNotificationManager::GetInstance(); +} + +void DistributedNotificationManagerTest::TearDown() +{ + distributedManager_ = nullptr; + DistributedNotificationManager::DestroyInstance(); +} + +/** + * @tc.name : Distributed_Publish_00100 + * @tc.number : Distributed_Publish_00100 + * @tc.desc : Publish a local notification to remote used distributed. + */ +HWTEST_F(DistributedNotificationManagerTest, Distributed_Publish_00100, Function | SmallTest | Level1) +{ + sptr request = new NotificationRequest(1000); + request->SetLabel("