From 62ed29c855d96f78bfe7ca5f380c37e8455546ac Mon Sep 17 00:00:00 2001 From: zhaoyuan Date: Wed, 13 Oct 2021 10:16:20 +0000 Subject: [PATCH 001/131] update depends in sa xml and modify the unsubscribe code Signed-off-by: zhaoyuan --- frameworks/ans/core/src/ans_manager_proxy.cpp | 20 +++++++++++-------- interfaces/kits/napi/ans/src/unsubscribe.cpp | 11 +++++++++- sa_profile/3203.xml | 2 ++ .../ans/src/advanced_notification_service.cpp | 4 ++-- 4 files changed, 26 insertions(+), 11 deletions(-) diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index ae493cd..b7ac0f7 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -354,10 +354,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 +420,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; diff --git a/interfaces/kits/napi/ans/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp index f50a804..a8b188e 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; @@ -48,8 +50,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SubscriberInstancesInfo subscriberInstancesInfo; if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { - return nullptr; + ANS_LOGW("Subscriber not found"); } + paras.objectInfo = subscriberInstancesInfo.subscriber; ANS_LOGI("ObjectInfo = %{public}p start", paras.objectInfo); @@ -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)); }, diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml index 7f45c1f..ccaa7c4 100755 --- a/sa_profile/3203.xml +++ b/sa_profile/3203.xml @@ -17,6 +17,8 @@ 3203 /system/lib/libans.z.so + 3299 + 5000 true false 1 diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 875112f..d67e8c0 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1403,10 +1403,10 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrPostTask(std::bind([&]() { + handler_->PostTask(std::bind([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); } })); } -- Gitee From 597de16d423c7ff623fe7d69f2bc45c521e78066 Mon Sep 17 00:00:00 2001 From: zmx <1029211721@qq.com> Date: Mon, 18 Oct 2021 09:39:14 +0800 Subject: [PATCH 002/131] samgr part name rectify Signed-off-by: zmx <1029211721@qq.com> Change-Id: I2bcc2de6257d85f49fd31b270d6fbf233093d422 --- frameworks/ans/core/BUILD.gn | 2 +- frameworks/ans/native/BUILD.gn | 2 +- frameworks/ans/test/moduletest/BUILD.gn | 8 ++++---- frameworks/wantagent/BUILD.gn | 2 +- notification.gni | 2 +- services/ans/test/unittest/BUILD.gn | 2 +- services/test/moduletest/BUILD.gn | 2 +- 7 files changed, 10 insertions(+), 10 deletions(-) diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 4929685..69083c2 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -83,7 +83,7 @@ ohos_shared_library("ans_core") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] part_name = "ans_standard" diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 502edd9..835e149 100755 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -84,7 +84,7 @@ ohos_shared_library("ans_innerkits") { external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] if (is_double_framework) { diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index 0912b06..f2edf40 100755 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -113,7 +113,7 @@ ohos_moduletest("ans_fw_module_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -194,7 +194,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -272,7 +272,7 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" @@ -350,7 +350,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" diff --git a/frameworks/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn index 29d0b47..7121bed 100644 --- a/frameworks/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -74,7 +74,7 @@ ohos_shared_library("wantagent_innerkits") { "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] if (is_double_framework) { diff --git a/notification.gni b/notification.gni index 54fa446..61aa51b 100644 --- a/notification.gni +++ b/notification.gni @@ -38,5 +38,5 @@ ans_standard_external_deps = [ "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index d94e670..0f88ad8 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -88,7 +88,7 @@ ohos_unittest("ans_unit_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 3afbfa5..e982028 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -87,7 +87,7 @@ ohos_moduletest("ans_module_test") { "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", - "samgr_L2:samgr_proxy", + "samgr_standard:samgr_proxy", ] subsystem_name = "notification" -- Gitee From 3fa9c05b3b382908b45ae312221f536d8ea9e117 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 25 Oct 2021 15:26:16 +0000 Subject: [PATCH 003/131] Fix bugs and add update test case Signed-off-by: zhaoyuan17 --- .../ans/native/src/notification_sorting.cpp | 4 + .../ans/native/include/notification_sorting.h | 2 +- interfaces/kits/napi/ans/include/common.h | 3 +- interfaces/kits/napi/ans/src/common.cpp | 13 +- interfaces/kits/napi/ans/src/get_active.cpp | 260 ++++++++++-------- interfaces/kits/napi/ans/src/slot.cpp | 210 +++++++------- .../ans/src/advanced_notification_service.cpp | 99 +++++-- services/ans/src/notification_preferences.cpp | 18 +- .../advanced_notification_service_test.cpp | 4 +- 9 files changed, 358 insertions(+), 255 deletions(-) diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 0ff27d7..fc390cf 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 NotificationSlot(NotificationConstant::SlotType::OTHER); + return; + } slot_ = slot; } diff --git a/interfaces/innerkits/ans/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h index 4be3ba5..1efa272 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting.h @@ -175,7 +175,7 @@ private: bool isHiddenNotification_ {}; std::string groupKeyOverride_ {}; int32_t visiblenessOverride_ {}; - sptr slot_ {nullptr}; + sptr slot_ = new NotificationSlot(NotificationConstant::SlotType::OTHER); friend class AdvancedNotificationService; }; diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index ace3fef..8cd32ef 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -132,7 +132,8 @@ 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 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); diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 45f69f2..650e093 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -138,7 +138,7 @@ void Common::ReturnCallbackPromise(const napi_env &env, const CallbackPromiseInf 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"); } @@ -160,10 +160,15 @@ void Common::SetCallback( ANS_LOGI("end"); } -void Common::SetPromise(const napi_env &env, const napi_deferred &deferred, const napi_value &result) +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,7 +180,7 @@ 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; } } diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index 788fdd2..c424913 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -23,8 +23,10 @@ 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) @@ -67,6 +69,58 @@ napi_value ParseParametersByGetActive(const napi_env &env, const napi_callback_i return Common::NapiGetNull(env); } +void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status status, void *data) +{ + ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); + + if (!data) { + ANS_LOGE("Invalid async callback data"); + return; + } + + AsyncCallbackInfoActive *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); + } + } + + 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 GetAllActiveNotifications(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -95,52 +149,10 @@ napi_value GetAllActiveNotifications(napi_env env, napi_callback_info info) ANS_LOGI("GetAllActiveNotifications napi_create_async_work start"); AsyncCallbackInfoActive *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,6 +165,57 @@ 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; + } + + AsyncCallbackInfoActive *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"); @@ -181,52 +244,10 @@ napi_value GetActiveNotifications(napi_env env, napi_callback_info info) 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; - - 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,6 +260,36 @@ 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; + } + + AsyncCallbackInfoActive *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"); @@ -267,31 +318,10 @@ napi_value GetActiveNotificationCount(napi_env env, napi_callback_info info) 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; - - 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/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index c5ba3fe..4590c92 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -77,8 +77,8 @@ 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 { @@ -89,16 +89,16 @@ struct ParametersInfoGetSlotNumByBundle { 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 { @@ -109,9 +109,9 @@ struct ParametersInfoGetSlotsByBundle { struct AsyncCallbackInfoGetSlotsByBundle { napi_env env = nullptr; napi_async_work asyncWork = nullptr; - napi_value result = nullptr; ParametersInfoGetSlotsByBundle params; CallbackPromiseInfo info; + std::vector> slots; }; struct ParametersInfoRemoveSlot { @@ -594,6 +594,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; + } + + AsyncCallbackInfoGetSlot *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"); @@ -621,39 +657,10 @@ napi_value GetSlot(napi_env env, napi_callback_info info) ANS_LOGI("GetSlot napi_create_async_work start"); AsyncCallbackInfoGetSlot *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); @@ -696,15 +703,16 @@ napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) 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); + asynccallbackinfo->info.errorCode = + NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, 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); + 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); @@ -754,42 +762,39 @@ napi_value GetSlots(napi_env env, napi_callback_info info) [](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); - } + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(asynccallbackinfo->slots); }, [](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); + napi_value result = nullptr; + 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); @@ -843,42 +848,41 @@ napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) 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); - } + asynccallbackinfo->info.errorCode = + NotificationHelper::GetNotificationSlotsForBundle(bundleOption, asynccallbackinfo->slots); }, [](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); + napi_value result = nullptr; + 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); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index d67e8c0..153e6bc 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -502,8 +502,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 +524,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 +541,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 +561,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; } @@ -709,6 +725,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; } @@ -843,8 +863,13 @@ ErrCode AdvancedNotificationService::GetSlotsByBundle( } 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; } @@ -863,8 +888,12 @@ ErrCode AdvancedNotificationService::UpdateSlots( } 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; } @@ -883,8 +912,12 @@ ErrCode AdvancedNotificationService::UpdateSlotGroups( } 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; } @@ -943,8 +976,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; } @@ -1029,8 +1067,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 +1086,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; } @@ -1200,6 +1246,10 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( result = NotificationPreferences::GetInstance().GetNotificationsEnabled(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; @@ -1428,8 +1478,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; } @@ -1555,8 +1609,13 @@ 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; } diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index dc3ebcb..a95b1fc 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -295,7 +295,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 +333,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 +351,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 +369,7 @@ ErrCode NotificationPreferences::GetNotificationAllSlotInSlotGroup(const sptrIsSpecialBundleAllowedNotify( new NotificationBundleOption(TEST_DEFUALT_BUNDLE, SYSTEM_APP_UID), allowed), - (int)ERR_ANS_PREFERENCES_NOTIFICATION_BUNDLE_NOT_EXIST); + (int)ERR_OK); } /** @@ -1264,7 +1264,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) -- Gitee From bc6ecb8dfb1173d0b5c4dd618125bd2b584f13a2 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 26 Oct 2021 15:48:52 +0000 Subject: [PATCH 004/131] Remove notifications on app deleted Signed-off-by: zhaoyuan17 --- .../ans/src/advanced_notification_service.cpp | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 153e6bc..3d8eb02 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1453,11 +1453,27 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrPostTask(std::bind([bundleOption]() { + handler_->PostTask(std::bind([this, bundleOption]() { ErrCode result = NotificationPreferences::GetInstance().RemoveNotificationForBundle(bundleOption); if (result != ERR_OK) { ANS_LOGW("NotificationPreferences::RemoveNotificationForBundle failed: %{public}d", result); } + + std::vector keys = GetNotificationKeys(bundleOption); + 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); + } + } })); } -- Gitee From e5f684e04fdcaf2f0b81f301fc92976f4b8471c7 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sat, 30 Oct 2021 18:41:01 +0000 Subject: [PATCH 005/131] modify wantagent bug Signed-off-by: zhaoyuan17 --- .../kits/napi/wantagent/napi_want_agent.cpp | 41 +++++++++++-------- 1 file changed, 24 insertions(+), 17 deletions(-) diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index bce26d6..23b1504 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -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() @@ -306,7 +313,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,7 +326,7 @@ 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{ @@ -431,7 +438,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,7 +450,7 @@ 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{ @@ -553,7 +560,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,7 +572,7 @@ 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{ @@ -693,7 +700,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,7 +712,7 @@ 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{ @@ -778,7 +785,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 +830,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)); @@ -844,7 +851,7 @@ napi_value NAPI_Trigger(napi_env env, napi_callback_info info) 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; } @@ -969,7 +976,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 +986,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,7 +998,7 @@ 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{ @@ -1148,7 +1155,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 +1194,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)); @@ -1242,7 +1249,7 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) 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; } -- Gitee From cf02f9bc48c168673e5ae70a31719908760c18c4 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 2 Nov 2021 16:20:17 +0000 Subject: [PATCH 006/131] Fix wantagenthelper UT error Signed-off-by: zhaoyuan17 --- .../want_agent_helper_test/want_agent_helper_test.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) 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 156b5dd..32776ba 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 @@ -506,9 +506,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); } -- Gitee From a2f4e8d941a53a8a19420ce252dcc05f0b7e4784 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 3 Nov 2021 10:53:16 +0800 Subject: [PATCH 007/131] Fix bug Signed-off-by: zhaoyuan17 --- .../ans/core/include/ans_manager_interface.h | 6 + .../ans/core/include/ans_manager_proxy.h | 4 + .../ans/core/include/ans_manager_stub.h | 6 + .../ans/core/include/ans_notification.h | 17 + .../core/include/ans_subscriber_interface.h | 8 +- .../ans/core/include/ans_subscriber_proxy.h | 4 +- .../ans/core/include/ans_subscriber_stub.h | 8 +- frameworks/ans/core/src/ans_manager_proxy.cpp | 64 + frameworks/ans/core/src/ans_manager_stub.cpp | 61 + frameworks/ans/core/src/ans_notification.cpp | 46 +- .../ans/core/src/ans_subscriber_proxy.cpp | 30 +- .../ans/core/src/ans_subscriber_stub.cpp | 24 +- frameworks/ans/native/src/notification.cpp | 4 +- .../ans/native/src/notification_helper.cpp | 11 + .../ans/native/src/notification_request.cpp | 22 +- .../native/src/notification_subscriber.cpp | 12 +- .../test/moduletest/ans_fw_module_test.cpp | 100 +- .../ans_innerkits_module_publish_test.cpp | 85 +- .../ans/native/include/notification_helper.h | 18 +- .../ans/native/include/notification_request.h | 22 +- .../native/include/notification_subscriber.h | 16 +- interfaces/kits/napi/ans/include/cancel.h | 1 + interfaces/kits/napi/ans/include/common.h | 4 + interfaces/kits/napi/ans/include/remove.h | 1 + interfaces/kits/napi/ans/include/subscribe.h | 4 +- interfaces/kits/napi/ans/src/cancel.cpp | 105 +- interfaces/kits/napi/ans/src/common.cpp | 48 +- interfaces/kits/napi/ans/src/init.cpp | 2 + interfaces/kits/napi/ans/src/remove.cpp | 117 ++ interfaces/kits/napi/ans/src/subscribe.cpp | 162 +- .../include/advanced_notification_service.h | 4 + .../include/notification_subscriber_manager.h | 4 +- .../ans/src/advanced_notification_service.cpp | 91 +- .../src/notification_subscriber_manager.cpp | 45 +- .../advanced_notification_service_test.cpp | 64 +- .../notification_subscriber_manager_test.cpp | 4 +- services/test/moduletest/ans_module_test.cpp | 20 +- test/BUILD.gn | 5 +- test/common/acts/BUILD.gn | 40 + .../acts/actsnotificationfuzztest/BUILD.gn | 107 ++ .../actsnotificationfuzztest.cpp | 50 + .../include/notificationfuzzconfigparser.h | 76 + .../include/notificationfuzztestmanager.h | 106 ++ .../include/notificationgetparam.h | 444 +++++ .../notificationfuzzconfig/config.json | 153 ++ .../notificationfuzztest/ohos_test.xml | 25 + .../src/notificationfuzztestmanager.cpp | 921 +++++++++++ .../src/notificationgetparam.cpp | 1449 +++++++++++++++++ 48 files changed, 4285 insertions(+), 335 deletions(-) create mode 100644 test/common/acts/BUILD.gn create mode 100755 test/common/acts/actsnotificationfuzztest/BUILD.gn create mode 100644 test/common/acts/actsnotificationfuzztest/actsnotificationfuzztest.cpp create mode 100644 test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h create mode 100644 test/resource/notificationfuzztest/include/notificationfuzztestmanager.h create mode 100644 test/resource/notificationfuzztest/include/notificationgetparam.h create mode 100644 test/resource/notificationfuzztest/notificationfuzzconfig/config.json create mode 100644 test/resource/notificationfuzztest/ohos_test.xml create mode 100644 test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp create mode 100644 test/resource/notificationfuzztest/src/notificationgetparam.cpp diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 9f71a1a..7baefa8 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -104,6 +104,10 @@ public: virtual ErrCode IsAllowedNotify(bool &allowed) = 0; virtual ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) = 0; + virtual ErrCode CancelGroup(const std::string &groupName) = 0; + virtual ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) = 0; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) = 0; protected: @@ -158,6 +162,8 @@ protected: GET_CURRENT_APP_SORTING, IS_ALLOWED_NOTIFY, IS_SPECIAL_BUNDLE_ALLOWED_NOTIFY, + CANCEL_GROUP, + REMOVE_GROUP_BY_BUNDLE, SHELL_DUMP, }; }; diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index 80214ca..24a8105 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -93,6 +93,10 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; + ErrCode CancelGroup(const std::string &groupName) override; + ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; private: diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index f85ab60..082bec3 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -98,6 +98,10 @@ public: virtual ErrCode IsSpecialBundleAllowedNotify( const sptr &bundleOption, bool &allowed) override; + virtual ErrCode CancelGroup(const std::string &groupName) override; + virtual ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + virtual ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; private: @@ -155,6 +159,8 @@ private: ErrCode HandleIsAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleIsSpecialBundleAllowedNotify(MessageParcel &data, MessageParcel &reply); ErrCode HandleShellDump(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCancelGroup(MessageParcel &data, MessageParcel &reply); + ErrCode HandleRemoveGroupByBundle(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 100bb38..ce3893a 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -593,6 +593,23 @@ public: */ ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); + /** + * 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); + /** * Reset ans manager proxy when OnRemoteDied called. */ diff --git a/frameworks/ans/core/include/ans_subscriber_interface.h b/frameworks/ans/core/include/ans_subscriber_interface.h index 539f22a..e49cb26 100644 --- a/frameworks/ans/core/include/ans_subscriber_interface.h +++ b/frameworks/ans/core/include/ans_subscriber_interface.h @@ -34,8 +34,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; @@ -47,8 +47,8 @@ public: 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, diff --git a/frameworks/ans/core/include/ans_subscriber_proxy.h b/frameworks/ans/core/include/ans_subscriber_proxy.h index 1774567..f3101c5 100644 --- a/frameworks/ans/core/include/ans_subscriber_proxy.h +++ b/frameworks/ans/core/include/ans_subscriber_proxy.h @@ -29,8 +29,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; diff --git a/frameworks/ans/core/include/ans_subscriber_stub.h b/frameworks/ans/core/include/ans_subscriber_stub.h index 4d60ccf..b8c8b82 100644 --- a/frameworks/ans/core/include/ans_subscriber_stub.h +++ b/frameworks/ans/core/include/ans_subscriber_stub.h @@ -31,8 +31,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; @@ -45,8 +45,8 @@ public: 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); diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index b7ac0f7..5505d1e 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1744,6 +1744,70 @@ 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 ERR_OK; +} + ErrCode AnsManagerProxy::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { MessageParcel data; diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 5510247..cf1024b 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -176,6 +176,12 @@ const std::map 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::HandleShellDump(MessageParcel &data, MessageParcel &reply) { std::string dumpOption; @@ -1512,6 +1560,19 @@ ErrCode AnsManagerStub::IsSpecialBundleAllowedNotify(const sptr &bundleOption, const std::string &groupName) +{ + ANS_LOGW("AnsManagerStub::RemoveGroupByBundle called!"); + return ERR_INVALID_OPERATION; +} + ErrCode AnsManagerStub::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { ANS_LOGW("AnsManagerStub::ShellDump called!"); diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index da55aed..74d77b8 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -165,7 +165,7 @@ ErrCode AnsNotification::GetNotificationSlotNumAsBundle(const NotificationBundle return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->GetSlotNumAsBundle(bo, num); } @@ -519,7 +519,7 @@ ErrCode AnsNotification::RemoveNotification( return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->RemoveNotification(bo, notificationId, label); } @@ -530,7 +530,7 @@ ErrCode AnsNotification::RemoveAllNotifications(const NotificationBundleOption & return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->RemoveAllNotifications(bo); } @@ -541,7 +541,7 @@ ErrCode AnsNotification::RemoveNotificationsByBundle(const NotificationBundleOpt return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->DeleteByBundle(bo); } @@ -567,7 +567,7 @@ 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); } @@ -579,7 +579,7 @@ ErrCode AnsNotification::UpdateNotificationSlots( return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->UpdateSlots(bo, slots); } @@ -591,7 +591,7 @@ ErrCode AnsNotification::UpdateNotificationSlotGroups( 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 +626,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); } @@ -656,7 +656,7 @@ ErrCode AnsNotification::SetNotificationsEnabledForSpecifiedBundle( return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->SetNotificationsEnabledForSpecialBundle(deviceId, bo, enabled); } @@ -667,7 +667,7 @@ ErrCode AnsNotification::SetShowBadgeEnabledForBundle(const NotificationBundleOp return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->SetShowBadgeEnabledForBundle(bo, enabled); } @@ -678,7 +678,7 @@ ErrCode AnsNotification::GetShowBadgeEnabledForBundle(const NotificationBundleOp return ERR_ANS_SERVICE_NOT_CONNECTED; } - sptr bo(new NotificationBundleOption(bundleOption)); + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); return ansManagerProxy_->GetShowBadgeEnabledForBundle(bo, enabled); } @@ -710,6 +710,28 @@ ErrCode AnsNotification::GetDisturbMode(NotificationConstant::DisturbMode &distu return ansManagerProxy_->GetDisturbMode(disturbMode); } +ErrCode AnsNotification::CancelGroup(const std::string &groupName) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + return ansManagerProxy_->CancelGroup(groupName); +} + +ErrCode AnsNotification::RemoveGroupByBundle( + const NotificationBundleOption &bundleOption, const std::string &groupName) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + sptr bo(new (std::nothrow) NotificationBundleOption(bundleOption)); + return ansManagerProxy_->RemoveGroupByBundle(bo, groupName); +} + void AnsNotification::ResetAnsManagerProxy() { ANS_LOGI("enter"); @@ -754,7 +776,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; diff --git a/frameworks/ans/core/src/ans_subscriber_proxy.cpp b/frameworks/ans/core/src/ans_subscriber_proxy.cpp index f42f9a8..7cef65d 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; } } diff --git a/frameworks/ans/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp index 8ecb572..716affd 100644 --- a/frameworks/ans/core/src/ans_subscriber_stub.cpp +++ b/frameworks/ans/core/src/ans_subscriber_stub.cpp @@ -28,10 +28,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, @@ -75,19 +75,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; } @@ -194,10 +190,10 @@ ErrCode AnsSubscriberStub::HandleOnDisturbModeChanged(MessageParcel &data, Messa 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) diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index c69e086..9e82978 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -100,7 +100,7 @@ std::string Notification::GetGroup() const if (request_ == nullptr) { return ""; } - return request_->GetGroupValue(); + return request_->GetGroupName(); } int32_t Notification::GetId() const @@ -160,7 +160,7 @@ bool Notification::IsGroup() const if (request_ == nullptr) { return false; } - return !(request_->GetGroupValue() == ""); + return !(request_->GetGroupName() == ""); } bool Notification::IsFloatingIcon() const diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 87d459c..7b2ae30 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -305,5 +305,16 @@ ErrCode NotificationHelper::GetDisturbMode(NotificationConstant::DisturbMode &di { return DelayedSingleton::GetInstance()->GetDisturbMode(disturbMode); } + +ErrCode NotificationHelper::CancelGroup(const std::string &groupName) +{ + return DelayedSingleton::GetInstance()->CancelGroup(groupName); +} + +ErrCode NotificationHelper::RemoveGroupByBundle( + const NotificationBundleOption &bundleOption, const std::string &groupName) +{ + return DelayedSingleton::GetInstance()->RemoveGroupByBundle(bundleOption, groupName); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index b346882..801fb1e 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -74,7 +74,7 @@ NotificationRequest::NotificationRequest(const NotificationRequest &other) this->settingsText_ = other.settingsText_; this->creatorBundleName_ = other.creatorBundleName_; this->ownerBundleName_ = other.ownerBundleName_; - this->groupValue_ = other.groupValue_; + this->groupName_ = other.groupName_; this->statusBarText_ = other.statusBarText_; this->label_ = other.label_; this->shortcutId_ = other.shortcutId_; @@ -133,7 +133,7 @@ NotificationRequest &NotificationRequest::operator=(const NotificationRequest &o this->settingsText_ = other.settingsText_; this->creatorBundleName_ = other.creatorBundleName_; this->ownerBundleName_ = other.ownerBundleName_; - this->groupValue_ = other.groupValue_; + this->groupName_ = other.groupName_; this->statusBarText_ = other.statusBarText_; this->label_ = other.label_; this->shortcutId_ = other.shortcutId_; @@ -472,14 +472,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 @@ -720,7 +720,7 @@ std::string NotificationRequest::Dump() ", creatorBundleName = " + creatorBundleName_ + ", creatorPid = " + std::to_string(static_cast(creatorPid_)) + ", creatorUid = " + std::to_string(static_cast(creatorUid_)) + - ", ownerBundleName = " + ownerBundleName_ + ", groupValue = " + groupValue_ + + ", ownerBundleName = " + ownerBundleName_ + ", groupName = " + groupName_ + ", statusBarText = " + statusBarText_ + ", label = " + label_ + ", shortcutId = " + shortcutId_ + ", sortingKey = " + sortingKey_ + ", groupAlertType = " + std::to_string(static_cast(groupAlertType_)) + @@ -824,8 +824,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; } @@ -1127,8 +1127,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; } diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index 4220ea0..e26174d 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -39,22 +39,22 @@ NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &s recipient_ = new 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) diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index d851d96..b906561 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -74,34 +74,20 @@ 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 { @@ -246,15 +232,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); } @@ -357,8 +343,7 @@ public: { 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,9 +366,7 @@ 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; } } } @@ -408,12 +391,12 @@ public: waitOnUnSubscriber_ = NotificationConstant::SubscribeResult::RESOURCES_FAIL; } - uint32_t getWaitOnSubscriber() + bool getWaitOnSubscriber() { return waitOnSubscriber_; } - uint32_t getWaitOnUnSubscriber() + bool getWaitOnUnSubscriber() { return waitOnUnSubscriber_; } @@ -474,8 +457,8 @@ public: } private: - uint32_t waitOnSubscriber_; - uint32_t waitOnUnSubscriber_; + bool waitOnSubscriber_ = false; + bool waitOnUnSubscriber_ = false; bool waitOnConsumed_ = false; std::vector> onConsumedReq_; std::vector> onConsumedWithSortingMapReq_; @@ -572,8 +555,8 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L } 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_TRUE(eventParser.getWaitOnSubscriber()); + EXPECT_TRUE(eventParser.getWaitOnUnSubscriber()); subscriber.ClearEvents(); SleepForFC(); } @@ -759,19 +742,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 +775,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,18 +815,16 @@ 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(); SleepForFC(); } 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 a1ba734..e32c361 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -61,6 +61,8 @@ 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; @@ -72,12 +74,12 @@ 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(); } @@ -93,6 +95,7 @@ public: virtual void OnCanceled(const std::shared_ptr &request) override { + GTEST_LOG_(INFO) << "ANS_Interface_MT::OnCanceled request : " << request->GetNotificationRequest().Dump(); OnCanceledReceived = true; } @@ -347,7 +350,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()); @@ -885,7 +888,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); @@ -1133,7 +1136,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_07000, Function NotificationRequest req; req.SetContent(content); req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); - req.SetGroupValue("groupnotifcation"); + req.SetGroupName("groupnotifcation"); req.SetGroupOverview(true); req.SetNotificationId(CASE_SIXTEEN); req.SetGroupAlertType(NotificationRequest::GroupAlertType::ALL); @@ -1203,5 +1206,77 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_GetActiveNotifications_ WaitOnUnsubscribeResult(); OnCanceledReceived = false; } + +/** + * @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_CancelGroup_10100, Function | MediumTest | Level1) +{ + NotificationSubscribeInfo info = NotificationSubscribeInfo(); + info.AddAppName("bundleName"); + + auto subscriber = TestAnsSubscriber(); + g_subscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber, info)); + WaitOnSubscribeResult(); + + 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::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, info)); + WaitOnUnsubscribeResult(); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index b6b5fbf..f0873ff 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -587,8 +587,24 @@ public: * @return Returns get disturb mode result. */ static ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); -}; + /** + * 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); +}; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 1536f67..d5f6c81 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -325,7 +325,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. @@ -530,8 +530,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 +542,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. @@ -903,7 +903,7 @@ private: std::string settingsText_ {}; std::string creatorBundleName_ {}; std::string ownerBundleName_ {}; - std::string groupValue_ {}; + std::string groupName_ {}; std::string statusBarText_ {}; std::string label_ {}; std::string shortcutId_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 6cbdecc..114a52f 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -59,11 +59,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 +81,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. @@ -127,9 +123,9 @@ private: SubscriberImpl(NotificationSubscriber &subscriber); ~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; diff --git a/interfaces/kits/napi/ans/include/cancel.h b/interfaces/kits/napi/ans/include/cancel.h index 6d41052..219005d 100644 --- a/interfaces/kits/napi/ans/include/cancel.h +++ b/interfaces/kits/napi/ans/include/cancel.h @@ -24,6 +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 8cd32ef..bf19774 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -132,6 +132,9 @@ public: static void SetCallback( const napi_env &env, const napi_ref &callbackIn, const int &errorCode, 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); @@ -214,6 +217,7 @@ public: static napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); private: + static const int ARGS_ONE = 1; static const int ARGS_TWO = 2; static const int PARAM0 = 0; static const int PARAM1 = 1; diff --git a/interfaces/kits/napi/ans/include/remove.h b/interfaces/kits/napi/ans/include/remove.h index 2e03ac5..fddba90 100644 --- a/interfaces/kits/napi/ans/include/remove.h +++ b/interfaces/kits/napi/ans/include/remove.h @@ -25,6 +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 diff --git a/interfaces/kits/napi/ans/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h index 5046928..77a3174 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -39,9 +39,9 @@ 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; diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 71ea420..3edad37 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -20,6 +20,8 @@ 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 +37,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"); @@ -77,7 +91,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, 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, napi_ref &callback) { ANS_LOGI("enter"); @@ -96,6 +110,35 @@ napi_value ParseParametersByCancelAll(const napi_env &env, const napi_callback_i return Common::NapiGetNull(env); } +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancelGroup ¶s) +{ + ANS_LOGI("enter"); + + 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"); + + napi_valuetype valuetype = napi_undefined; + // argv[0]: groupName: 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)); + paras.groupName = str; + + // argv[1]: callback + if (argc >= CANCEL_GROUP_MAX_PARA) { + NAPI_CALL(env, napi_typeof(env, argv[CANCEL_GROUP_MIN_PARA], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[CANCEL_GROUP_MIN_PARA], 1, ¶s.callback); + } + + return Common::NapiGetNull(env); +} + napi_value Cancel(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -159,7 +202,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 (ParseParameters(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -210,5 +253,63 @@ 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 650e093..62765bf 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -77,7 +77,8 @@ static napi_value GetNotificationMultiLineContent( 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); - +static napi_value GetNotificationGroupName( + const napi_env &env, const napi_value &value, NotificationRequest &request); Common::Common() {} @@ -160,6 +161,20 @@ void Common::SetCallback( ANS_LOGI("end"); } +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) { @@ -411,6 +426,10 @@ napi_value Common::SetNotificationRequest( } } + // 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); @@ -1141,6 +1160,11 @@ napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value return nullptr; } + // groupName?: string + if (GetNotificationGroupName(env, value, request) == nullptr) { + return nullptr; + } + return Common::NapiGetNull(env); } @@ -1395,6 +1419,28 @@ napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value return Common::NapiGetNull(env); } +napi_value 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 Common::NapiGetNull(env); +} + napi_value GetNotificationRemovalWantAgent(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 864e4a7..46ccbec 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -47,6 +47,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,6 +57,7 @@ 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), diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index 90c71f2..cd9faf5 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -29,6 +29,9 @@ 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; NotificationKey key; @@ -47,6 +50,19 @@ struct AsyncCallbackInfoRemove { CallbackPromiseInfo info; }; +struct RemoveParamsGroupByBundle { + BundleOption 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"); @@ -145,6 +161,45 @@ napi_value ParseParametersByRemoveAll(const napi_env &env, const napi_callback_i 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[0], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type.Object expected."); + auto retValue = Common::GetBundleOption(env, argv[0], params.option); + if (retValue == nullptr) { + ANS_LOGE("GetBundleOption failed."); + return nullptr; + } + + // argv[1]: groupName: string + NAPI_CALL(env, napi_typeof(env, argv[1], &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[1], 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[REMOVE_GROUP_BY_BUNDLE_MIN_PARA], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[REMOVE_GROUP_BY_BUNDLE_MIN_PARA], 1, ¶ms.callback); + } + + return Common::NapiGetNull(env); +} + napi_value Remove(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -275,5 +330,67 @@ napi_value RemoveAll(napi_env env, napi_callback_info info) } } +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; + NotificationBundleOption bundleOption( + asynccallbackinfo->params.option.bundle, asynccallbackinfo->params.option.uid); + ANS_LOGI("option.bundle = %{public}s, option.uid = %{public}d, groupName = %{public}s", + asynccallbackinfo->params.option.bundle.c_str(), + asynccallbackinfo->params.option.uid, + asynccallbackinfo->params.groupName.c_str()); + asynccallbackinfo->info.errorCode = + NotificationHelper::RemoveGroupByBundle(bundleOption, asynccallbackinfo->params.groupName); + }, + [](napi_env env, napi_status status, void *data) { + ANS_LOGI("RemoveGroupByBundle napi_create_async_work end"); + 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; + } + }, + (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/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 4edb90d..94b8801 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -141,6 +141,37 @@ 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"); + 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) { @@ -194,39 +225,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdata; - 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; - }); + UvQueueWorkOnCanceled); } void SubscriberInstance::OnConsumed(const std::shared_ptr &request) @@ -298,18 +297,15 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrenv, &result); - int error = 0; if (!SetSubscribeCallbackData(dataWorkerData->env, dataWorkerData->request, dataWorkerData->sortingMap, NO_DELETE_REASON, result)) { - result = Common::NapiGetNull(dataWorkerData->env); - error = ERROR; + ANS_LOGE("Failed to convert data to JS"); } else { - error = NO_ERROR; + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); delete dataWorkerData; dataWorkerData = nullptr; @@ -376,14 +372,11 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr } 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; + ANS_LOGE("Failed to convert data to JS"); } else { - error = NO_ERROR; + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); } - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, error, result); delete dataWorkerData; dataWorkerData = nullptr; @@ -392,7 +385,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr }); } -void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult result) +void SubscriberInstance::OnConnected() { ANS_LOGI("enter"); @@ -400,7 +393,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,7 +407,6 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult return; } - dataWorker->result = (int)result; dataWorker->env = subscribeCallbackInfo_.env; dataWorker->ref = subscribeCallbackInfo_.ref; @@ -443,11 +434,8 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult ANS_LOGE("dataWorkerData is null"); return; } - // result: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); delete dataWorkerData; dataWorkerData = nullptr; @@ -456,7 +444,7 @@ void SubscriberInstance::OnSubscribeResult(NotificationConstant::SubscribeResult }); } -void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResult result) +void SubscriberInstance::OnDisconnected() { ANS_LOGI("enter"); @@ -464,7 +452,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 +466,6 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu return; } - dataWorker->result = (int)result; dataWorker->env = unsubscribeCallbackInfo_.env; dataWorker->ref = unsubscribeCallbackInfo_.ref; dataWorker->subscriber = this; @@ -508,11 +494,8 @@ void SubscriberInstance::OnUnsubscribeResult(NotificationConstant::SubscribeResu ANS_LOGE("dataWorkerData is null"); return; } - // result: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->result, &result); - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); @@ -574,7 +557,7 @@ void SubscriberInstance::OnDied() } Common::SetCallback( - dataWorkerData->env, dataWorkerData->ref, NO_ERROR, Common::NapiGetNull(dataWorkerData->env)); + dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); delete dataWorkerData; dataWorkerData = nullptr; @@ -584,68 +567,7 @@ void SubscriberInstance::OnDied() } void SubscriberInstance::OnDisturbModeChanged(int disturbMode) -{ - ANS_LOGI("enter"); - - if (disturbModeCallbackInfo_.ref == nullptr) { - ANS_LOGI("disturbModeChange callback unset"); - return; - } - ANS_LOGI("OnDisturbModeChanged disturbMode = %{public}d", disturbMode); - - uv_loop_s *loop = nullptr; - napi_get_uv_event_loop(disturbModeCallbackInfo_.env, &loop); - if (loop == nullptr) { - ANS_LOGE("loop instance is nullptr"); - return; - } - - NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); - if (dataWorker == nullptr) { - ANS_LOGE("new dataWorker failed"); - return; - } - - dataWorker->disturbMode = disturbMode; - dataWorker->env = disturbModeCallbackInfo_.env; - dataWorker->ref = disturbModeCallbackInfo_.ref; - - uv_work_t *work = new (std::nothrow) uv_work_t; - if (work == nullptr) { - ANS_LOGE("new work failed"); - return; - } - - work->data = (void *)dataWorker; - - uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDisturbModeChanged uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - // disturbMode: number - napi_value result = nullptr; - napi_create_int32(dataWorkerData->env, dataWorkerData->disturbMode, &result); - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, NO_ERROR, result); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); -} +{} void SubscriberInstance::SetCancelCallbackInfo(const napi_env &env, const napi_ref &ref) { diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 67445a1..c05bd30 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -101,6 +101,10 @@ public: ErrCode IsAllowedNotify(bool &allowed) override; ErrCode IsSpecialBundleAllowedNotify(const sptr &bundleOption, bool &allowed) override; + ErrCode CancelGroup(const std::string &groupName) override; + ErrCode RemoveGroupByBundle( + const sptr &bundleOption, const std::string &groupName) override; + ErrCode ShellDump(const std::string &dumpOption, std::vector &dumpInfo) override; // SystemEvent diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index 0e1ff2c..0758789 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -57,9 +57,9 @@ private: 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( diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 3d8eb02..f91e697 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -961,8 +961,13 @@ ErrCode AdvancedNotificationService::GetShowBadgeEnabledForBundle( } 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; } @@ -1045,11 +1050,11 @@ ErrCode AdvancedNotificationService::Unsubscribe( ANS_LOGD("%{public}s", __FUNCTION__); if (subscriber == nullptr) { - ANS_LOGE("Client is not a system app"); return ERR_ANS_INVALID_PARAM; } if (!IsSystemApp()) { + ANS_LOGE("Client is not a system app"); return ERR_ANS_NON_SYSTEM_APP; } @@ -1636,5 +1641,85 @@ ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const 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()) && + (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); + } + } + })); + + 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 (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->bundleOption->GetBundleName() == bundle->GetBundleName()) && + (record->bundleOption->GetUid() == bundle->GetUid()) && !record->request->IsUnremovable() && + (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); + } + } + })); + + return ERR_OK; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index fedc523..b98b570 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -53,13 +53,12 @@ ErrCode NotificationSubscriberManager::AddSubscriber( return ERR_ANS_INVALID_PARAM; } - AppExecFwk::EventHandler::Callback addSubscriberFunc = - std::bind(&NotificationSubscriberManager::AddSubscriberInner, this, subscriber, subscribeInfo); - - if (!handler_->PostTask(addSubscriberFunc, 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->AddSubscriberInner(subscriber, subscribeInfo); + }), + AppExecFwk::EventQueue::Priority::HIGH); + return result; } ErrCode NotificationSubscriberManager::RemoveSubscriber( @@ -70,13 +69,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( @@ -214,7 +212,7 @@ void NotificationSubscriberManager::RemoveRecordInfo( } } -void NotificationSubscriberManager::AddSubscriberInner( +ErrCode NotificationSubscriberManager::AddSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo) { std::shared_ptr record = FindSubscriberRecord(subscriber); @@ -223,31 +221,29 @@ void NotificationSubscriberManager::AddSubscriberInner( 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,11 +253,11 @@ 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( @@ -306,6 +302,5 @@ void NotificationSubscriberManager::NotifyDisturbModeChangedInner(const Notifica record->subscriber->OnDisturbModeChanged(mode); } } - } // 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 b54d4b5..de51a5b 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -80,9 +80,9 @@ 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 {} @@ -618,14 +618,18 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, /** * @tc.number : AdvancedNotificationServiceTest_02800 * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 - * @tc.desc : Test GetShowBadgeEnabledForBundle function when no bundle + * @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); } /** @@ -1068,7 +1072,7 @@ 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); } /** @@ -1385,5 +1389,55 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10200, EXPECT_EQ(advancedNotificationService_->Publish("label", req), (int)ERR_ANS_ICON_OVER_SIZE); } +/** + * @tc.number : AdvancedNotificationServiceTest_10300 + * @tc.name : AMS_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 : AMS_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(); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp index 2c62f96..40b26ce 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -36,9 +36,9 @@ 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 {} diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 52d333e..1a76cf3 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -35,16 +35,16 @@ class TestAnsSubscriber : public NotificationSubscriber { public: ~TestAnsSubscriber(){}; - void OnSubscribeResult(NotificationConstant::SubscribeResult result) override + void OnConnected() override { if (subscriberCb_ != nullptr) { - subscriberCb_(result); + subscriberCb_(); } } - void OnUnsubscribeResult(NotificationConstant::SubscribeResult result) override + void OnDisconnected() override { if (unSubscriberCb_ != nullptr) { - unSubscriberCb_(result); + unSubscriberCb_(); } } void OnDied() override @@ -74,8 +74,8 @@ public: ConsumedFunc consumedCb_ = nullptr; CanceledFunc canceledCb_ = nullptr; - std::function unSubscriberCb_ = nullptr; - std::function subscriberCb_ = nullptr; + std::function unSubscriberCb_ = nullptr; + std::function subscriberCb_ = nullptr; }; class AnsModuleTest : public testing::Test { @@ -1465,7 +1465,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0064, Function | SmallTest | Level1) sptr subscriberInfo = new NotificationSubscribeInfo(); subscriberInfo->AddAppName("bundleName"); g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); - subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + subscriber->unSubscriberCb_ = []() { passed = true; }; g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); EXPECT_TRUE(passed); } @@ -1480,7 +1480,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0065, Function | SmallTest | Level1) // subscriber auto subscriber = new TestAnsSubscriber(); g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); - subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + subscriber->unSubscriberCb_ = []() { passed = true; }; g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); EXPECT_TRUE(passed); } @@ -1848,7 +1848,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0110, Function | SmallTest | Level1) auto subscriber = new TestAnsSubscriber(); sptr subscriberInfo = new NotificationSubscribeInfo(); subscriberInfo->AddAppName("bundleName"); - subscriber->unSubscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + subscriber->unSubscriberCb_ = []() { passed = true; }; g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); // unsubscriber @@ -1867,7 +1867,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0111, Function | SmallTest | Level1) auto subscriber = new TestAnsSubscriber(); sptr subscriberInfo = new NotificationSubscribeInfo(); subscriberInfo->AddAppName("bundleName"); - subscriber->subscriberCb_ = [](NotificationConstant::SubscribeResult) { passed = true; }; + subscriber->subscriberCb_ = []() { passed = true; }; g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); EXPECT_EQ(passed, true); diff --git a/test/BUILD.gn b/test/BUILD.gn index ab4862f..7f120ed 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -24,5 +24,8 @@ config("system_test_config") { group("systemtest") { testonly = true - deps = [ "resource\ansSTSlotGroupTest:ansSTSlotGroupTest" ] + deps = [ + "common\acts:actsnotificationtest", + "resource\ansSTSlotGroupTest:ansSTSlotGroupTest", + ] } diff --git a/test/common/acts/BUILD.gn b/test/common/acts/BUILD.gn new file mode 100644 index 0000000..e944f07 --- /dev/null +++ b/test/common/acts/BUILD.gn @@ -0,0 +1,40 @@ +# 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/ces_standard/event.gni") +import("//build/ohos.gni") + +config("ansfwk_kits_test_config") { + visibility = [ ":*" ] + + include_dirs = [ + "//utils/native/base/include", + "//foundation/appexecfwk/standard/common/log/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/appexecfwk/standard/services/bundlemgr/include", + "//utils/system/safwk/native/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include/ohos/aafwk/base", + "${services_path}/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/distributedschedule/safwk/services/safwk/include", + ] +} + +group("actsnotificationtest") { + testonly = true + + deps = [ "actsnotificationfuzztest:actsnotificationfuzztest" ] +} diff --git a/test/common/acts/actsnotificationfuzztest/BUILD.gn b/test/common/acts/actsnotificationfuzztest/BUILD.gn new file mode 100755 index 0000000..5ee78f9 --- /dev/null +++ b/test/common/acts/actsnotificationfuzztest/BUILD.gn @@ -0,0 +1,107 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/systemtest" + +ohos_systemtest("ActsNotificationFuzzTest") { + module_out_path = module_output_path + resource_config_file = + "${ans_standard_path}/test/resource/notificationfuzztest/ohos_test.xml" + + sources = [ + "${ans_standard_path}/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp", + "${ans_standard_path}/test/resource/notificationfuzztest/src/notificationgetparam.cpp", + "actsnotificationfuzztest.cpp", + ] + + configs = [ "${ans_standard_path}/test/common/acts:ansfwk_kits_test_config" ] + + include_dirs = [ + "//utils/native/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//base/notification/ans_standard/frameworks/ans/core/include", + "//base/notification/ans_standard/interfaces/innerkits/ans/native/include", + "//base/notification/ans_standard/services/ans/include", + "//third_party/json/single_include", + "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_core/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include", + "//foundation/appexecfwk/adapter/interfaces/innerkits/appexecfwk_base/include", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager/include", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/aafwk/standard/frameworks/kits/ability/native/include", + "//foundation/aafwk/standard/services/abilitymgr/include", + "//foundation/multimodalinput/input/interfaces/native/innerkits/event/include", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", + "//foundation/appexecfwk/standard/kits/appkit/native/app/include/task", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/threading", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/dispatcher", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher/include/task", + ] + + cflags = [] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "//base/global/resmgr_standard/frameworks/resmgr:global_resmgr", + "//base/notification/ans_standard/frameworks/ans/core:ans_core", + "//base/notification/ans_standard/frameworks/ans/native:ans_innerkits", + "//base/notification/ans_standard/frameworks/wantagent:native_wantagent", + "//base/notification/ans_standard/services/ans:ans_targets", + "//base/notification/ces_standard/frameworks/common:libevent_common", + "//base/notification/ces_standard/frameworks/native:cesfwk_innerkits", + "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/ability_manager:ability_manager", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", + "//foundation/aafwk/standard/services/abilitymgr:abilityms", + "//foundation/appexecfwk/standard/interfaces/innerkits/task_dispatcher:appkit_dispatcher_td", + "//foundation/appexecfwk/standard/kits:appkit_native", + "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//foundation/multimodalinput/input/frameworks/proxy:libmmi-client", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + defines = [ + "APP_LOG_TAG = \"AnsFwkKitsTest\"", + "LOG_DOMAIN = 0xD002200", + ] + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "native_appdatamgr:native_appdatafwk", + "native_appdatamgr:native_dataability", + "native_appdatamgr:native_rdb", + ] +} + +group("actsnotificationfuzztest") { + testonly = true + + deps = [ ":ActsNotificationFuzzTest" ] +} diff --git a/test/common/acts/actsnotificationfuzztest/actsnotificationfuzztest.cpp b/test/common/acts/actsnotificationfuzztest/actsnotificationfuzztest.cpp new file mode 100644 index 0000000..68c3dc8 --- /dev/null +++ b/test/common/acts/actsnotificationfuzztest/actsnotificationfuzztest.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 "../../../resource/notificationfuzztest/include/notificationfuzztestmanager.h" + +#include +#include + +using namespace testing::ext; +namespace OHOS { +namespace Notification { +class ActsNotificationFuzzTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void ActsNotificationFuzzTest::SetUpTestCase() +{} + +void ActsNotificationFuzzTest::TearDownTestCase() +{} + +void ActsNotificationFuzzTest::SetUp() +{} + +void ActsNotificationFuzzTest::TearDown() +{} + +HWTEST_F(ActsNotificationFuzzTest, ACTS_FuzzTest_0100, Function | MediumTest | Level1) +{ + std::cout << "fuzztest start" << std::endl; + NotificationFuzzTestManager::GetInstance()->StartFuzzTest(); + std::cout << "fuzztest end" << std::endl; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h new file mode 100644 index 0000000..d6d96c2 --- /dev/null +++ b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h @@ -0,0 +1,76 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#ifndef NOTIFICATION_FUZZ_CONFIG_PARSER_H +#define NOTIFICATION_FUZZ_CONFIG_PARSER_H + +#include +#include +#include +#include + +#include "nlohmann/json.hpp" +namespace OHOS { +const std::string FUZZ_TEST_CONFIG_FILE_PATH {"/data/fuzztestconfig/config.json"}; + +const std::string FUZZ_TEST_MAIN_LOOP_KEY {"flag"}; + +struct FuzzTestData { + int32_t mainLoopFlag {0}; + std::vector methodVec {}; +}; + +class FuzzConfigParser { +public: + void ParseFromFile4FuzzTest(const std::string &path, FuzzTestData &ftd) + { + std::cout << __func__ << std::endl; + if (path.empty()) { + std::cout << __FUNCTION__ << " invalid file path, check!" << std::endl; + return; + } + + nlohmann::json jsonObj; + std::ifstream(path) >> jsonObj; + std::cout << path; + for (auto it = jsonObj.begin(); it != jsonObj.end(); ++it) { + if (!it.key().compare(FUZZ_TEST_MAIN_LOOP_KEY)) { + ftd.mainLoopFlag = it.value(); + continue; + } + + auto className = it.key(); + if (it->is_structured()) { + for (auto itm = it->begin(); itm != it->end(); ++itm) { + auto methodName = itm.key(); + + if (!(it->is_structured() && (it->size() != 0))) { + ftd.methodVec.push_back(className + methodName); + continue; + } + + std::string param {}; + for (auto itp = itm->begin(); itp != itm->end(); ++itp) { + auto tp = itp.value(); + param += tp; + } + ftd.methodVec.push_back(className + methodName + param); + } + } + } + } +}; +} // namespace OHOS + +#endif // FUZZ_CONFIG_PARSER_H diff --git a/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h new file mode 100644 index 0000000..c17922a --- /dev/null +++ b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.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 NOTIFICATION_FUZZTESTMANAGER_H +#define NOTIFICATION_FUZZTESTMANAGER_H + +#include +#include + +#include "nlohmann/json.hpp" +namespace OHOS { +namespace Notification { +class NotificationFuzzTestManager { +public: + using Ptr = std::shared_ptr; + ~NotificationFuzzTestManager() + {} + static Ptr GetInstance() + { + if (instance_ == nullptr) { + auto pObj = new NotificationFuzzTestManager(); + instance_ = std::shared_ptr(pObj); + } + return instance_; + } + + void StartFuzzTest(); + +private: + void SetJsonFunction(std::string functionName); + void SetCycle(uint16_t cycle); + NotificationFuzzTestManager(); + NotificationFuzzTestManager(NotificationFuzzTestManager &) = delete; + NotificationFuzzTestManager &operator=(const NotificationFuzzTestManager &) = delete; + static Ptr instance_; + uint16_t cycle_; + std::unordered_map remainderMap_ {}; + std::unordered_map> callFunctionMap_ {}; + + const int COLOR_R = 100; + const int COLOR_G = 100; + const int COLOR_B = 100; + + void RegisterAsyncCommonEventResult(); + void RegisterCommonEventData(); + void RegisterCommonEventManager(); + void RegisterCommonEventPublishInfo(); + void RegisterCommonEventSubscribeInfo(); + void RegisterCommonEventSubscriber(); + void RegisterCommonEventSupport(); + void RegisterMatchingSkills(); + void RegisterDumper(); + void RegisterEventHandler(); + void RegisterEventQueue(); + void RegisterEventRunner(); + void RegisterFileDescriptorListener(); + void RegisterInnerEvent(); + void RegisterEventRunnerNativeImplement(); + void RegisterAbilityManager(); + void RegisterWantParams(); + void RegisterWant(); + void RegisterElementName(); + void RegisterBundleMgrProxy(); + + void RegisterOHOSApplication(); + void RegisterAbility(); + void RegisterDataAbilityHelper(); + void RegisterDataUriUtils(); + void RegisterLifeCycle(); + + void RegisterAbilityContext(); + void RegisterProcessInfo(); + + void RegisterNotificationHelper(); + void RegisterNotificationSorting(); + void RegisterNotificationSortingMap(); + void RegisterNotificationSubscribeInfo(); + void RegisterNotificationSubscriber(); + void RegisterWantAgentHelper(); + void RegisterLauncherService(); + void RegisterNapiBundlemgr(); + void RegisterIAbilityContinuation(); + void RegisterRevocable(); + void RegisterTaskDispatcher(); + void RegisterAbility_(); + void RegisterAbilityContext_(); + void RegisterContext(); + void RegisterAbilityLifecycleCallbacks(); + void RegisterIAbilityManager(); + friend class TestAnsSubscriber; +}; +} // namespace EventFwk +} // namespace OHOS + +#endif \ No newline at end of file diff --git a/test/resource/notificationfuzztest/include/notificationgetparam.h b/test/resource/notificationfuzztest/include/notificationgetparam.h new file mode 100644 index 0000000..4fdcba8 --- /dev/null +++ b/test/resource/notificationfuzztest/include/notificationgetparam.h @@ -0,0 +1,444 @@ +/* + * 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 NOTIFICATION_GET_PARAM_H +#define NOTIFICATION_GET_PARAM_H +#include +#include "ability.h" +#include "ability_handler.h" +#include "ability_manager.h" +#include "ability_manager_interface.h" +#include "async_common_event_result.h" +#include "bundle_info.h" +#include "common_event_manager.h" +#include "common_event_data.h" +#include "common_event_publish_info.h" +#include "common_event_subscribe_info.h" +#include "common_event_subscriber.h" +#include "common_event_support.h" +#include "data_uri_utils.h" +#include "element_name.h" +#include "event_handler.h" +#include "event_runner.h" +#include "inner_event.h" +#include "key_event.h" +#include "logger.h" +#include "matching_skills.h" +#include "module_info.h" +#include "native_implement_eventhandler.h" +#include "pac_map.h" +#include "parcel.h" +#include "patterns_matcher.h" +#include "uri.h" +#include "want.h" +#include "bundle_mgr_proxy.h" +#include "notification_sorting_map.h" +#include "notification_helper.h" +#include "want_agent_helper.h" +#include "notification.h" +#ifdef PRINT_LOG +#undef PRINT_LOG +#endif +#include "launcher_service.h" +#include "launcher_ability_info.h" +#include "task_dispatcher.h" +#include "base_task_dispatcher.h" +#include "spec_task_dispatcher.h" +#include "task_dispatcher_context.h" +#include "ability_manager_service.h" + +using Want = OHOS::AAFwk::Want; +namespace OHOS { +namespace Notification { +class TestDumper; +bool GetBoolParam(); +uint8_t GetU8Param(); +unsigned int GetUIntParam(); +uint16_t GetU16Param(); +uint32_t GetU32Param(); +uint64_t GetU64Param(); +int8_t GetS8Param(); +int16_t GetS16Param(); +int32_t GetS32Param(); +int64_t GetS64Param(); +char32_t GetChar32Param(); + +short GetShortParam(); +long GetLongParam(); +int GetIntParam(); +double GetDoubleParam(); +float GetFloatParam(); +char GetCharParam(); +char *GetCharArryParam(); +std::string GetStringParam(); +std::vector GetBoolVectorParam(); +std::vector GetShortVectorParam(); +std::vector GetLongVectorParam(); +std::vector GetIntVectorParam(); +std::vector GetFloatVectorParam(); +std::vector GetDoubleVectorParam(); +std::vector GetCharVectorParam(); +std::vector GetChar32VectorParam(); +std::vector GetStringVectorParam(); +template +std::vector GetUnsignVectorParam(); +std::vector GetS8VectorParam(); +std::vector GetS16VectorParam(); +std::vector GetS32VectorParam(); +std::vector GetS64VectorParam(); + +std::shared_ptr GetParamParcel(); +std::shared_ptr GetParamWant(); +std::vector> GetParamWantVector(); +OHOS::AAFwk::Operation GetParamOperation(); +std::shared_ptr GetParamAsyncCommonEventResult(); +std::shared_ptr GetParamCommonEventData(); +std::shared_ptr GetParamCommonEventManager(); +std::shared_ptr GetParamCommonEventPublishInfo(); +std::shared_ptr GetParamCommonEventSubscribeInfo(); +std::shared_ptr GetParamCommonEventSubscriber(); +std::shared_ptr GetParamCommonEventSupport(); +std::shared_ptr GetParamMatchingSkills(); +sptr GetParamSptrRemote(); +std::shared_ptr GetParamEventRunner(); +std::shared_ptr GetParamEventHandler(); +std::shared_ptr GetParamEventQueue(); +std::shared_ptr GetParamEventRunnerNativeImplement(); +std::shared_ptr GetParamFileDescriptorListener(); +std::shared_ptr GetParamLogger(); +OHOS::AppExecFwk::EventQueue::Priority GetParamPriority(); +TestDumper GetParamDumper(); +OHOS::AppExecFwk::InnerEvent::Pointer GetParamInnerEvent(); +OHOS::AppExecFwk::InnerEvent::Callback GetParamCallback(); +OHOS::AppExecFwk::InnerEvent::TimePoint GetParamTimePoint(); +OHOS::EventFwk::CommonEventSubscribeInfo::ThreadMode GetParamThreadMode(); + +std::shared_ptr GetParamAbilityContext(); +std::shared_ptr GetParamIAbilityEvent(); +sptr GetParamAbilityThread(); +std::shared_ptr GetParamAbilityHandler(); +std::shared_ptr GetParamAbilityStartSetting(); +std::shared_ptr GetParamAbility(); +std::shared_ptr GetParamOHOSApplication(); +std::shared_ptr GetParamKeyEvent(); +OHOS::Uri GetParamUri(); + +NativeRdb::ValuesBucket GetParamValuesBucket(); +OHOS::AppExecFwk::Configuration GetParamConfiguration(); +NativeRdb::DataAbilityPredicates GetParamDataAbilityPredicates(); +OHOS::AppExecFwk::PacMap GetParamPacMap(); +std::shared_ptr GetParamComponentContainer(); +sptr GetParamIAbilityConnection(); + +std::shared_ptr GetParamProcessInfo(); +std::shared_ptr GetParamDataUriUtils(); +std::shared_ptr GetParamDataAbilityHelper(); +std::shared_ptr GetParamLifeCycle(); +OHOS::AppExecFwk::LifeCycle::Event GetParamLifeCycleEvent(); +std::shared_ptr GetParamElementName(); +std::shared_ptr GetParamWantParams(); +std::shared_ptr GetParamAbilityManager(); +OHOS::AAFwk::PatternsMatcher GetParamPatternsMatcher(); +OHOS::AAFwk::MatchType GetParamMatchType(); +std::shared_ptr GetParamContext(); + +std::shared_ptr GetParamBundleMgrProxy(); +OHOS::AppExecFwk::ApplicationFlag GetParamApplicationFlag(); +OHOS::AppExecFwk::ApplicationInfo GetParamApplicationInfo(); +std::vector GetParamApplicationInfoVector(); +OHOS::AppExecFwk::BundleFlag GetParamBundleFlag(); +OHOS::AppExecFwk::BundleInfo GetParamBundleInfo(); +OHOS::AppExecFwk::AbilityInfo GetParamAbilityInfo(); +std::vector GetParamBundleInfoVector(); +OHOS::AppExecFwk::HapModuleInfo GetParamHapModuleInfo(); +OHOS::AppExecFwk::PermissionDef GetParamPermissionDef(); +std::vector GetParamPermissionDefVector(); +OHOS::AppExecFwk::IBundleMgr::Message GetParamIBundleMgrMessage(); +OHOS::MessageParcel GetParamMessageParcel(); +OHOS::AppExecFwk::DumpFlag GetParamDumpFlag(); +sptr GetParamICleanCacheCallback(); +sptr GetParamIBundleStatusCallback(); + +std::shared_ptr GetParamNotificationSorting(); +std::vector GetParamNotificationSortingVector(); +std::shared_ptr GetParamNotificationSortingMap(); +std::shared_ptr GetParamNotificationSlot(); +sptr GetParamNotificationSlotSptr(); +OHOS::Notification::NotificationConstant::SlotType GetParamSlotType(); +std::vector> GetParamNotificationSlotSptrVector(); +std::vector GetParamNotificationSlotVector(); +std::vector GetParamNotificationSlotGroupVector(); +sptr GetParamNotificationSlotGroup(); +std::vector> GetParamNotificationSlotGroupSptrVector(); +std::shared_ptr GetParamNotificationBundleOption(); +std::shared_ptr GetParamNotificationRequest(); +std::vector> GetParamNotificationRequestVector(); +sptr GetParamNotificationSortingMapSptr(); +OHOS::Notification::NotificationSlot::NotificationLevel GetParamNotificationLevel(); +std::shared_ptr GetParamNotificationSubscriber(); +std::shared_ptr GetParamNotificationSubscribeInfo(); +OHOS::Notification::NotificationConstant::DisturbMode GetParamDisturbMode(); + +std::shared_ptr GetParamWantAgentInfo(); +OHOS::Notification::WantAgent::WantAgentConstant::OperationType GetParamOperationType(); +OHOS::Notification::WantAgent::WantAgentConstant::Flags GetParamFlags(); +std::vector GetParamFlagsVector(); + +std::shared_ptr GetParamNotification(); +sptr GetParamNotificationSptr(); +std::vector> GetParamNotificationSptrVector(); +std::shared_ptr GetParamPendingWant(); +std::shared_ptr GetParamWantAgent(); +std::shared_ptr GetParamCompletedCallback(); +std::shared_ptr GetParamTriggerInfo(); +std::shared_ptr GetParamCancelListener(); + +std::shared_ptr GetParamLauncherService(); +std::vector GetParamLauncherAbilityInfoVector(); +std::shared_ptr GetParamLauncherAbilityInfo(); +std::vector GetParamLauncherShortcutInfoVector(); +std::vector GetParamFormInfoVector(); +std::vector GetParamShortcutInfoVector(); +std::vector GetParamModuleUsageRecordVector(); +sptr GetParamOnPermissionChangedCallback(); + +std::shared_ptr GetParamTaskDispatcher(); +std::shared_ptr GetParamBaseTaskDispatcher(); +OHOS::AppExecFwk::TaskPriority GetParamTaskPriority(); +std::shared_ptr GetParamRunnable(); +std::shared_ptr GetParamGroup(); +std::shared_ptr> GetParamIteratableTask(); +OHOS::Notification::NotificationConstant::SubscribeResult GetParamSubscribeResult(); +OHOS::AppExecFwk::MissionInformation GetParamMissionInformation(); +std::shared_ptr GetParamAbilityLifecycleCallbacks(); +std::shared_ptr GetParamIAbilityManager(); +class TestRemoteObject : public IRemoteObject { +public: + TestRemoteObject(); + ~TestRemoteObject(); + + int32_t GetObjectRefCount() override + { + return 0; + } + + int SendRequest(uint32_t code, MessageParcel &data, MessageParcel &reply, MessageOption &option) override + { + return 0; + } + + bool IsProxyObject() const override + { + return true; + } + + bool CheckObjectLegality() const override + { + return true; + } + + bool AddDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool RemoveDeathRecipient(const sptr &recipient) override + { + return true; + } + + bool Marshalling(Parcel &parcel) const override + { + return true; + } + + sptr AsInterface() override + { + return nullptr; + } + + int Dump(int fd, const std::vector &args) override + { + return 0; + } + + std::u16string GetObjectDescriptor() const + { + std::u16string descriptor = std::u16string(); + return descriptor; + } +}; + +class TestCommonEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { +public: + TestCommonEventSubscriber() + {} + ~TestCommonEventSubscriber() + {} + virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) + { + printf("Fuzz Test Reveive Event\n"); + } +}; + +class TestDumper : public OHOS::AppExecFwk::Dumper { +public: + void Dump(const std::string &message) + { + return; + } + std::string GetTag() + { + return GetStringParam(); + } +}; + +class TestFileDescriptorListener : public OHOS::AppExecFwk::FileDescriptorListener { +public: + TestFileDescriptorListener() + {} + ~TestFileDescriptorListener() + {} +}; + +class TestIAbilityConnection : public OHOS::AAFwk::IAbilityConnection { +public: + void OnAbilityConnectDone( + const OHOS::AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override + {} + void OnAbilityDisconnectDone(const OHOS::AppExecFwk::ElementName &element, int resultCode) override + {} + virtual ~TestIAbilityConnection() + {} +}; + +class TestAbilityEvent : public OHOS::AppExecFwk::IAbilityEvent { +public: + virtual void OnBackPressed() + { + printf("Fuzz Test Back Pressed."); + } +}; + +class TestLogger : public OHOS::AppExecFwk::Logger { +public: + void Log(const std::string &line) + {} + virtual ~TestLogger() + {} +}; + +class TestICleanCacheCallback : public OHOS::AppExecFwk::ICleanCacheCallback { +public: + TestICleanCacheCallback() + {} + void OnCleanCacheFinished(bool succeeded) override + {} + virtual ~TestICleanCacheCallback() + {} +}; + +class TestIBundleStatusCallback : public OHOS::AppExecFwk::IBundleStatusCallback { +public: + TestIBundleStatusCallback() + {} + void OnBundleStateChanged(const uint8_t installType, const int32_t resultCode, const std::string &resultMsg, + const std::string &bundleName) override + {} + virtual ~TestIBundleStatusCallback() + {} +}; + +class TestAnsSubscriber : public OHOS::Notification::NotificationSubscriber { +public: + TestAnsSubscriber() + {} + ~TestAnsSubscriber() + {} + void OnConnected() override + { + std::cout << "TestAnsSubscriber OnConnected" << std::endl; + mutex_.unlock(); + } + void OnDisconnected() override + { + std::cout << "TestAnsSubscriber OnDisconnected" << std::endl; + mutex_.unlock(); + } + void OnDied() override + {} + void OnUpdate(const std::shared_ptr &sortingMap) override + {} + void OnDisturbModeChanged(int disturbMode) override + {} + void OnCanceled(const std::shared_ptr &request) override + {} + void OnCanceled(const std::shared_ptr &request, + const std::shared_ptr &sortingMap, int deleteReason) override + {} + void OnConsumed(const std::shared_ptr &request) override + {} + void OnConsumed(const std::shared_ptr &request, + const std::shared_ptr &sortingMap) override + {} + +private: + static std::mutex mutex_; +}; + +class TestCompletedCallback : public OHOS::Notification::WantAgent::CompletedCallback { + void OnSendFinished(const AAFwk::Want &want, int resultCode, const std::string &resultData, + const AAFwk::WantParams &resultExtras) override + {} +}; + +class TestCancelListener : public OHOS::Notification::WantAgent::CancelListener { +public: + void OnCancelled(int resultCode) override + {} +}; + +class TestOnPermissionChangedCallback : public OHOS::AppExecFwk::OnPermissionChangedCallback { +public: + void OnChanged(const int32_t uid) override + {} +}; + +class TestAbilityLifecycleCallbacks : public OHOS::AppExecFwk::AbilityLifecycleCallbacks { +public: + TestAbilityLifecycleCallbacks() = default; + virtual ~TestAbilityLifecycleCallbacks() = default; + virtual void OnAbilityStart(const std::shared_ptr &ability) + {} + virtual void OnAbilityInactive(const std::shared_ptr &ability) + {} + virtual void OnAbilityBackground(const std::shared_ptr &ability) + {} + virtual void OnAbilityForeground(const std::shared_ptr &ability) + {} + virtual void OnAbilityActive(const std::shared_ptr &ability) + {} + virtual void OnAbilityStop(const std::shared_ptr &ability) + {} + virtual void OnAbilitySaveState(const OHOS::AppExecFwk::PacMap &outState) + {} +}; +class WantSender : public OHOS::AAFwk::WantSenderStub { +public: + void Send(OHOS::AAFwk::SenderInfo &senderInfo) override + {} +}; +} // namespace Notification +} // namespace OHOS +#endif \ No newline at end of file diff --git a/test/resource/notificationfuzztest/notificationfuzzconfig/config.json b/test/resource/notificationfuzztest/notificationfuzzconfig/config.json new file mode 100644 index 0000000..ec41e63 --- /dev/null +++ b/test/resource/notificationfuzztest/notificationfuzzconfig/config.json @@ -0,0 +1,153 @@ +{ + "flag": 10, + "NotificationSubscriber": { + "OnCanceledNotification": [], + "OnCanceledNotificationNotificationSortingMapint": [], + "OnSubscribeResult": [], + "OnConsumedNotification": [], + "OnConsumedNotificationNotificationSortingMap": [], + "OnUnsubscribeResultNotificationConstantSubscribeResult": [], + "OnUpdate": [], + "OnDied": [] + }, + "NotificationSubscribeInfo": { + "AddAppName": [], + "AddAppNames": [], + "GetAppNames": [] + }, + "NotificationSorting": { + "GetRanking": [], + "GetKey": [], + "GetImportance": [], + "GetSlot": [], + "GetVisiblenessOverride": [], + "IsDisplayBadge": [], + "IsHiddenNotification": [], + "GetGroupKeyOverride": [] + }, + "NotificationSortingMap": { + "GetKey": [], + "GetNotificationSorting": [] + }, + "NotificationHelper": { + "AddNotificationSlot": [], + "AddSlotByType": [], + "AddNotificationSlots": [], + "RemoveNotificationSlot": [], + "RemoveAllSlots": [], + "GetNotificationSlot": [], + "GetNotificationSlots": [], + "AddNotificationSlotGroup": [], + "AddNotificationSlotGroups": [], + "RemoveNotificationSlotGroup": [], + "GetNotificationSlotGroup": [], + "GetNotificationSlotGroups": [], + "GetNotificationSlotNumAsBundle": [], + "PublishNotificationNotificationRequest": [], + "PublishNotificationstringNotificationRequest": [], + "PublishNotificationNotificationRequeststring": [], + "CancelNotificationint32_t": [], + "CancelNotificationstringint32_t": [], + "CancelAllNotifications": [], + "GetActiveNotificationNums": [], + "GetActiveNotifications": [], + "GetCurrentAppSorting": [], + "SetNotificationAgent": [], + "GetNotificationAgent": [], + "CanPublishNotificationAsBundle": [], + "PublishNotificationAsBundle": [], + "SetNotificationBadgeNum": [], + "SetNotificationBadgeNumint32_t": [], + "IsAllowedNotifybool": [], + "AreNotificationsSuspended": [], + "HasNotificationPolicyAccessPermission": [], + "GetBundleImportance": [], + "SubscribeNotificationNotificationSubscriber": [], + "SubscribeNotificationNotificationSubscriberNotificationSubscribeInfo": [], + "UnSubscribeNotificationNotificationSubscriber": [], + "UnSubscribeNotificationNotificationSubscriberNotificationSubscribeInfo": [], + "RemoveNotificationstring": [], + "RemoveNotificationNotificationBundleOptionint32_tstring": [], + "RemoveAllNotifications": [], + "RemoveNotificationsByBundle": [], + "RemoveNotifications": [], + "GetNotificationSlotsForBundle": [], + "UpdateNotificationSlots": [], + "UpdateNotificationSlotGroups": [], + "GetAllActiveNotificationsNotification": [], + "GetAllActiveNotificationsstringNotification": [], + "IsAllowedNotify": [], + "SetNotificationsEnabledForAllBundles": [], + "SetNotificationsEnabledForDefaultBundle": [], + "SetNotificationsEnabledForSpecifiedBundle": [], + "SetShowBadgeEnabledForBundle": [], + "GetShowBadgeEnabledForBundle": [], + "GetShowBadgeEnabled": [], + "SetDisturbMode": [], + "GetDisturbMode": [] + }, + "WantAgentHelper": { + "GetWantAgentOHOSAppExecFwkContextWantAgentInfo": [], + "GetWantAgentWantAgentInfo": [], + "GetType": [], + "TriggerWantAgent": [], + "Cancel": [], + "JudgeEquality": [], + "GetHashCode": [], + "GetBundleName": [], + "GetUid": [], + "GetWant": [], + "RegisterCancelListener": [], + "UnregisterCancelListener": [] + }, + "LauncherService": { + "GetAbilityList": [], + "GetAbilityInfo": [], + "GetApplicationInfo": [], + "IsBundleEnabled": [], + "IsAbilityEnabled": [], + "GetShortcutInfos": [], + "RegisterCallback": [], + "UnRegisterCallback": [] + }, + "IAbilityContinuation": { + "OnStartContinuation": [], + "OnSaveData": [], + "OnRestoreData": [], + "OnCompleteContinuation": [] + }, + "Ability": { + "StartAbility": [], + "OnRequestPermissionsFromUserResult": [] + }, + "AbilityContext": { + "StartAbility": [] + }, + "Context": { + "VerifyPermission": [], + "VerifyCallingPermission": [], + "VerifySelfPermission": [], + "VerifyCallingOrSelfPermission": [], + "CanRequestPermission": [], + "RequestPermissionsFromUser": [], + "MoveMissionToEnd": [], + "SetMissionInformation": [], + "LockMission": [], + "UnlockMission": [], + "GetMissionId": [], + "GetUITaskDispatcher": [], + "GetMainTaskDispatcher": [], + "CreateParallelTaskDispatcher": [], + "CreateSerialTaskDispatcher": [], + "GetGlobalTaskDispatcher": [] + }, + "AbilityLifecycleCallbacks": { + "OnAbilityActive": [] + }, + "IAbilityManager": { + "MoveMissionToEnd": [], + "IsFirstInMission": [], + "PowerOn": [], + "PowerOff": [] + } +} \ No newline at end of file diff --git a/test/resource/notificationfuzztest/ohos_test.xml b/test/resource/notificationfuzztest/ohos_test.xml new file mode 100644 index 0000000..a2f6e1d --- /dev/null +++ b/test/resource/notificationfuzztest/ohos_test.xml @@ -0,0 +1,25 @@ + + + + + + + + + + + \ No newline at end of file diff --git a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp new file mode 100644 index 0000000..cef442c --- /dev/null +++ b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp @@ -0,0 +1,921 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define private public +#define protected public + +#include "datetime_ex.h" +#include "../include/notificationfuzzconfigparser.h" +#include "../include/notificationfuzztestmanager.h" +#include "../include/notificationgetparam.h" + +#undef private +#undef protected +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +namespace OHOS { +namespace Notification { +std::shared_ptr NotificationFuzzTestManager::instance_ = nullptr; +// RegisterNotificationHelper +void NotificationFuzzTestManager::RegisterNotificationHelper() +{ + callFunctionMap_.emplace("NotificationHelperAddNotificationSlot", + []() { OHOS::Notification::NotificationHelper::AddNotificationSlot(*GetParamNotificationSlot()); }); + + callFunctionMap_.emplace("NotificationHelperAddSlotByType", + []() { OHOS::Notification::NotificationHelper::AddSlotByType(GetParamSlotType()); }); + + callFunctionMap_.emplace("NotificationHelperAddNotificationSlots", + []() { OHOS::Notification::NotificationHelper::AddNotificationSlots(GetParamNotificationSlotVector()); }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotificationSlot", + []() { OHOS::Notification::NotificationHelper::RemoveNotificationSlot(GetParamSlotType()); }); + + callFunctionMap_.emplace( + "NotificationHelperRemoveAllSlots", []() { OHOS::Notification::NotificationHelper::RemoveAllSlots(); }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlot", []() { + sptr param = GetParamNotificationSlotSptr(); + OHOS::Notification::NotificationHelper::GetNotificationSlot(GetParamSlotType(), param); + }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlots", []() { + std::vector> param = GetParamNotificationSlotSptrVector(); + OHOS::Notification::NotificationHelper::GetNotificationSlots(param); + }); + + callFunctionMap_.emplace("NotificationHelperAddNotificationSlotGroup", + []() { OHOS::Notification::NotificationHelper::AddNotificationSlotGroup(*GetParamNotificationSlotGroup()); }); + + callFunctionMap_.emplace("NotificationHelperAddNotificationSlotGroups", []() { + OHOS::Notification::NotificationHelper::AddNotificationSlotGroups(GetParamNotificationSlotGroupVector()); + }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotificationSlotGroup", + []() { OHOS::Notification::NotificationHelper::RemoveNotificationSlotGroup(GetStringParam()); }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlotGroup", []() { + sptr param = GetParamNotificationSlotGroup(); + OHOS::Notification::NotificationHelper::GetNotificationSlotGroup(GetStringParam(), param); + }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlotGroups", []() { + std::vector> param = GetParamNotificationSlotGroupSptrVector(); + OHOS::Notification::NotificationHelper::GetNotificationSlotGroups(param); + }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlotNumAsBundle", []() { + int param = GetIntParam(); + OHOS::Notification::NotificationHelper::GetNotificationSlotNumAsBundle( + *GetParamNotificationBundleOption(), param); + }); + + callFunctionMap_.emplace("NotificationHelperPublishNotificationNotificationRequest", + []() { OHOS::Notification::NotificationHelper::PublishNotification(*GetParamNotificationRequest()); }); + + callFunctionMap_.emplace("NotificationHelperPublishNotificationstringNotificationRequest", []() { + OHOS::Notification::NotificationHelper::PublishNotification(GetStringParam(), *GetParamNotificationRequest()); + }); + + callFunctionMap_.emplace("NotificationHelperPublishNotificationNotificationRequeststring", []() { + OHOS::Notification::NotificationHelper::PublishNotification(*GetParamNotificationRequest(), GetStringParam()); + }); + + callFunctionMap_.emplace("NotificationHelperCancelNotificationint32_t", + []() { OHOS::Notification::NotificationHelper::CancelNotification(GetS32Param()); }); + + callFunctionMap_.emplace("NotificationHelperCancelNotificationstringint32_t", + []() { OHOS::Notification::NotificationHelper::CancelNotification(GetStringParam(), GetS32Param()); }); + + callFunctionMap_.emplace("NotificationHelperCancelAllNotifications", + []() { OHOS::Notification::NotificationHelper::CancelAllNotifications(); }); + + callFunctionMap_.emplace("NotificationHelperGetActiveNotificationNums", []() { + int32_t notificationId = GetS32Param(); + OHOS::Notification::NotificationHelper::GetActiveNotificationNums(notificationId); + }); + + callFunctionMap_.emplace("NotificationHelperGetActiveNotifications", []() { + std::vector> param = GetParamNotificationRequestVector(); + OHOS::Notification::NotificationHelper::GetActiveNotifications(param); + }); + + callFunctionMap_.emplace("NotificationHelperGetCurrentAppSorting", []() { + sptr sortingMap = GetParamNotificationSortingMapSptr(); + OHOS::Notification::NotificationHelper::GetCurrentAppSorting(sortingMap); + }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationAgent", + []() { OHOS::Notification::NotificationHelper::SetNotificationAgent(GetStringParam()); }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationAgent", []() { + std::string agent = GetStringParam(); + OHOS::Notification::NotificationHelper::GetNotificationAgent(agent); + }); + + callFunctionMap_.emplace("NotificationHelperCanPublishNotificationAsBundle", []() { + bool canPublish = GetBoolParam(); + OHOS::Notification::NotificationHelper::CanPublishNotificationAsBundle(GetStringParam(), canPublish); + }); + + callFunctionMap_.emplace("NotificationHelperPublishNotificationAsBundle", []() { + OHOS::Notification::NotificationHelper::PublishNotificationAsBundle( + GetStringParam(), *GetParamNotificationRequest()); + }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationBadgeNum", + []() { OHOS::Notification::NotificationHelper::SetNotificationBadgeNum(); }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationBadgeNumint32_t", []() { + int32_t num = GetS32Param(); + OHOS::Notification::NotificationHelper::SetNotificationBadgeNum(num); + }); + + callFunctionMap_.emplace("NotificationHelperIsAllowedNotify", []() { + bool allowed = GetBoolParam(); + OHOS::Notification::NotificationHelper::IsAllowedNotify(allowed); + }); + + callFunctionMap_.emplace("NotificationHelperAreNotificationsSuspended", []() { + bool suspended = GetBoolParam(); + OHOS::Notification::NotificationHelper::AreNotificationsSuspended(suspended); + }); + + callFunctionMap_.emplace("NotificationHelperHasNotificationPolicyAccessPermission", []() { + bool hasPermission = GetBoolParam(); + OHOS::Notification::NotificationHelper::HasNotificationPolicyAccessPermission(hasPermission); + }); + + callFunctionMap_.emplace("NotificationHelperGetBundleImportance", []() { + OHOS::Notification::NotificationSlot::NotificationLevel importance = GetParamNotificationLevel(); + OHOS::Notification::NotificationHelper::GetBundleImportance(importance); + }); + + callFunctionMap_.emplace("NotificationHelperSubscribeNotificationNotificationSubscriber", []() { + TestAnsSubscriber::mutex_.lock(); + std::shared_ptr subscriber = GetParamNotificationSubscriber(); + struct tm start = {0}; + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber); + struct tm end = {0}; + int64_t timeout = 0; + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex_.lock(); + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber); + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + }); + + callFunctionMap_.emplace( + "NotificationHelperSubscribeNotificationNotificationSubscriberNotificationSubscribeInfo", []() { + TestAnsSubscriber::mutex_.lock(); + std::shared_ptr subscriber = GetParamNotificationSubscriber(); + std::shared_ptr subscribeInfo = + GetParamNotificationSubscribeInfo(); + struct tm start = {0}; + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber, *subscribeInfo); + struct tm end = {0}; + int64_t timeout = 0; + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex_.lock(); + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber, *subscribeInfo); + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + }); + + callFunctionMap_.emplace("NotificationHelperUnSubscribeNotificationNotificationSubscriber", []() { + TestAnsSubscriber::mutex_.lock(); + std::shared_ptr subscriber = GetParamNotificationSubscriber(); + struct tm start = {0}; + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber); + struct tm end = {0}; + int64_t timeout = 0; + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex_.lock(); + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber); + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + }); + + callFunctionMap_.emplace( + "NotificationHelperUnSubscribeNotificationNotificationSubscriberNotificationSubscribeInfo", []() { + TestAnsSubscriber::mutex_.lock(); + std::shared_ptr subscriber = GetParamNotificationSubscriber(); + std::shared_ptr subscribeInfo = + GetParamNotificationSubscribeInfo(); + struct tm start = {0}; + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber, *subscribeInfo); + struct tm end = {0}; + int64_t timeout = 0; + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex_.lock(); + OHOS::GetSystemCurrentTime(&start); + OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber, *subscribeInfo); + while (!TestAnsSubscriber::mutex_.try_lock()) { + OHOS::GetSystemCurrentTime(&end); + timeout = OHOS::GetSecondsBetween(start, end); + if (timeout >= 5L) { + break; + } + } + TestAnsSubscriber::mutex_.unlock(); + }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotificationstring", + []() { OHOS::Notification::NotificationHelper::RemoveNotification(GetStringParam()); }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotificationNotificationBundleOptionint32_tstring", []() { + OHOS::Notification::NotificationHelper::RemoveNotification( + *GetParamNotificationBundleOption(), GetS32Param(), GetStringParam()); + }); + + callFunctionMap_.emplace("NotificationHelperRemoveAllNotifications", + []() { OHOS::Notification::NotificationHelper::RemoveAllNotifications(*GetParamNotificationBundleOption()); }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotifications", + []() { OHOS::Notification::NotificationHelper::RemoveNotifications(); }); + + callFunctionMap_.emplace("NotificationHelperRemoveNotificationsByBundle", []() { + OHOS::Notification::NotificationHelper::RemoveNotificationsByBundle(*GetParamNotificationBundleOption()); + }); + + callFunctionMap_.emplace("NotificationHelperGetNotificationSlotsForBundle", []() { + std::vector> param = GetParamNotificationSlotSptrVector(); + OHOS::Notification::NotificationHelper::GetNotificationSlotsForBundle( + *GetParamNotificationBundleOption(), param); + }); + + callFunctionMap_.emplace("NotificationHelperUpdateNotificationSlots", []() { + OHOS::Notification::NotificationHelper::UpdateNotificationSlots( + *GetParamNotificationBundleOption(), GetParamNotificationSlotSptrVector()); + }); + + callFunctionMap_.emplace("NotificationHelperUpdateNotificationSlotGroups", []() { + OHOS::Notification::NotificationHelper::UpdateNotificationSlotGroups( + *GetParamNotificationBundleOption(), GetParamNotificationSlotGroupSptrVector()); + }); + + callFunctionMap_.emplace("NotificationHelperGetAllActiveNotificationsvectorsptrNotification", []() { + std::vector> notification = GetParamNotificationSptrVector(); + OHOS::Notification::NotificationHelper::GetAllActiveNotifications(notification); + }); + + callFunctionMap_.emplace("NotificationHelperGetAllActiveNotificationsstringNotification", []() { + std::vector> notification = GetParamNotificationSptrVector(); + OHOS::Notification::NotificationHelper::GetAllActiveNotifications(GetStringVectorParam(), notification); + }); + + callFunctionMap_.emplace("NotificationHelperIsAllowedNotify", []() { + bool param = GetBoolParam(); + OHOS::Notification::NotificationHelper::IsAllowedNotify(*GetParamNotificationBundleOption(), param); + }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationsEnabledForAllBundles", []() { + OHOS::Notification::NotificationHelper::SetNotificationsEnabledForAllBundles(GetStringParam(), GetBoolParam()); + }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationsEnabledForDefaultBundle", []() { + OHOS::Notification::NotificationHelper::SetNotificationsEnabledForDefaultBundle( + GetStringParam(), GetBoolParam()); + }); + + callFunctionMap_.emplace("NotificationHelperSetNotificationsEnabledForSpecifiedBundle", []() { + std::string param = GetStringParam(); + OHOS::Notification::NotificationHelper::SetNotificationsEnabledForSpecifiedBundle( + *GetParamNotificationBundleOption(), param, GetBoolParam()); + }); + + callFunctionMap_.emplace("NotificationHelperSetShowBadgeEnabledForBundle", []() { + OHOS::Notification::NotificationHelper::SetShowBadgeEnabledForBundle( + *GetParamNotificationBundleOption(), GetBoolParam()); + }); + + callFunctionMap_.emplace("NotificationHelperGetShowBadgeEnabledForBundle", []() { + bool param = GetBoolParam(); + OHOS::Notification::NotificationHelper::GetShowBadgeEnabledForBundle( + *GetParamNotificationBundleOption(), param); + }); + + callFunctionMap_.emplace("NotificationHelperGetShowBadgeEnabled", []() { + bool param = GetBoolParam(); + OHOS::Notification::NotificationHelper::GetShowBadgeEnabled(param); + }); + + callFunctionMap_.emplace("NotificationHelperSetDisturbMode", + []() { OHOS::Notification::NotificationHelper::SetDisturbMode(GetParamDisturbMode()); }); + + callFunctionMap_.emplace("NotificationHelperGetDisturbMode", []() { + OHOS::Notification::NotificationConstant::DisturbMode param = GetParamDisturbMode(); + OHOS::Notification::NotificationHelper::GetDisturbMode(param); + }); +} + +// RegisterNotificationSorting +void NotificationFuzzTestManager::RegisterNotificationSorting() +{ + callFunctionMap_.emplace("NotificationSortingGetRanking", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetRanking(); + }); + + callFunctionMap_.emplace("NotificationSortingGetKey", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetKey(); + }); + + callFunctionMap_.emplace("NotificationSortingGetImportance", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetImportance(); + }); + + callFunctionMap_.emplace("NotificationSortingGetSlot", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetSlot(); + }); + + callFunctionMap_.emplace("NotificationSortingGetVisiblenessOverride", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetVisiblenessOverride(); + }); + + callFunctionMap_.emplace("NotificationSortingIsDisplayBadge", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->IsDisplayBadge(); + }); + + callFunctionMap_.emplace("NotificationSortingIsHiddenNotification", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->IsHiddenNotification(); + }); + + callFunctionMap_.emplace("NotificationSortingGetGroupKeyOverride", []() { + std::shared_ptr temp = GetParamNotificationSorting(); + temp->GetGroupKeyOverride(); + }); +} + +// RegisterNotificationSortingMap +void NotificationFuzzTestManager::RegisterNotificationSortingMap() +{ + callFunctionMap_.emplace("NotificationSortingMapGetKey", []() { + std::shared_ptr temp = GetParamNotificationSortingMap(); + temp->GetKey(); + }); + + callFunctionMap_.emplace("NotificationSortingMapGetNotificationSorting", []() { + std::shared_ptr temp = GetParamNotificationSortingMap(); + const std::string key = GetStringParam(); + OHOS::Notification::NotificationSorting sorting = *(GetParamNotificationSorting().get()); + temp->GetNotificationSorting(key, sorting); + }); +} + +// RegisterNotificationSubscribeInfo +void NotificationFuzzTestManager::RegisterNotificationSubscribeInfo() +{ + callFunctionMap_.emplace("NotificationSubscribeInfoAddAppName", []() { + std::shared_ptr temp = GetParamNotificationSubscribeInfo(); + std::string appName = GetStringParam(); + temp->AddAppName(appName); + }); + + callFunctionMap_.emplace("NotificationSubscribeInfoAddAppNames", []() { + std::shared_ptr temp = GetParamNotificationSubscribeInfo(); + const std::vector appNames = GetStringVectorParam(); + temp->AddAppNames(appNames); + }); + + callFunctionMap_.emplace("NotificationSubscribeInfoGetAppNames", []() { + std::shared_ptr temp = GetParamNotificationSubscribeInfo(); + temp->GetAppNames(); + }); +} + +// RegisterNotificationSubscriber +void NotificationFuzzTestManager::RegisterNotificationSubscriber() +{ + callFunctionMap_.emplace("NotificationSubscriberOnCanceledNotification", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + temp->OnCanceled(GetParamNotification()); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnCanceledNotificationNotificationSortingMapdeleteReason", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + const std::shared_ptr request = GetParamNotification(); + const std::shared_ptr sortingMap = GetParamNotificationSortingMap(); + int deleteReason = GetIntParam(); + temp->OnCanceled(request, sortingMap, deleteReason); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnSubscribeResult", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + temp->OnConnected(); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnConsumedNotification", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + const std::shared_ptr request = GetParamNotification(); + temp->OnConsumed(request); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnConsumedNotificationNotificationSortingMap", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + std::shared_ptr request = GetParamNotification(); + std::shared_ptr sortingMap = GetParamNotificationSortingMap(); + temp->OnConsumed(request, sortingMap); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnUnsubscribeResult", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + temp->OnDisconnected(); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnUpdate", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + const std::shared_ptr sortingMap = GetParamNotificationSortingMap(); + temp->OnUpdate(sortingMap); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnDied", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + temp->OnDied(); + }); + + callFunctionMap_.emplace("NotificationSubscriberOnDisturbModeChanged", []() { + std::shared_ptr temp = GetParamNotificationSubscriber(); + int disturbMode = GetIntParam(); + temp->OnDisturbModeChanged(disturbMode); + }); +} + +// RegisterWantAgentHelper +void NotificationFuzzTestManager::RegisterWantAgentHelper() +{ + callFunctionMap_.emplace("WantAgentHelperGetWantAgentAppExecFwkparamsInfo", []() { + const std::shared_ptr context = GetParamContext(); + const OHOS::Notification::WantAgent::WantAgentInfo paramsInfo = *GetParamWantAgentInfo(); + OHOS::Notification::WantAgent::WantAgentHelper::GetWantAgent(context, paramsInfo); + }); + + callFunctionMap_.emplace("WantAgentHelperGetWantAgentparamsInfo", []() { + const OHOS::Notification::WantAgent::WantAgentInfo paramsInfo = *GetParamWantAgentInfo(); + OHOS::Notification::WantAgent::WantAgentHelper::GetWantAgent(paramsInfo); + }); + + callFunctionMap_.emplace("WantAgentHelperGetType", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::GetType(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperTriggerWantAgent", []() { + const std::shared_ptr context; + const std::shared_ptr agent = GetParamWantAgent(); + const std::shared_ptr callback = GetParamCompletedCallback(); + OHOS::Notification::WantAgent::TriggerInfo paramsInfo(*GetParamTriggerInfo()); + OHOS::Notification::WantAgent::WantAgentHelper::TriggerWantAgent(context, agent, callback, paramsInfo); + }); + + callFunctionMap_.emplace("WantAgentHelperCancel", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::Cancel(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperJudgeEquality", []() { + const std::shared_ptr agent = GetParamWantAgent(); + const std::shared_ptr otherAgent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::JudgeEquality(agent, otherAgent); + }); + callFunctionMap_.emplace("WantAgentHelperGetHashCode", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::GetHashCode(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperGetBundleName", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::GetBundleName(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperGetUid", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::GetUid(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperGetWant", []() { + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::GetWant(agent); + }); + + callFunctionMap_.emplace("WantAgentHelperRegisterCancelListener", []() { + const std::shared_ptr cancelListener; + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::RegisterCancelListener(cancelListener, agent); + }); + + callFunctionMap_.emplace("WantAgentHelperUnregisterCancelListener", []() { + const std::shared_ptr cancelListener = GetParamCancelListener(); + const std::shared_ptr agent = GetParamWantAgent(); + OHOS::Notification::WantAgent::WantAgentHelper::UnregisterCancelListener(cancelListener, agent); + }); +} + +// RegisterLauncherService +void NotificationFuzzTestManager::RegisterLauncherService() +{ + callFunctionMap_.emplace("LauncherServiceGetAbilityList", []() { + std::shared_ptr temp = GetParamLauncherService(); + const std::string bundleName = GetStringParam(); + const int userId = GetIntParam(); + std::vector launcherAbilityInfos = GetParamLauncherAbilityInfoVector(); + temp->GetAbilityList(bundleName, userId, launcherAbilityInfos); + }); + + callFunctionMap_.emplace("LauncherServiceGetAbilityInfo", []() { + std::shared_ptr temp = GetParamLauncherService(); + const Want want = *GetParamWant(); + const int userI = GetIntParam(); + OHOS::AppExecFwk::LauncherAbilityInfo launcherAbilityInfo = *GetParamLauncherAbilityInfo(); + temp->GetAbilityInfo(want, userI, launcherAbilityInfo); + }); + + callFunctionMap_.emplace("LauncherServiceGetApplicationInfo", []() { + std::shared_ptr temp = GetParamLauncherService(); + const std::string bundleName = GetStringParam(); + const ApplicationFlag flags = GetParamApplicationFlag(); + const int userId = GetIntParam(); + ApplicationInfo applicationInfo = GetParamApplicationInfo(); + temp->GetApplicationInfo(bundleName, flags, userId, applicationInfo); + }); + + callFunctionMap_.emplace("LauncherServiceIsBundleEnabled", []() { + std::shared_ptr temp = GetParamLauncherService(); + const std::string bundleName = GetStringParam(); + temp->IsBundleEnabled(bundleName); + }); + + callFunctionMap_.emplace("LauncherServiceIsAbilityEnabled", []() { + std::shared_ptr temp = GetParamLauncherService(); + const OHOS::AppExecFwk::AbilityInfo abilityInfo = GetParamAbilityInfo(); + temp->IsAbilityEnabled(abilityInfo); + }); + + callFunctionMap_.emplace("LauncherServiceGetShortcutInfos", []() { + std::shared_ptr temp = GetParamLauncherService(); + const std::string bundleName = GetStringParam(); + std::vector launcherShortcutInfo = GetParamLauncherShortcutInfoVector(); + temp->GetShortcutInfos(bundleName, launcherShortcutInfo); + }); + + callFunctionMap_.emplace("LauncherServiceRegisterCallback", []() { + std::shared_ptr temp = GetParamLauncherService(); + const sptr callback = GetParamIBundleStatusCallback(); + temp->RegisterCallback(callback); + }); + + callFunctionMap_.emplace("LauncherServiceUnRegisterCallback", []() { + std::shared_ptr temp = GetParamLauncherService(); + temp->UnRegisterCallback(); + }); +} + +// RegisterIAbilityContinuation +void NotificationFuzzTestManager::RegisterIAbilityContinuation() +{ + callFunctionMap_.emplace("IAbilityContinuationOnStartContinuation", []() { + std::shared_ptr temp = GetParamAbility(); + temp->OnStartContinuation(); + }); + + callFunctionMap_.emplace("IAbilityContinuationOnSaveData", []() { + std::shared_ptr temp = GetParamAbility(); + WantParams saveData = *GetParamWantParams(); + temp->OnSaveData(saveData); + }); + + callFunctionMap_.emplace("IAbilityContinuationOnRestoreData", []() { + std::shared_ptr temp = GetParamAbility(); + OHOS::AppExecFwk::WantParams restoreData = *GetParamWantParams(); + temp->OnRestoreData(restoreData); + }); + + callFunctionMap_.emplace("IAbilityContinuationOnCompleteContinuation", []() { + std::shared_ptr temp = GetParamAbility(); + int result = GetIntParam(); + temp->OnCompleteContinuation(result); + }); +} + +// RegisterAbility_ +void NotificationFuzzTestManager::RegisterAbility_() +{ + callFunctionMap_.emplace("AbilityOnRequestPermissionsFromUserResult", []() { + std::shared_ptr temp = GetParamAbility(); + int requestCode = GetIntParam(); + const std::vector permissions = GetStringVectorParam(); + const std::vector grantResults = GetIntVectorParam(); + temp->OnRequestPermissionsFromUserResult(requestCode, permissions, grantResults); + }); + + callFunctionMap_.emplace("AbilityStartAbility", []() { + std::shared_ptr temp = GetParamAbility(); + const Want want = *GetParamWant(); + temp->StartAbility(want); + }); +} + +// RegisterAbilityContext_ +void NotificationFuzzTestManager::RegisterAbilityContext_() +{ + callFunctionMap_.emplace("AbilityStartAbility", []() { + std::shared_ptr temp = GetParamAbility(); + const AAFwk::Want want = *GetParamWant(); + int requestCode = GetIntParam(); + temp->StartAbility(want, requestCode); + }); +} + +// RegisterContext +void NotificationFuzzTestManager::RegisterContext() +{ + callFunctionMap_.emplace("ContextVerifyPermission", []() { + std::shared_ptr temp = GetParamContext(); + const std::string permission = GetStringParam(); + int pid = GetIntParam(); + int uid = GetIntParam(); + temp->VerifyPermission(permission, pid, uid); + }); + + callFunctionMap_.emplace("ContextVerifyCallingPermission", []() { + std::shared_ptr temp = GetParamContext(); + const std::string permission = GetStringParam(); + temp->VerifyCallingPermission(permission); + }); + + callFunctionMap_.emplace("ContextVerifySelfPermission", []() { + std::shared_ptr temp = GetParamContext(); + const std::string permission = GetStringParam(); + temp->VerifySelfPermission(permission); + }); + + callFunctionMap_.emplace("ContextVerifyCallingOrSelfPermission", []() { + std::shared_ptr temp = GetParamContext(); + temp->VerifyCallingOrSelfPermission(GetStringParam()); + }); + + callFunctionMap_["ContextCanRequestPermission"] = []() { + std::shared_ptr temp = GetParamContext(); + const std::string permission = GetStringParam(); + temp->CanRequestPermission(permission); + }; + + callFunctionMap_["ContextRequestPermissionsFromUser"] = []() { + std::shared_ptr temp = GetParamContext(); + std::vector permissions = GetStringVectorParam(); + int requestCode = GetIntParam(); + temp->RequestPermissionsFromUser(permissions, requestCode); + }; + + callFunctionMap_["ContextMoveMissionToEnd"] = []() { + std::shared_ptr temp = GetParamContext(); + bool nonFirst = GetBoolParam(); + temp->MoveMissionToEnd(nonFirst); + }; + + callFunctionMap_["ContextSetMissionInformation"] = []() { + std::shared_ptr temp = GetParamContext(); + const MissionInformation missionInformation = GetParamMissionInformation(); + temp->SetMissionInformation(missionInformation); + }; + + callFunctionMap_["ContextSetLockMission"] = []() { + std::shared_ptr temp = GetParamContext(); + temp->LockMission(); + }; + + callFunctionMap_["ContextUnlockMission"] = []() { + std::shared_ptr temp = GetParamContext(); + temp->UnlockMission(); + }; + + callFunctionMap_["ContextGetMissionId"] = []() { + std::shared_ptr temp = GetParamContext(); + temp->GetMissionId(); + }; + + callFunctionMap_["ContextGetUITaskDispatcher"] = []() { + std::shared_ptr temp = GetParamContext(); + temp->GetUITaskDispatcher(); + }; + + callFunctionMap_["ContextGetMainTaskDispatcher"] = []() { + std::shared_ptr temp = GetParamContext(); + temp->GetMainTaskDispatcher(); + }; + + callFunctionMap_["ContextCreateParallelTaskDispatcher"] = []() { + std::shared_ptr temp = GetParamContext(); + const std::string name = GetStringParam(); + const TaskPriority priority = GetParamTaskPriority(); + temp->CreateParallelTaskDispatcher(name, priority); + }; + + callFunctionMap_["ContextCreateSerialTaskDispatcher"] = []() { + std::shared_ptr temp = GetParamContext(); + const std::string name = GetStringParam(); + const TaskPriority priority = GetParamTaskPriority(); + temp->CreateSerialTaskDispatcher(name, priority); + }; + + callFunctionMap_["ContextGetGlobalTaskDispatcher"] = []() { + std::shared_ptr temp = GetParamContext(); + const TaskPriority priority = GetParamTaskPriority(); + temp->GetGlobalTaskDispatcher(priority); + }; +} + +// RegisterAbilityLifecycleCallbacks +void NotificationFuzzTestManager::RegisterAbilityLifecycleCallbacks() +{ + callFunctionMap_.emplace("AbilityLifecycleCallbacksOnAbilityActive", []() { + std::shared_ptr temp = GetParamAbilityLifecycleCallbacks(); + const std::shared_ptr ability = GetParamAbility(); + temp->OnAbilityActive(ability); + }); +} + +// RegisterIAbilityManager +void NotificationFuzzTestManager::RegisterIAbilityManager() +{ + callFunctionMap_.emplace("IAbilityManagerMoveMissionToEnd", []() { + std::shared_ptr temp = GetParamIAbilityManager(); + const sptr token = GetParamSptrRemote(); + const bool nonFirs = GetBoolParam(); + temp->MoveMissionToEnd(token, nonFirs); + }); + + callFunctionMap_.emplace("IAbilityManagerIsFirstInMission", []() { + std::shared_ptr temp = GetParamIAbilityManager(); + const sptr token = GetParamSptrRemote(); + temp->IsFirstInMission(token); + }); + + callFunctionMap_.emplace("IAbilityManagerPowerOn", []() { + std::shared_ptr temp = GetParamIAbilityManager(); + temp->PowerOn(); + }); + + callFunctionMap_.emplace("IAbilityManagerPowerOff", []() { + std::shared_ptr temp = GetParamIAbilityManager(); + temp->PowerOff(); + }); +} + +NotificationFuzzTestManager::NotificationFuzzTestManager() +{ + RegisterNotificationHelper(); + RegisterNotificationSorting(); + RegisterNotificationSortingMap(); + RegisterNotificationSubscribeInfo(); + RegisterNotificationSubscriber(); + RegisterWantAgentHelper(); + RegisterLauncherService(); + RegisterIAbilityContinuation(); + RegisterAbility_(); + RegisterAbilityContext_(); + RegisterContext(); + RegisterAbilityLifecycleCallbacks(); + RegisterIAbilityManager(); +} + +void NotificationFuzzTestManager::SetJsonFunction(std::string functionName) +{ + remainderMap_.emplace(functionName, cycle_); +} + +void NotificationFuzzTestManager::SetCycle(uint16_t cycle) +{ + cycle_ = cycle; + for_each(remainderMap_.begin(), remainderMap_.end(), [cycle](std::unordered_map::reference temp) { + temp.second = cycle; + }); +} + +int GetRandomInt(int minNum, int maxNum) +{ + return GetU16Param() % (maxNum - minNum + 1) + minNum; +} + +void action(int a) +{ + std::cout << "Interrupt signal (" << a << ") received.\n"; +} + +void NotificationFuzzTestManager::StartFuzzTest() +{ + std::cout << __func__ << std::endl; + OHOS::FuzzConfigParser jsonParser; + OHOS::FuzzTestData tempData; + + std::cout << "parseFromFile start" << std::endl; + jsonParser.ParseFromFile4FuzzTest(FUZZ_TEST_CONFIG_FILE_PATH, tempData); + std::cout << "flag :" << tempData.mainLoopFlag << std::endl; + for_each(tempData.methodVec.begin(), tempData.methodVec.end(), [this](std::vector::reference s) { + SetJsonFunction(s); + }); + SetCycle(tempData.mainLoopFlag); + + std::vector index; + std::unordered_map::iterator it = remainderMap_.begin(); + while (it != remainderMap_.end()) { + if (it->second <= 0) { + it = remainderMap_.erase(it); + } else { + index.push_back(it->first); + it++; + } + } + + std::cout << remainderMap_.size() << "--------fuzz test start1111--------" << callFunctionMap_.size() << std::endl; + for (; remainderMap_.size() > 0;) { + std::string functionName; + int offset = GetRandomInt(0, index.size() - 1); + functionName = index[offset]; + if (callFunctionMap_.find(functionName) != callFunctionMap_.end()) { + std::cout << "call function : " << functionName << std::endl; + callFunctionMap_[functionName](); + std::cout << "function end :" << functionName << std::endl; + } else { + std::cout << "can't find function : " << functionName << std::endl; + } + remainderMap_[functionName]--; + if (remainderMap_[functionName] <= 0) { + remainderMap_.erase(functionName); + index.erase(index.begin() + offset); + }; + } + std::cout << remainderMap_.size() << "--------fuzz test end--------" << std::endl; +} +} // namespace Notification +} // namespace OHOS diff --git a/test/resource/notificationfuzztest/src/notificationgetparam.cpp b/test/resource/notificationfuzztest/src/notificationgetparam.cpp new file mode 100644 index 0000000..48badd2 --- /dev/null +++ b/test/resource/notificationfuzztest/src/notificationgetparam.cpp @@ -0,0 +1,1449 @@ +/* + * 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/notificationgetparam.h" + +#include +#include +#include +#include +#include + +#include "abs_shared_result_set.h" +#include "data_ability_predicates.h" +#include "values_bucket.h" +using namespace std; +using namespace OHOS::AppExecFwk; +using namespace OHOS::EventFwk; +using Uri = OHOS::Uri; + +static const int INDEX_ZERO = 0; +static const int INDEX_ONE = 1; +static const int INDEX_TWO = 2; +static const int INDEX_THREE = 3; +static const int INDEX_FOUR = 4; +static const int INDEX_FIVE = 5; +static const int INDEX_SIX = 6; +static const int INDEX_SEVEN = 7; +static const int INDEX_EIGHT = 8; +static const int INDEX_NINE = 9; +static const int INDEX_TEN = 10; +static const int MESSAGE_INDEX = 36; +static const int CHAR_MINCOUNT = -128; +static const int CHAR_MAXCOUNT = 127; + +namespace OHOS { +namespace Notification { +std::mutex TestAnsSubscriber::mutex_ = std::mutex(); +bool GetBoolParam() +{ + bool param; + if (GetIntParam() % INDEX_TWO == 0) { + param = true; + } else { + param = false; + } + return param; +} + +size_t GenRandom(size_t min, size_t max) +{ + std::random_device rd; + static uniform_int_distribution u(min, max); + static default_random_engine e(rd()); + size_t param = u(e); + return param; +} + +int8_t GetS8Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT8_MIN, INT8_MAX); + static default_random_engine e(rd()); + int8_t param = u(e); + return param; +} +int16_t GetS16Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT16_MIN, INT16_MAX); + static default_random_engine e(rd()); + int16_t param = u(e); + return param; +} +int32_t GetS32Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT32_MIN, INT32_MAX); + static default_random_engine e(rd()); + int32_t param = u(e); + return param; +} + +int64_t GetS64Param() +{ + std::random_device rd; + static uniform_int_distribution u(INT64_MIN, INT64_MAX); + static default_random_engine e(rd()); + int64_t param = u(e); + return param; +} + +template +T GetUnsignParam() +{ + std::random_device rd; + static uniform_int_distribution u; + static default_random_engine e(rd()); + T param = u(e); + return param; +} + +size_t GetSizeTParam() +{ + size_t param = GetUnsignParam(); + return param; +} + +uint8_t GetU8Param() +{ + uint8_t param = GetUnsignParam(); + return param; +} + +unsigned int GetUIntParam() +{ + unsigned int param = GetUnsignParam(); + return param; +} + +uint16_t GetU16Param() +{ + uint16_t param = GetUnsignParam(); + return param; +} + +uint32_t GetU32Param() +{ + uint32_t param = GetUnsignParam(); + return param; +} + +uint64_t GetU64Param() +{ + uint64_t param = GetUnsignParam(); + return param; +} + +short GetShortParam() +{ + std::random_device rd; + static uniform_int_distribution u(SHRT_MIN, SHRT_MAX); + static default_random_engine e(rd()); + short param = u(e); + return param; +} + +long GetLongParam() +{ + std::random_device rd; + static uniform_int_distribution u(LONG_MIN, LONG_MAX); + static default_random_engine e(rd()); + long param = u(e); + return param; +} + +int GetIntParam() +{ + std::random_device rd; + static uniform_int_distribution<> u(INT_MIN, INT_MAX); + static default_random_engine e(rd()); + int param = u(e); + return param; +} + +double GetDoubleParam() +{ + double param = 0; + std::random_device rd; + static uniform_real_distribution u(DBL_MIN, DBL_MAX); + static default_random_engine e(rd()); + param = u(e); + return param; +} + +float GetFloatParam() +{ + float param = 0; + std::random_device rd; + static uniform_real_distribution u(FLT_MIN, FLT_MAX); + static default_random_engine e(rd()); + param = u(e); + return param; +} + +char GetCharParam() +{ + std::random_device rd; + static uniform_int_distribution<> u(CHAR_MINCOUNT, CHAR_MAXCOUNT); + static default_random_engine e(rd()); + char param = u(e); + return param; +} + +char32_t GetChar32Param() +{ + char32_t param = ' '; + std::random_device rd; + static uniform_int_distribution u; + static default_random_engine e(rd()); + param = u(e); + return param; +} + +char *GetCharArryParam() +{ + static char param[256]; + size_t len = 0; + string strparam = GetStringParam(); + if (!strparam.empty()) { + len = strparam.size() + 1; + if (len > sizeof(param)) { + len = sizeof(param) - 1; + } + + int ret = strcpy_s(param, len, strparam.c_str()); + if (ret == 0) { + return param; + } else { + return nullptr; + } + } else { + return nullptr; + } +} + +string GetStringParam() +{ + string param = ""; + char ch = GetCharParam(); + size_t len = GenRandom(0, 255); + while (len--) { + ch = GetCharParam(); + param += ch; + } + return param; +} + +template +vector GetUnsignVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + T t = GetUnsignParam(); + param.push_back(t); + } + return param; +} + +template +T GetClassParam() +{ + T param; + return param; +} + +std::vector GetBoolVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int t = GetBoolParam(); + param.push_back(t); + } + return param; +} + +std::vector GetShortVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + short t = GetShortParam(); + param.push_back(t); + } + return param; +} + +std::vector GetLongVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + long t = GetLongParam(); + param.push_back(t); + } + return param; +} + +vector GetIntVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int t = GetIntParam(); + param.push_back(t); + } + return param; +} + +std::vector GetFloatVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + float t = GetIntParam(); + param.push_back(t); + } + return param; +} + +std::vector GetDoubleVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + double t = GetIntParam(); + param.push_back(t); + } + return param; +} + +vector GetCharVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + char t = GetCharParam(); + param.push_back(t); + } + return param; +} + +vector GetChar32VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + char32_t t = GetChar32Param(); + param.push_back(t); + } + return param; +} + +vector GetStringVectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + string t = GetStringParam(); + param.push_back(t); + } + return param; +} + +vector GetS8VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int8_t temp = GetS8Param(); + param.push_back(temp); + } + return param; +} + +vector GetS16VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int16_t temp = GetS16Param(); + param.push_back(temp); + } + return param; +} + +vector GetS32VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int32_t temp = GetS32Param(); + param.push_back(temp); + } + return param; +} + +vector GetS64VectorParam() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + int64_t temp = GetS64Param(); + param.push_back(temp); + } + return param; +} + +std::shared_ptr GetParamParcel() +{ + return make_shared(); +} +std::shared_ptr GetParamWant() +{ + return make_shared(); +} + +std::vector> GetParamWantVector() +{ + vector> param; + size_t len = GenRandom(0, 255); + while (len--) { + std::shared_ptr t = GetParamWant(); + param.push_back(t); + } + return param; +} + +OHOS::AAFwk::Operation GetParamOperation() +{ + return OHOS::AAFwk::Operation(); +} + +std::shared_ptr GetParamAsyncCommonEventResult() +{ + return make_shared( + GetIntParam(), GetStringParam(), GetBoolParam(), GetBoolParam(), GetParamSptrRemote()); +} + +std::shared_ptr GetParamCommonEventData() +{ + return make_shared(); +} + +std::shared_ptr GetParamCommonEventManager() +{ + return make_shared(); +} + +std::shared_ptr GetParamCommonEventPublishInfo() +{ + return make_shared(); +} + +std::shared_ptr GetParamCommonEventSubscribeInfo() +{ + return make_shared(); +} + +std::shared_ptr GetParamCommonEventSubscriber() +{ + return make_shared(); +} + +std::shared_ptr GetParamCommonEventSupport() +{ + return make_shared(); +} + +std::shared_ptr GetParamMatchingSkills() +{ + return make_shared(); +} + +sptr GetParamSptrRemote() +{ + return sptr(); +} + +std::shared_ptr GetParamEventRunner() +{ + return EventRunner::Create(GetCharArryParam()); +} + +std::shared_ptr GetParamEventHandler() +{ + return make_shared(GetParamEventRunner()); +} + +std::shared_ptr GetParamEventQueue() +{ + return make_shared(); +} + +std::shared_ptr GetParamEventRunnerNativeImplement() +{ + return make_shared(GetBoolParam()); +} + +std::shared_ptr GetParamFileDescriptorListener() +{ + return make_shared(); +} + +TestDumper GetParamDumper() +{ + return GetClassParam(); +} + +InnerEvent::Pointer GetParamInnerEvent() +{ + return InnerEvent::Get(GetU32Param(), GetS64Param()); +} + +CommonEventSubscribeInfo::ThreadMode GetParamThreadMode() +{ + switch (GetIntParam() % INDEX_FOUR) { + case INDEX_ZERO: + return CommonEventSubscribeInfo::ThreadMode::HANDLER; + break; + case INDEX_ONE: + return CommonEventSubscribeInfo::ThreadMode::POST; + break; + case INDEX_TWO: + return CommonEventSubscribeInfo::ThreadMode::ASYNC; + break; + case INDEX_THREE: + return CommonEventSubscribeInfo::ThreadMode::BACKGROUND; + break; + default: + return CommonEventSubscribeInfo::ThreadMode::HANDLER; + break; + } +} + +EventQueue::Priority GetParamPriority() +{ + switch (GetIntParam() % INDEX_FOUR) { + case INDEX_ZERO: + return EventQueue::Priority::IMMEDIATE; + break; + case INDEX_ONE: + return EventQueue::Priority::HIGH; + break; + case INDEX_TWO: + return EventQueue::Priority::LOW; + break; + case INDEX_THREE: + return EventQueue::Priority::IDLE; + break; + default: + return EventQueue::Priority::LOW; + break; + } +} + +std::shared_ptr GetParamLogger() +{ + return make_shared(); +} + +InnerEvent::Callback GetParamCallback() +{ + auto callback = []() { printf("Fuzz Test Inner Event Callback."); }; + return callback; +} + +OHOS::AppExecFwk::InnerEvent::TimePoint GetParamTimePoint() +{ + std::chrono::steady_clock::time_point param = std::chrono::steady_clock::now(); + return param; +} + +std::shared_ptr GetParamAbilityStartSetting() +{ + return AbilityStartSetting::GetEmptySetting(); +} + +sptr GetParamIAbilityConnection() +{ + return sptr(); +} + +std::shared_ptr GetParamAbilityContext() +{ + return make_shared(); +} +std::shared_ptr GetParamIAbilityEvent() +{ + return make_shared(); +} + +sptr GetParamAbilityThread() +{ + return sptr(); +} + +std::shared_ptr GetParamAbilityHandler() +{ + return make_shared(GetParamEventRunner(), GetParamAbilityThread()); +} + +std::shared_ptr GetParamAbility() +{ + return make_shared(); +} + +std::shared_ptr GetParamComponentContainer() +{ + return make_shared(); +} + +std::shared_ptr GetParamOHOSApplication() +{ + return make_shared(); +} + +std::shared_ptr GetParamKeyEvent() +{ + return make_shared(); +} + +OHOS::Uri GetParamUri() +{ + return OHOS::Uri(GetStringParam()); +} + +NativeRdb::ValuesBucket GetParamValuesBucket() +{ + if (GetBoolParam()) { + NativeRdb::ValuesBucket val; + val.PutNull(GetStringParam()); + return val; + } else { + return NativeRdb::ValuesBucket(); + } +} + +OHOS::AppExecFwk::Configuration GetParamConfiguration() +{ + if (GetBoolParam()) { + return OHOS::AppExecFwk::Configuration(GetStringParam()); + } else { + return OHOS::AppExecFwk::Configuration(); + } +} + +NativeRdb::DataAbilityPredicates GetParamDataAbilityPredicates() +{ + if (GetBoolParam()) { + return NativeRdb::DataAbilityPredicates(GetStringParam()); + } else { + return NativeRdb::DataAbilityPredicates(); + } +} + +OHOS::AppExecFwk::PacMap GetParamPacMap() +{ + return OHOS::AppExecFwk::PacMap(); +} + +std::shared_ptr GetParamProcessInfo() +{ + pid_t id = GetIntParam(); + if (GetBoolParam()) { + return make_shared(GetStringParam(), id); + } else { + return make_shared(); + } +} + +std::shared_ptr GetParamDataUriUtils() +{ + return make_shared(); +} + +std::shared_ptr GetParamContext() +{ + return make_shared(); +} + +std::shared_ptr GetParamLifeCycle() +{ + return make_shared(); +} + +OHOS::AppExecFwk::LifeCycle::Event GetParamLifeCycleEvent() +{ + switch (GetIntParam() % INDEX_SEVEN) { + case INDEX_ZERO: + return OHOS::AppExecFwk::LifeCycle::Event::ON_ACTIVE; + break; + case INDEX_ONE: + return OHOS::AppExecFwk::LifeCycle::Event::ON_BACKGROUND; + break; + case INDEX_TWO: + return OHOS::AppExecFwk::LifeCycle::Event::ON_FOREGROUND; + break; + case INDEX_THREE: + return OHOS::AppExecFwk::LifeCycle::Event::ON_INACTIVE; + break; + case INDEX_FOUR: + return OHOS::AppExecFwk::LifeCycle::Event::ON_START; + break; + case INDEX_FIVE: + return OHOS::AppExecFwk::LifeCycle::Event::ON_STOP; + break; + case INDEX_SIX: + return OHOS::AppExecFwk::LifeCycle::Event::UNDEFINED; + break; + default: + return OHOS::AppExecFwk::LifeCycle::Event::ON_ACTIVE; + break; + } +} + +std::shared_ptr GetParamElementName() +{ + if (GetBoolParam()) { + return make_shared(GetStringParam(), GetStringParam(), GetStringParam()); + } else { + return make_shared(); + } +} + +std::shared_ptr GetParamWantParams() +{ + return make_shared(); +} + +std::shared_ptr GetParamAbilityManager() +{ + return make_shared(); +} + +OHOS::AAFwk::PatternsMatcher GetParamPatternsMatcher() +{ + return OHOS::AAFwk::PatternsMatcher(); +} + +OHOS::AAFwk::MatchType GetParamMatchType() +{ + switch (GetIntParam() % INDEX_FOUR) { + case INDEX_ZERO: + return OHOS::AAFwk::MatchType::DEFAULT; + break; + case INDEX_ONE: + return OHOS::AAFwk::MatchType::PREFIX; + break; + case INDEX_TWO: + return OHOS::AAFwk::MatchType::PATTERN; + break; + case INDEX_THREE: + return OHOS::AAFwk::MatchType::GLOBAL; + break; + default: + return OHOS::AAFwk::MatchType::DEFAULT; + break; + } +} + +std::shared_ptr GetParamBundleMgrProxy() +{ + return make_shared(GetParamSptrRemote()); +} + +OHOS::AppExecFwk::ApplicationFlag GetParamApplicationFlag() +{ + if (GetBoolParam()) { + return OHOS::AppExecFwk::ApplicationFlag::GET_BASIC_APPLICATION_INFO; + } else { + return OHOS::AppExecFwk::ApplicationFlag::GET_APPLICATION_INFO_WITH_PERMS; + } +} + +OHOS::AppExecFwk::ApplicationInfo GetParamApplicationInfo() +{ + return OHOS::AppExecFwk::ApplicationInfo(); +} + +std::vector GetParamApplicationInfoVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::ApplicationInfo t = GetParamApplicationInfo(); + param.push_back(t); + } + return param; +} + +OHOS::AppExecFwk::BundleFlag GetParamBundleFlag() +{ + if (GetBoolParam()) { + return OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT; + } else { + return OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES; + } +} + +OHOS::AppExecFwk::BundleInfo GetParamBundleInfo() +{ + return OHOS::AppExecFwk::BundleInfo(); +} + +OHOS::AppExecFwk::AbilityInfo GetParamAbilityInfo() +{ + return OHOS::AppExecFwk::AbilityInfo(); +} + +OHOS::AppExecFwk::HapModuleInfo GetParamHapModuleInfo() +{ + return OHOS::AppExecFwk::HapModuleInfo(); +} + +OHOS::AppExecFwk::PermissionDef GetParamPermissionDef() +{ + return OHOS::AppExecFwk::PermissionDef(); +} + +std::vector GetParamPermissionDefVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::PermissionDef t = GetParamPermissionDef(); + param.push_back(t); + } + return param; +} + +OHOS::AppExecFwk::IBundleMgr::Message GetParamIBundleMgrMessage() +{ + return (OHOS::AppExecFwk::IBundleMgr::Message)(GetIntParam() % MESSAGE_INDEX); +} + +OHOS::MessageParcel GetParamMessageParcel() +{ + return OHOS::MessageParcel(); +} + +OHOS::AppExecFwk::DumpFlag GetParamDumpFlag() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_LIST; + break; + case INDEX_ONE: + return OHOS::AppExecFwk::DumpFlag::DUMP_ALL_BUNDLE_INFO; + break; + case INDEX_TWO: + return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_INFO; + break; + default: + return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_LIST; + break; + } +} + +sptr GetParamICleanCacheCallback() +{ + return sptr(); +} + +sptr GetParamIBundleStatusCallback() +{ + return sptr(); +} + +std::shared_ptr GetParamDataAbilityHelper() +{ + return OHOS::AppExecFwk::DataAbilityHelper::Creator(std::make_shared()); +} + +std::shared_ptr GetParamNotificationSorting() +{ + return std::make_shared(); +} + +std::vector GetParamNotificationSortingVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + NotificationSorting t; + param.push_back(t); + } + return param; +} + +std::shared_ptr GetParamNotificationSortingMap() +{ + if (GetBoolParam()) { + return std::make_shared(); + } else { + std::vector sortingList = GetParamNotificationSortingVector(); + return std::make_shared(sortingList); + } +} + +std::shared_ptr GetParamNotificationSlot() +{ + return std::make_shared(GetParamSlotType()); +} + +sptr GetParamNotificationSlotSptr() +{ + sptr param = + new OHOS::Notification::NotificationSlot(GetParamSlotType()); + return param; +} + +OHOS::Notification::NotificationConstant::SlotType GetParamSlotType() +{ + switch (GetIntParam() % INDEX_FIVE) { + case INDEX_ZERO: + return OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION; + break; + case INDEX_ONE: + return OHOS::Notification::NotificationConstant::SlotType::SERVICE_REMINDER; + break; + case INDEX_TWO: + return OHOS::Notification::NotificationConstant::SlotType::CONTENT_INFORMATION; + break; + case INDEX_THREE: + return OHOS::Notification::NotificationConstant::SlotType::CUSTOM; + break; + case INDEX_FOUR: + return OHOS::Notification::NotificationConstant::SlotType::OTHER; + break; + default: + return OHOS::Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION; + break; + } +} +std::vector> GetParamNotificationSlotSptrVector() +{ + vector> param; + size_t len = GenRandom(0, 255); + while (len--) { + sptr t = GetParamNotificationSlotSptr(); + param.push_back(t); + } + return param; +} + +std::vector GetParamNotificationSlotVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + NotificationSlot t = *GetParamNotificationSlot(); + param.push_back(t); + } + return param; +} + +std::vector GetParamNotificationSlotGroupVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::Notification::NotificationSlotGroup t = *GetParamNotificationSlotGroup(); + param.push_back(t); + } + return param; +} +sptr GetParamNotificationSlotGroup() +{ + sptr param = + new OHOS::Notification::NotificationSlotGroup(GetStringParam(), GetStringParam()); + return param; +} +std::vector> GetParamNotificationSlotGroupSptrVector() +{ + vector> param; + size_t len = GenRandom(0, 255); + while (len--) { + sptr t = GetParamNotificationSlotGroup(); + param.push_back(t); + } + return param; +} +std::shared_ptr GetParamNotificationBundleOption() +{ + if (GetBoolParam()) { + return std::make_shared(); + } else { + return std::make_shared(GetStringParam(), GetS32Param()); + } +} +std::shared_ptr GetParamNotificationRequest() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return std::make_shared(); + break; + case INDEX_ONE: + return std::make_shared(GetS32Param()); + break; + case INDEX_TWO: + return std::make_shared(GetParamContext(), GetS32Param()); + break; + default: + return std::make_shared(); + break; + } +} + +sptr GetParamNotificationRequestSptr() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: { + sptr param = new OHOS::Notification::NotificationRequest(); + return param; + } break; + case INDEX_ONE: { + sptr param = + new OHOS::Notification::NotificationRequest(GetS32Param()); + return param; + } break; + case INDEX_TWO: { + sptr param = + new OHOS::Notification::NotificationRequest(GetParamContext(), GetS32Param()); + return param; + } break; + default: { + sptr param = new OHOS::Notification::NotificationRequest(); + return param; + } break; + } +} + +std::vector> GetParamNotificationRequestVector() +{ + vector> param; + size_t len = GenRandom(0, 255); + while (len--) { + sptr t = GetParamNotificationRequestSptr(); + param.push_back(t); + } + return param; +} +sptr GetParamNotificationSortingMapSptr() +{ + sptr param; + if (GetBoolParam()) { + param = new OHOS::Notification::NotificationSortingMap(); + } else { + std::vector sortingList = GetParamNotificationSortingVector(); + param = new OHOS::Notification::NotificationSortingMap(sortingList); + } + return param; +} +OHOS::Notification::NotificationSlot::NotificationLevel GetParamNotificationLevel() +{ + switch (GetIntParam() % INDEX_SIX) { + case INDEX_ZERO: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE; + break; + case INDEX_ONE: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_MIN; + break; + case INDEX_TWO: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_LOW; + break; + case INDEX_THREE: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_DEFAULT; + break; + case INDEX_FOUR: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_HIGH; + break; + case INDEX_FIVE: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_UNDEFINED; + break; + default: + return OHOS::Notification::NotificationSlot::NotificationLevel::LEVEL_NONE; + break; + } +} + +std::shared_ptr GetParamNotificationSubscriber() +{ + return std::make_shared(); +} + +std::shared_ptr GetParamNotificationSubscribeInfo() +{ + return std::make_shared(); +} + +OHOS::Notification::NotificationConstant::DisturbMode GetParamDisturbMode() +{ + switch (GetIntParam() % INDEX_FIVE) { + case INDEX_ZERO: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS; + break; + case INDEX_ONE: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALL; + break; + case INDEX_TWO: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_NONE; + break; + case INDEX_THREE: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_PRIORITY; + break; + case INDEX_FOUR: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_UNKNOWN; + break; + default: + return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS; + break; + } +} +std::shared_ptr GetParamWantAgentInfo() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return std::make_shared(); + break; + case INDEX_ONE: { + std::vector> param = GetParamWantVector(); + return std::make_shared( + GetIntParam(), GetParamOperationType(), GetParamFlags(), param, GetParamWantParams()); + } break; + case INDEX_TWO: { + std::vector> param = GetParamWantVector(); + return std::make_shared( + GetIntParam(), GetParamOperationType(), GetParamFlagsVector(), param, GetParamWantParams()); + } break; + default: + return std::make_shared(); + break; + } +} + +OHOS::Notification::WantAgent::WantAgentConstant::OperationType GetParamOperationType() +{ + switch (GetIntParam() % INDEX_SIX) { + case INDEX_ZERO: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::UNKNOWN_TYPE; + break; + case INDEX_ONE: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::START_ABILITY; + break; + case INDEX_TWO: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::START_ABILITIES; + break; + case INDEX_THREE: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::START_SERVICE; + break; + case INDEX_FOUR: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT; + break; + case INDEX_FIVE: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::START_FOREGROUND_SERVICE; + break; + default: + return OHOS::Notification::WantAgent::WantAgentConstant::OperationType::UNKNOWN_TYPE; + break; + } +} +OHOS::Notification::WantAgent::WantAgentConstant::Flags GetParamFlags() +{ + switch (GetIntParam() % INDEX_TEN) { + case INDEX_ZERO: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::ONE_TIME_FLAG; + break; + case INDEX_ONE: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::NO_BUILD_FLAG; + break; + case INDEX_TWO: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::CANCEL_PRESENT_FLAG; + break; + case INDEX_THREE: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG; + break; + case INDEX_FOUR: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::CONSTANT_FLAG; + break; + case INDEX_FIVE: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::REPLACE_ELEMENT; + break; + case INDEX_SIX: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::REPLACE_ACTION; + break; + case INDEX_SEVEN: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::REPLACE_URI; + break; + case INDEX_EIGHT: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::REPLACE_ENTITIES; + break; + case INDEX_NINE: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::REPLACE_BUNDLE; + break; + default: + return OHOS::Notification::WantAgent::WantAgentConstant::Flags::ONE_TIME_FLAG; + break; + } +} +std::vector GetParamFlagsVector() +{ + vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::Notification::WantAgent::WantAgentConstant::Flags t = GetParamFlags(); + param.push_back(t); + } + return param; +} + +std::shared_ptr GetParamNotification() +{ + sptr param = GetParamNotificationRequestSptr(); + return std::make_shared(param); +} + +sptr GetParamNotificationSptr() +{ + sptr t = GetParamNotificationRequestSptr(); + sptr param = new OHOS::Notification::Notification(t); + return param; +} + +std::vector> GetParamNotificationSptrVector() +{ + std::vector> param; + size_t len = GenRandom(0, 255); + while (len--) { + sptr t = GetParamNotificationSptr(); + param.push_back(t); + } + return param; +} +std::shared_ptr GetParamPendingWant() +{ + sptr target = new WantSender(); + sptr whitelistToken = GetParamSptrRemote(); + if (GetBoolParam()) { + return std::make_shared(target); + } else { + return std::make_shared(target, whitelistToken); + } +} +std::shared_ptr GetParamWantAgent() +{ + if (GetBoolParam()) { + return std::make_shared(); + } else { + return std::make_shared(GetParamPendingWant()); + } +} +std::shared_ptr GetParamCompletedCallback() +{ + return std::make_shared(); +} +std::shared_ptr GetParamTriggerInfo() +{ + if (GetBoolParam()) { + return std::make_shared(); + } else { + return std::make_shared( + GetStringParam(), GetParamWantParams(), GetParamWant(), GetIntParam()); + } +} +std::shared_ptr GetParamCancelListener() +{ + return std::make_shared(); +} + +std::shared_ptr GetParamLauncherService() +{ + return make_shared(); +} +std::vector GetParamLauncherAbilityInfoVector() +{ + std::vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::LauncherAbilityInfo t; + param.push_back(t); + } + return param; +} +std::shared_ptr GetParamLauncherAbilityInfo() +{ + return make_shared(); +} +std::vector GetParamLauncherShortcutInfoVector() +{ + std::vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::LauncherShortcutInfo t; + param.push_back(t); + } + return param; +} +std::vector GetParamFormInfoVector() +{ + std::vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::FormInfo t; + param.push_back(t); + } + return param; +} +std::vector GetParamShortcutInfoVector() +{ + std::vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::ShortcutInfo t; + param.push_back(t); + } + return param; +} +std::vector GetParamModuleUsageRecordVector() +{ + std::vector param; + size_t len = GenRandom(0, 255); + while (len--) { + OHOS::AppExecFwk::ModuleUsageRecord t; + param.push_back(t); + } + return param; +} +sptr GetParamOnPermissionChangedCallback() +{ + return sptr(); +} + +std::shared_ptr GetParamTaskDispatcher() +{ + switch (GetIntParam() % INDEX_FOUR) { + case INDEX_ZERO: + return GetParamContext()->GetMainTaskDispatcher(); + break; + case INDEX_ONE: + return GetParamContext()->CreateParallelTaskDispatcher(GetStringParam(), GetParamTaskPriority()); + break; + case INDEX_TWO: + return GetParamContext()->CreateSerialTaskDispatcher(GetStringParam(), GetParamTaskPriority()); + break; + case INDEX_THREE: + return GetParamContext()->GetGlobalTaskDispatcher(GetParamTaskPriority()); + break; + default: + return GetParamContext()->GetMainTaskDispatcher(); + break; + } +} + +OHOS::AppExecFwk::TaskPriority GetParamTaskPriority() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return OHOS::AppExecFwk::TaskPriority::HIGH; + break; + case INDEX_ONE: + return OHOS::AppExecFwk::TaskPriority::DEFAULT; + break; + case INDEX_TWO: + return OHOS::AppExecFwk::TaskPriority::LOW; + break; + default: + return OHOS::AppExecFwk::TaskPriority::HIGH; + break; + } +} + +std::shared_ptr GetParamRunnable() +{ + return std::make_shared([]() { std::cout << "Start task runnable."; }); +} + +std::shared_ptr GetParamGroup() +{ + return std::make_shared(); +} + +std::shared_ptr> GetParamIteratableTask() +{ + return std::make_shared>([](long data) { std::cout << "Start IteratableTask."; }); +} + +OHOS::Notification::NotificationConstant::SubscribeResult GetParamSubscribeResult() +{ + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return OHOS::Notification::NotificationConstant::SubscribeResult::SUCCESS; + break; + case INDEX_ONE: + return OHOS::Notification::NotificationConstant::SubscribeResult::PREMISSION_FAIL; + break; + case INDEX_TWO: + return OHOS::Notification::NotificationConstant::SubscribeResult::RESOURCES_FAIL; + break; + default: + return OHOS::Notification::NotificationConstant::SubscribeResult::SUCCESS; + break; + } +} + +OHOS::AppExecFwk::MissionInformation GetParamMissionInformation() +{ + return OHOS::AppExecFwk::MissionInformation(); +} + +std::shared_ptr GetParamAbilityLifecycleCallbacks() +{ + return std::make_shared(); +} + +std::shared_ptr GetParamBaseTaskDispatcher() +{ + std::shared_ptr context = + std::make_shared(); + std::shared_ptr config = + std::make_shared(GetStringParam(), GetParamTaskPriority()); + std::shared_ptr specTaskDispatcher = + std::make_shared(config, GetParamEventRunner()); + switch (GetIntParam() % INDEX_THREE) { + case INDEX_ZERO: + return context->CreateSerialDispatcher(GetStringParam(), GetParamTaskPriority()); + break; + case INDEX_ONE: + return context->CreateParallelDispatcher(GetStringParam(), GetParamTaskPriority()); + break; + case INDEX_TWO: + return specTaskDispatcher; + break; + default: + return context->CreateSerialDispatcher(GetStringParam(), GetParamTaskPriority()); + break; + } +} + +std::shared_ptr GetParamIAbilityManager() +{ + std::shared_ptr param = + DelayedSingleton::GetInstance(); + return param; +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file -- Gitee From 662e6d07916acbe2148191ee5a770160c62f7282 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 3 Nov 2021 15:36:08 +0800 Subject: [PATCH 008/131] Fix codex Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/src/subscribe.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 94b8801..47597e7 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -141,7 +141,8 @@ SubscriberInstance::~SubscriberInstance() void SubscriberInstance::OnCanceled(const std::shared_ptr &request) {} -void UvQueueWorkOnCanceled(uv_work_t *work, int status) { +void UvQueueWorkOnCanceled(uv_work_t *work, int status) +{ ANS_LOGI("OnCanceled uv_work_t start"); if (work == nullptr) { -- Gitee From 4b503ae55bb7d5a390530ef2af7f94429a6ae43b Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 3 Nov 2021 16:05:15 +0800 Subject: [PATCH 009/131] Fix codex Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/src/subscribe.cpp | 112 +++++++++++---------- 1 file changed, 59 insertions(+), 53 deletions(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 47597e7..003ea3c 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -232,6 +232,38 @@ void SubscriberInstance::OnCanceled(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"); + 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) { @@ -283,36 +315,35 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrdata; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - 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); - } + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + 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; } void SubscriberInstance::OnUpdate(const std::shared_ptr &sortingMap) @@ -358,32 +389,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr uv_queue_work(loop, work, [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUpdate uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - return; - } - napi_value result = nullptr; - napi_create_object(dataWorkerData->env, &result); - 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; - }); + UvQueueWorkOnUpdate); } void SubscriberInstance::OnConnected() -- Gitee From 93c5858775f4fa81a325d449f43117cfa1226d35 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Fri, 5 Nov 2021 14:09:24 +0800 Subject: [PATCH 010/131] Update acceptanceTest Signed-off-by: zhaoyuan17 --- test/resource/ansSTSlotGroupTest/BUILD.gn | 4 +- test/resource/ansSTSlotGroupTest/config.json | 1 + .../src/ans_slotgroup_test.cpp | 107 ++++++++++++------ .../ansSlotGroupHap/AnsSTSlotGroupTest.hap | Bin 102831 -> 110986 bytes 4 files changed, 77 insertions(+), 35 deletions(-) diff --git a/test/resource/ansSTSlotGroupTest/BUILD.gn b/test/resource/ansSTSlotGroupTest/BUILD.gn index 0018e05..8dbed11 100644 --- a/test/resource/ansSTSlotGroupTest/BUILD.gn +++ b/test/resource/ansSTSlotGroupTest/BUILD.gn @@ -67,6 +67,6 @@ ohos_shared_library("libraryAnsSTSlotGroupTest") { "ipc:ipc_core", ] - subsystem_name = "notification" - part_name = "ans_standard" + subsystem_name = "anssystemtest" + part_name = "test" } diff --git a/test/resource/ansSTSlotGroupTest/config.json b/test/resource/ansSTSlotGroupTest/config.json index bc9a6fa..9228a94 100644 --- a/test/resource/ansSTSlotGroupTest/config.json +++ b/test/resource/ansSTSlotGroupTest/config.json @@ -30,6 +30,7 @@ "abilities": [{ "name": "AnsSlotGroupSystemTest", "icon": "$media:snowball", + "srcLanguage": "c++", "label": "AnsSlotGroupSystemTest Ability zofa label", "launchType": "singletop", "orientation": "unspecified", diff --git a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp index a1efa3a..b93f1b3 100644 --- a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -20,49 +20,90 @@ namespace OHOS { namespace AppExecFwk { void AnsSlotGroupSystemTest::OnStart(const Want &want) { - APP_LOGI("====> ans SlotGroup test start====>"); - Notification::NotificationSlotGroup notificationSlotGroupTest("id_test", "name_test"); - - if (notificationSlotGroupTest.GetId().empty()) { - ANS_LOGI("====> Notification slot group id is invalid====>"); + APP_LOGI("====>Ans SlotGroup test start:====>"); + Notification::NotificationSlotGroup slotGroupTest("id_test", "name_test"); + if (slotGroupTest.GetId().empty()) { + ANS_LOGI("====>Notification slot group id is invalid====>"); } else { - ANS_LOGI("====> Notification slot group id is====> %{public}s", notificationSlotGroupTest.GetId().c_str()); + ANS_LOGI("====>Notification slot group id is====> %{public}s", slotGroupTest.GetId().c_str()); } - - ErrCode errcodeAdd = Notification::NotificationHelper::AddNotificationSlotGroup(notificationSlotGroupTest); - APP_LOGI("====> ansSlotGroupTest add:====> %{public}d", errcodeAdd); - - Notification::NotificationSlot notificationSlotFirst( - Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - Notification::NotificationSlot notificationSlotSecond( - Notification::NotificationConstant::SlotType::SERVICE_REMINDER); - - notificationSlotFirst.SetSlotGroup("id_test"); - notificationSlotSecond.SetSlotGroup("id_test"); - - ErrCode errcodeAddSlotFirst = Notification::NotificationHelper::AddNotificationSlot(notificationSlotFirst); - ErrCode errcodeAddSlotSecond = Notification::NotificationHelper::AddNotificationSlot(notificationSlotSecond); - - APP_LOGI("====> ansSlotGroupTest errcodeAddSlotFirst:====> %{public}d", errcodeAddSlotFirst); - APP_LOGI("====> ansSlotGroupTest errcodeAddSlotSecond:====> %{public}d", errcodeAddSlotSecond); + ErrCode errAddGroupTest = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupTest); + APP_LOGI("====>add a SlotGroup with id name id_test, ErrCode is====> %{public}d", errAddGroupTest); + + Notification::NotificationSlot slotFirst(Notification::NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + Notification::NotificationSlot slotSecond(Notification::NotificationConstant::SlotType::SERVICE_REMINDER); + Notification::NotificationSlot slotThird(Notification::NotificationConstant::SlotType::CONTENT_INFORMATION); + Notification::NotificationSlot slotFourth(Notification::NotificationConstant::SlotType::OTHER); + Notification::NotificationSlot slotFifth(Notification::NotificationConstant::SlotType::CUSTOM); + + slotFirst.SetSlotGroup("id_test"); + slotSecond.SetSlotGroup("id_test"); + slotThird.SetSlotGroup("id_test"); + slotFourth.SetSlotGroup("id_test"); + slotFifth.SetSlotGroup("id_test"); + + ErrCode errAddSlotFirst = Notification::NotificationHelper::AddNotificationSlot(slotFirst); + ErrCode errAddSlotSecond = Notification::NotificationHelper::AddNotificationSlot(slotSecond); + ErrCode errAddSlotThird = Notification::NotificationHelper::AddNotificationSlot(slotThird); + ErrCode errAddSlotFourth = Notification::NotificationHelper::AddNotificationSlot(slotFourth); + ErrCode errAddSlotFifth = Notification::NotificationHelper::AddNotificationSlot(slotFifth); + + APP_LOGI("====>add SOCIAL_COMMUNICATION type slot, ErrCode is====> %{public}d", errAddSlotFirst); + APP_LOGI("====>add SERVICE_REMINDER type slot, ErrCode is====> %{public}d", errAddSlotSecond); + APP_LOGI("====>add CONTENT_INFORMATION type slot, ErrCode is====> %{public}d", errAddSlotThird); + APP_LOGI("====>add OTHER type slot, ErrCode is====> %{public}d", errAddSlotFourth); + APP_LOGI("====>add CUSTOM type slot, ErrCode is====> %{public}d", errAddSlotFifth); sptr group; ErrCode errcodeGet = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", group); - APP_LOGI("====> ansSlotGroupTest get:====> %{public}d", errcodeGet); - + APP_LOGI("====>get SlotGroup after adding SlotGroup and slots, ErrCode is====> %{public}d", errcodeGet); if (group != nullptr) { std::string dumpGroupStr = group->Dump(); - APP_LOGI("====> ansSlotGroupTest dump:====> %{public}s", dumpGroupStr.c_str()); - APP_LOGI("====> ansSlotGroupTest the size of slots:====> %{public}zu", group->GetSlots().size()); + APP_LOGI("====>obtained group dump====> %{public}s", dumpGroupStr.c_str()); + APP_LOGI("====>the number of slots in the obtained group====> %{public}d", group->GetSlots().size()); + + ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); + APP_LOGI("====>remove the group whose id is id_test, ErrCode is====> %{public}d", errcodeRem); + sptr groupTwo; + ErrCode errcodeGetTwo = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", groupTwo); + APP_LOGI("====>get SlotGroup after removing SlotGroup, ErrCode is====> %{public}d", errcodeGetTwo); + + ErrCode errAddGroupTestSecond = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupTest); + APP_LOGI("====>add SlotGroup again with id name id_test, ErrCode is====> %{public}d", errAddGroupTestSecond); + sptr groupSecond; + ErrCode errcodeGetSecond = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", groupSecond); + APP_LOGI("====>get SlotGroup again after adding SlotGroup again, ErrCode is: %{public}d", errcodeGetSecond); + if (groupSecond != nullptr) { + dumpGroupStr = groupSecond->Dump(); + APP_LOGI("====>the second time obtained group dump====> %{public}s", dumpGroupStr.c_str()); + APP_LOGI("====>the number of slots in second obtained group: %{public}d", groupSecond->GetSlots().size()); + + Notification::NotificationSlotGroup slotGroupFirst("id_first", "name_first"); + ErrCode errAddGroupFirst = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupFirst); + APP_LOGI("====>add SlotGroup with id name id_first, ErrCode is====> %{public}d", errAddGroupFirst); + + Notification::NotificationSlotGroup slotGroupSecond("id_second", "name_second"); + ErrCode errAddGroupSecond = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupSecond); + APP_LOGI("====>add SlotGroup with id name id_second, ErrCode is====> %{public}d", errAddGroupSecond); + + Notification::NotificationSlotGroup slotGroupThird("id_third", "name_third"); + ErrCode errAddGroupThird = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupThird); + APP_LOGI("====>add SlotGroup with id name id_third, ErrCode is====> %{public}d", errAddGroupThird); + + Notification::NotificationSlotGroup slotGroupFourth("id_fourth", "name_fourth"); + ErrCode errAddGroupFourth = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupFourth); + APP_LOGI("====>add SlotGroup with id name id_fourth, ErrCode is====> %{public}d", errAddGroupFourth); + + Notification::NotificationSlotGroup slotGroupFifth("id_fifth", "name_fifth"); + ErrCode errAddGroupFifth = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupFifth); + APP_LOGI("====>add SlotGroup with id name id_fifth, ErrCode is====> %{public}d", errAddGroupFifth); + } else { + ANS_LOGI("====>fail to get group after adding SlotGroup for the second time====>"); + } } else { - APP_LOGI("====>group is null====>"); + ANS_LOGI("====>fail to get group after adding SlotGroup and slots for the first time====>"); } - ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); - APP_LOGI("====> ansSlotGroupTest remove:====> %{public}d", errcodeRem); - sptr groupTwo; - ErrCode errcodeGetTwo = Notification::NotificationHelper::GetNotificationSlotGroup("id_test", groupTwo); - APP_LOGI("====> ansSlotGroupTest get:====> %{public}d", errcodeGetTwo); Ability::OnStart(want); } diff --git a/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap b/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap index 62a810190d1093a65ae99d6b7e729b3e20a3cecb..0132daeec68f4c4e81ce4f02e6352cec88a7be96 100755 GIT binary patch delta 106202 zcmWhzcRbbK8>gFn5t6;KLiWzMR`#kyvdb2ilo9U7mdf6gYm*V#GOm%8a&4K{%yzGR zamVlb`|td9&hvh~-_QGb&N)wQG5Lpe@?;6%i3v1H3fy^NRp8!YIbFH*t|}l~$fUh- zp6&@fAFHRhz@ry`pY;O{j8~-T9-N|{5Xb^LXZ`*W{rW)NnRM46(W6v`sJGSQ5%;^FdZ*3|V{rXIyrMlk%1Cy3pVV|coxa!IJ^l?65 zCv!lyG1%W?@Jp(4HTo;~j6UqS?&2K{zR<+x25!lb0$tLi=bO*K?qNb(86}#&&un(9 zKZu7sjs0k5k9C}q9BMi0{o=BqkXW!7F*|8J&QfKQZxVIg?XzO{Qfob_Fw&wSr7Uux zD)U;M_CfvCOdeR^-Fj|dNngY3pQWd~Kt1!P?DkFMpcc$9zevaPuK-3)3iPl!r+)UD zV~@f1*}hU32XU8a{N7qZT|1-9hFAHi75g2wo(?ieTjr;yBVO|GB!<*-UgBZis~;I@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^;du9nh*8(Ba1xp3rqQfG>&c`5QOOu48;?!4c!? Date: Fri, 5 Nov 2021 15:32:06 +0800 Subject: [PATCH 011/131] Fix 64-bit build error Signed-off-by: zhaoyuan17 --- test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp index b93f1b3..b344c2d 100644 --- a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -60,7 +60,7 @@ void AnsSlotGroupSystemTest::OnStart(const Want &want) if (group != nullptr) { std::string dumpGroupStr = group->Dump(); APP_LOGI("====>obtained group dump====> %{public}s", dumpGroupStr.c_str()); - APP_LOGI("====>the number of slots in the obtained group====> %{public}d", group->GetSlots().size()); + APP_LOGI("====>the number of slots in the obtained group====> %{public}uz", group->GetSlots().size()); ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); APP_LOGI("====>remove the group whose id is id_test, ErrCode is====> %{public}d", errcodeRem); @@ -76,7 +76,7 @@ void AnsSlotGroupSystemTest::OnStart(const Want &want) if (groupSecond != nullptr) { dumpGroupStr = groupSecond->Dump(); APP_LOGI("====>the second time obtained group dump====> %{public}s", dumpGroupStr.c_str()); - APP_LOGI("====>the number of slots in second obtained group: %{public}d", groupSecond->GetSlots().size()); + APP_LOGI("====>the number of slots in second obtained group: %{public}uz", groupSecond->GetSlots().size()); Notification::NotificationSlotGroup slotGroupFirst("id_first", "name_first"); ErrCode errAddGroupFirst = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupFirst); -- Gitee From 958d656ef7fcf7d6901c199a184c97a81ab484d0 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Fri, 5 Nov 2021 15:57:02 +0800 Subject: [PATCH 012/131] Fix 64build-error Signed-off-by: zhaoyuan17 --- test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp index b344c2d..ac933f8 100644 --- a/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp +++ b/test/resource/ansSTSlotGroupTest/src/ans_slotgroup_test.cpp @@ -60,7 +60,7 @@ void AnsSlotGroupSystemTest::OnStart(const Want &want) if (group != nullptr) { std::string dumpGroupStr = group->Dump(); APP_LOGI("====>obtained group dump====> %{public}s", dumpGroupStr.c_str()); - APP_LOGI("====>the number of slots in the obtained group====> %{public}uz", group->GetSlots().size()); + APP_LOGI("====>the number of slots in the obtained group====> %{public}zu", group->GetSlots().size()); ErrCode errcodeRem = Notification::NotificationHelper::RemoveNotificationSlotGroup("id_test"); APP_LOGI("====>remove the group whose id is id_test, ErrCode is====> %{public}d", errcodeRem); @@ -76,7 +76,7 @@ void AnsSlotGroupSystemTest::OnStart(const Want &want) if (groupSecond != nullptr) { dumpGroupStr = groupSecond->Dump(); APP_LOGI("====>the second time obtained group dump====> %{public}s", dumpGroupStr.c_str()); - APP_LOGI("====>the number of slots in second obtained group: %{public}uz", groupSecond->GetSlots().size()); + APP_LOGI("====>the number of slots in second obtained group: %{public}zu", groupSecond->GetSlots().size()); Notification::NotificationSlotGroup slotGroupFirst("id_first", "name_first"); ErrCode errAddGroupFirst = Notification::NotificationHelper::AddNotificationSlotGroup(slotGroupFirst); -- Gitee From 1d0a09560116f2af324a7342e31185ece566000c Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 9 Nov 2021 15:52:11 +0000 Subject: [PATCH 013/131] Add default values of sound and vibration to the social and service reminder type slots Signed-off-by: zhaoyuan17 --- .../core/common/include/ans_const_define.h | 8 +++ .../ans/native/src/notification_slot.cpp | 7 +- .../ans_innerkits_module_slot_test.cpp | 69 +++++++++++++++++++ .../src/notification_subscriber_manager.cpp | 1 - 4 files changed, 82 insertions(+), 3 deletions(-) diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 353899e..3343ccb 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -16,6 +16,10 @@ #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" + namespace OHOS { namespace Notification { @@ -28,6 +32,10 @@ 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; +// Default sound for notification +const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); +const static std::vector DEFAULT_NOTIFICATION_VIBRATION = {200}; + } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 5c57480..3ff67a5 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -15,6 +15,7 @@ #include "notification_slot.h" #include "ans_log_wrapper.h" +#include "ans_const_define.h" namespace OHOS { namespace Notification { @@ -97,14 +98,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: 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 e7ced93..91ab5d6 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -15,6 +15,7 @@ #include #include +#include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.h" #include "advanced_notification_service.h" @@ -315,6 +316,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(0, 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(0, 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/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index b98b570..5f0eadd 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -298,7 +298,6 @@ void NotificationSubscriberManager::NotifyUpdatedInner(const sptrsubscriber->OnDisturbModeChanged(mode); } } -- Gitee From 2606d3608c638e25cdcb6275b93b63284fc0c867 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Fri, 12 Nov 2021 17:13:29 +0000 Subject: [PATCH 014/131] Check empty string Signed-off-by: zhaoyuan17 --- frameworks/ans/core/src/ans_notification.cpp | 55 ++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 74d77b8..d57d6fc 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -160,6 +160,11 @@ ErrCode AnsNotification::GetNotificationSlotGroups(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; @@ -586,6 +611,11 @@ ErrCode AnsNotification::UpdateNotificationSlots( 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; @@ -651,6 +681,11 @@ 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; @@ -662,6 +697,11 @@ ErrCode AnsNotification::SetNotificationsEnabledForSpecifiedBundle( 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; @@ -673,6 +713,11 @@ ErrCode AnsNotification::SetShowBadgeEnabledForBundle(const NotificationBundleOp 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; @@ -712,6 +757,11 @@ ErrCode AnsNotification::GetDisturbMode(NotificationConstant::DisturbMode &distu 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; @@ -723,6 +773,11 @@ ErrCode AnsNotification::CancelGroup(const std::string &groupName) 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; -- Gitee From dc8bf9c208d2b568d3cc0a6bba898821e92c195c Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 16 Nov 2021 17:23:02 +0000 Subject: [PATCH 015/131] Fix memory leak Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/src/subscribe.cpp | 89 +++++++++++++++++-- .../kits/napi/wantagent/napi_want_agent.cpp | 1 + 2 files changed, 84 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 003ea3c..c08b96e 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -153,6 +153,8 @@ void UvQueueWorkOnCanceled(uv_work_t *work, int status) NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } napi_value result = nullptr; @@ -218,15 +220,24 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdata = (void *)dataWorker; - uv_queue_work(loop, + 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) @@ -244,6 +255,8 @@ void UvQueueWorkOnConsumed(uv_work_t *work, int status) NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } napi_value result = nullptr; @@ -307,15 +320,23 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrdata = (void *)dataWorker; - uv_queue_work(loop, + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnConsumed); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void UvQueueWorkOnUpdate(uv_work_t *work, int status) @@ -330,6 +351,8 @@ void UvQueueWorkOnUpdate(uv_work_t *work, int status) NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } napi_value result = nullptr; @@ -381,15 +404,23 @@ 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, + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnUpdate); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::OnConnected() @@ -420,12 +451,14 @@ void SubscriberInstance::OnConnected() 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, + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { @@ -439,6 +472,8 @@ void SubscriberInstance::OnConnected() NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } @@ -449,6 +484,12 @@ void SubscriberInstance::OnConnected() delete work; work = nullptr; }); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::OnDisconnected() @@ -480,12 +521,14 @@ void SubscriberInstance::OnDisconnected() 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, + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { @@ -499,6 +542,8 @@ void SubscriberInstance::OnDisconnected() NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } @@ -511,6 +556,12 @@ void SubscriberInstance::OnDisconnected() delete work; work = nullptr; }); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::OnDied() @@ -541,12 +592,14 @@ 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, + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, [](uv_work_t *work, int status) { @@ -560,6 +613,8 @@ void SubscriberInstance::OnDied() NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; if (dataWorkerData == nullptr) { ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; return; } @@ -571,6 +626,12 @@ void SubscriberInstance::OnDied() delete work; work = nullptr; }); + if (ret != 0) { + delete dataWorker; + dataWorker = nullptr; + delete work; + work = nullptr; + } } void SubscriberInstance::OnDisturbModeChanged(int disturbMode) @@ -813,10 +874,18 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, if (!HasNotificationSubscriber(env, argv[0], subscriberInstancesInfo)) { if (GetNotificationSubscriber(env, argv[0], 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; } } @@ -856,6 +925,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); @@ -864,6 +937,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; diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index 23b1504..4cb4152 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -57,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}; -- Gitee From 674be5eb49c8e10d3c87647e7749c20a32942611 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 16 Nov 2021 18:54:15 +0000 Subject: [PATCH 016/131] Fix codex Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/src/subscribe.cpp | 175 ++++++++++----------- 1 file changed, 81 insertions(+), 94 deletions(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index c08b96e..7d44a9b 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -227,11 +227,7 @@ void SubscriberInstance::OnCanceled(const std::shared_ptrdata = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - UvQueueWorkOnCanceled); - + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnCanceled); if (ret != 0) { delete dataWorker; dataWorker = nullptr; @@ -327,10 +323,7 @@ void SubscriberInstance::OnConsumed(const std::shared_ptrdata = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - UvQueueWorkOnConsumed); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnConsumed); if (ret != 0) { delete dataWorker; dataWorker = nullptr; @@ -411,10 +404,7 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr work->data = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - UvQueueWorkOnUpdate); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnUpdate); if (ret != 0) { delete dataWorker; dataWorker = nullptr; @@ -423,6 +413,30 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr } } +void UvQueueWorkOnConnected(uv_work_t *work, int status) { + ANS_LOGI("OnConnected 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; + } + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void SubscriberInstance::OnConnected() { ANS_LOGI("enter"); @@ -458,32 +472,7 @@ void SubscriberInstance::OnConnected() work->data = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnSubscribeResult uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - delete work; - work = nullptr; - return; - } - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnConnected); if (ret != 0) { delete dataWorker; dataWorker = nullptr; @@ -492,6 +481,32 @@ void SubscriberInstance::OnConnected() } } +void UvQueueWorkOnDisconnected(uv_work_t *work, int status) { + ANS_LOGI("OnDisconnected 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; + } + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); + + DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void SubscriberInstance::OnDisconnected() { ANS_LOGI("enter"); @@ -528,34 +543,7 @@ void SubscriberInstance::OnDisconnected() work->data = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnUnsubscribeResult uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - delete work; - work = nullptr; - return; - } - - Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - - DelSubscriberInstancesInfo(dataWorkerData->env, dataWorkerData->subscriber); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnDisconnected); if (ret != 0) { delete dataWorker; dataWorker = nullptr; @@ -564,6 +552,31 @@ void SubscriberInstance::OnDisconnected() } } +void UvQueueWorkOnDied(uv_work_t *work, int status) { + ANS_LOGI("OnDied uv_work_t start"); + + if (work == nullptr) { + ANS_LOGE("work is null"); + return; + } + + NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; + if (dataWorkerData == nullptr) { + ANS_LOGE("dataWorkerData is null"); + delete work; + work = nullptr; + return; + } + + Common::SetCallback( + dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + void SubscriberInstance::OnDied() { ANS_LOGI("enter"); @@ -599,33 +612,7 @@ void SubscriberInstance::OnDied() work->data = (void *)dataWorker; - int ret = uv_queue_work(loop, - work, - [](uv_work_t *work) {}, - [](uv_work_t *work, int status) { - ANS_LOGI("OnDied uv_work_t start"); - - if (work == nullptr) { - ANS_LOGE("work is null"); - return; - } - - NotificationReceiveDataWorker *dataWorkerData = (NotificationReceiveDataWorker *)work->data; - if (dataWorkerData == nullptr) { - ANS_LOGE("dataWorkerData is null"); - delete work; - work = nullptr; - return; - } - - Common::SetCallback( - dataWorkerData->env, dataWorkerData->ref, Common::NapiGetNull(dataWorkerData->env)); - - delete dataWorkerData; - dataWorkerData = nullptr; - delete work; - work = nullptr; - }); + int ret = uv_queue_work(loop, work, [](uv_work_t *work) {}, UvQueueWorkOnDied); if (ret != 0) { delete dataWorker; dataWorker = nullptr; -- Gitee From e40df260e9ef5ea83a1ae75f5f391a9fe2fabcda Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 16 Nov 2021 19:03:56 +0000 Subject: [PATCH 017/131] Fix codex Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/src/subscribe.cpp | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 7d44a9b..54bfade 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -413,7 +413,8 @@ void SubscriberInstance::OnUpdate(const std::shared_ptr } } -void UvQueueWorkOnConnected(uv_work_t *work, int status) { +void UvQueueWorkOnConnected(uv_work_t *work, int status) +{ ANS_LOGI("OnConnected uv_work_t start"); if (work == nullptr) { @@ -481,7 +482,8 @@ void SubscriberInstance::OnConnected() } } -void UvQueueWorkOnDisconnected(uv_work_t *work, int status) { +void UvQueueWorkOnDisconnected(uv_work_t *work, int status) +{ ANS_LOGI("OnDisconnected uv_work_t start"); if (work == nullptr) { @@ -552,7 +554,8 @@ void SubscriberInstance::OnDisconnected() } } -void UvQueueWorkOnDied(uv_work_t *work, int status) { +void UvQueueWorkOnDied(uv_work_t *work, int status) +{ ANS_LOGI("OnDied uv_work_t start"); if (work == nullptr) { -- Gitee From edd675c90b1466d40c0dbc9e4a22b7d56eafd920 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 22 Nov 2021 23:34:57 +0800 Subject: [PATCH 018/131] Add DoNotDisturbMode feature Signed-off-by: zhaoyuan17 --- frameworks/ans/core/BUILD.gn | 1 + .../core/common/include/ans_const_define.h | 1 + .../core/common/include/ans_inner_errors.h | 1 + .../common/include/ans_permission_define.h | 58 +-- .../ans/core/include/ans_manager_interface.h | 11 +- .../ans/core/include/ans_manager_proxy.h | 5 +- .../ans/core/include/ans_manager_stub.h | 10 +- .../ans/core/include/ans_notification.h | 46 +- .../core/include/ans_subscriber_interface.h | 5 +- .../ans/core/include/ans_subscriber_proxy.h | 2 +- .../ans/core/include/ans_subscriber_stub.h | 4 +- frameworks/ans/core/src/ans_manager_proxy.cpp | 160 ++++--- frameworks/ans/core/src/ans_manager_stub.cpp | 95 ++-- frameworks/ans/core/src/ans_notification.cpp | 68 ++- .../ans/core/src/ans_subscriber_proxy.cpp | 12 +- .../ans/core/src/ans_subscriber_stub.cpp | 13 +- frameworks/ans/native/BUILD.gn | 1 + .../src/notification_do_not_disturb_date.cpp | 104 +++++ .../ans/native/src/notification_helper.cpp | 23 +- .../native/src/notification_subscriber.cpp | 4 +- frameworks/ans/test/moduletest/BUILD.gn | 8 + .../test/moduletest/ans_fw_module_test.cpp | 363 ++++++++++++++- .../ans_innerkits_module_publish_test.cpp | 122 +---- .../ans/test/moduletest/ans_mt_constant.h | 2 - .../test/moduletest/mock/permission_kit.cpp | 90 ++++ .../wantagent/src/want_agent_helper.cpp | 1 + .../native/include/notification_constant.h | 17 +- .../notification_conversational_content.h | 2 +- .../notification_do_not_disturb_date.h | 116 +++++ .../ans/native/include/notification_helper.h | 62 +-- .../ans/native/include/notification_slot.h | 4 +- .../native/include/notification_slot_group.h | 2 +- .../native/include/notification_subscriber.h | 9 +- interfaces/kits/napi/ans/include/common.h | 13 +- interfaces/kits/napi/ans/include/constant.h | 1 + .../kits/napi/ans/include/disturb_mode.h | 4 +- interfaces/kits/napi/ans/include/subscribe.h | 6 +- interfaces/kits/napi/ans/src/common.cpp | 117 ++++- interfaces/kits/napi/ans/src/constant.cpp | 21 + interfaces/kits/napi/ans/src/disturb_mode.cpp | 259 +++++++++-- interfaces/kits/napi/ans/src/init.cpp | 4 +- interfaces/kits/napi/ans/src/publish.cpp | 6 +- interfaces/kits/napi/ans/src/subscribe.cpp | 108 ++++- sa_profile/3203.xml | 1 + services/ans/BUILD.gn | 2 +- .../include/advanced_notification_service.h | 8 +- services/ans/include/disturb_filter.h | 3 + .../ans/include/notification_preferences.h | 68 +-- .../notification_preferences_database.h | 9 +- .../include/notification_preferences_info.h | 7 +- .../include/notification_subscriber_manager.h | 4 +- services/ans/include/preferences_constant.h | 4 +- .../ans/src/advanced_notification_service.cpp | 215 +++++++-- services/ans/src/disturb_filter.cpp | 81 ---- services/ans/src/notification_preferences.cpp | 10 +- .../src/notification_preferences_database.cpp | 100 +++- .../ans/src/notification_preferences_info.cpp | 8 +- .../src/notification_subscriber_manager.cpp | 12 +- services/ans/test/unittest/BUILD.gn | 4 +- ...nced_notification_service_ability_test.cpp | 2 +- .../advanced_notification_service_test.cpp | 318 +++++++++---- .../unittest/bundle_manager_helper_test.cpp | 4 +- .../ans/test/unittest/mock/permission_kit.cpp | 90 ++++ ...notification_preferences_database_test.cpp | 72 ++- .../notification_preferences_test.cpp | 41 +- .../notification_slot_filter_test.cpp | 6 +- .../notification_subscriber_manager_test.cpp | 23 +- .../test/unittest/permission_filter_test.cpp | 4 +- services/test/moduletest/BUILD.gn | 3 +- services/test/moduletest/ans_module_test.cpp | 430 ++++++++++-------- .../test/moduletest/mock/permission_kit.cpp | 90 ++++ .../include/notificationgetparam.h | 5 +- .../notificationfuzzconfig/config.json | 4 +- .../src/notificationfuzztestmanager.cpp | 13 +- .../src/notificationgetparam.cpp | 54 ++- 75 files changed, 2645 insertions(+), 1011 deletions(-) rename services/ans/test/unittest/disturb_filter_test.cpp => frameworks/ans/core/common/include/ans_permission_define.h (31%) create mode 100644 frameworks/ans/native/src/notification_do_not_disturb_date.cpp create mode 100644 frameworks/ans/test/moduletest/mock/permission_kit.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_do_not_disturb_date.h delete mode 100644 services/ans/src/disturb_filter.cpp create mode 100644 services/ans/test/unittest/mock/permission_kit.cpp create mode 100644 services/test/moduletest/mock/permission_kit.cpp diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 69083c2..e262036 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -51,6 +51,7 @@ 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_do_not_disturb_date.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", diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 3343ccb..60a2cc4 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -31,6 +31,7 @@ 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; // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index 3552497..a671871 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -55,6 +55,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, diff --git a/services/ans/test/unittest/disturb_filter_test.cpp b/frameworks/ans/core/common/include/ans_permission_define.h similarity index 31% rename from services/ans/test/unittest/disturb_filter_test.cpp rename to frameworks/ans/core/common/include/ans_permission_define.h index 7ef21bb..058c75d 100644 --- a/services/ans/test/unittest/disturb_filter_test.cpp +++ b/frameworks/ans/core/common/include/ans_permission_define.h @@ -13,58 +13,16 @@ * limitations under the License. */ -#include -#include +#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H +#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H -#include "disturb_filter.h" +#include -using namespace testing::ext; namespace OHOS { namespace Notification { - -class DisturbFilterTest : public testing::Test { -public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; -}; - -/** - * @tc.number : DisturbFilterTest_00100 - * @tc.name : AMS_ANS_OnStart_0100 - * @tc.desc : Test OnStart function - */ -HWTEST_F(DisturbFilterTest, DisturbFilterTest_00100, Function | SmallTest | Level1) -{ - DisturbFilter disturbFilter; - disturbFilter.OnStart(); -} - -/** - * @tc.number : DisturbFilterTest_00200 - * @tc.name : AMS_ANS_OnStop_0100 - * @tc.desc : Test OnStop function for data - */ -HWTEST_F(DisturbFilterTest, DisturbFilterTest_00200, Function | SmallTest | Level1) -{ - DisturbFilter disturbFilter; - disturbFilter.OnStop(); -} - -/** - * @tc.number : DisturbFilterTest_00300 - * @tc.name : AMS_ANS_OnPublish_0100 - * @tc.desc : Test OnPublish function for data - */ -HWTEST_F(DisturbFilterTest, DisturbFilterTest_00300, Function | SmallTest | Level1) -{ - DisturbFilter disturbFilter; - std::shared_ptr record = std::make_shared(); - record->request = new NotificationRequest(); - record->notification = new Notification(record->request); - record->slot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - disturbFilter.OnPublish(record); -} +// Permission +const std::string ANS_PERMISSION_CONTROLLER = "ohos.permission.NOTIFICATION_CONTROLLER"; } // namespace Notification -} // namespace OHOS \ No newline at end of file +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 7baefa8..70caf0f 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -22,6 +22,7 @@ #include "ans_subscriber_interface.h" #include "iremote_broker.h" #include "notification_bundle_option.h" +#include "notification_do_not_disturb_date.h" #include "notification_constant.h" #include "notification_request.h" #include "notification_slot.h" @@ -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,6 +103,9 @@ 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; @@ -137,8 +139,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, @@ -162,6 +162,9 @@ 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, SHELL_DUMP, diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index 24a8105..b780d0d 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,6 +91,9 @@ 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; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index 082bec3..04338d6 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,6 +96,9 @@ 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; @@ -133,8 +134,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); @@ -161,6 +160,9 @@ private: 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); 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 ce3893a..066b03b 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -21,6 +21,7 @@ #include "ans_manager_death_recipient.h" #include "ans_manager_interface.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" @@ -574,25 +575,6 @@ 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. - * @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. - */ - ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); - - /** - * Obtains the Disturb Mode. - * @param disturbMode The current type of the Do Not Disturb mode. - * @return Returns get disturb mode result. - */ - ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); - /** * Cancel the notification of the specified group of this application. * @@ -610,6 +592,32 @@ public: */ 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); + /** * Reset ans manager proxy when OnRemoteDied called. */ diff --git a/frameworks/ans/core/include/ans_subscriber_interface.h b/frameworks/ans/core/include/ans_subscriber_interface.h index e49cb26..3266801 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" @@ -43,7 +44,7 @@ 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 { @@ -54,7 +55,7 @@ protected: 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 f3101c5..ea286a7 100644 --- a/frameworks/ans/core/include/ans_subscriber_proxy.h +++ b/frameworks/ans/core/include/ans_subscriber_proxy.h @@ -38,7 +38,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 b8c8b82..403731b 100644 --- a/frameworks/ans/core/include/ans_subscriber_stub.h +++ b/frameworks/ans/core/include/ans_subscriber_stub.h @@ -40,7 +40,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: std::map> interfaces_; @@ -52,7 +52,7 @@ private: 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_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 5505d1e..69c1809 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -845,67 +845,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; @@ -1770,7 +1709,7 @@ ErrCode AnsManagerProxy::CancelGroup(const std::string &groupName) return ERR_ANS_PARCELABLE_FAILED; } - return ERR_OK; + return result; } ErrCode AnsManagerProxy::RemoveGroupByBundle( @@ -1805,7 +1744,102 @@ ErrCode AnsManagerProxy::RemoveGroupByBundle( return ERR_ANS_PARCELABLE_FAILED; } - return ERR_OK; + 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::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index cf1024b..8928488 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -101,12 +101,6 @@ const std::map(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::HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply) +{ + sptr date = nullptr; + + ErrCode result = GetDoNotDisturbDate(date); + + if (!reply.WriteInt32(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::HandleGetDisturbMode(MessageParcel &data, MessageParcel &reply) +ErrCode AnsManagerStub::HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply) { - NotificationConstant::DisturbMode mode; - ErrCode result = GetDisturbMode(mode); + bool support = false; + + ErrCode result = DoesSupportDoNotDisturbMode(support); if (!reply.WriteInt32(result)) { - ANS_LOGW("[HandleGetDisturbMode] fail: write result failed, ErrCode=%{public}d", result); + ANS_LOGW("[HandleDoesSupportDoNotDisturbMode] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } - if (!reply.WriteInt32(mode)) { - ANS_LOGW("[HandleGetDisturbMode] fail: write mode failed."); + if (!reply.WriteBool(support)) { + ANS_LOGW("[HandleDoesSupportDoNotDisturbMode] fail: write doesSupport failed."); return ERR_ANS_PARCELABLE_FAILED; } + return ERR_OK; } @@ -1405,18 +1438,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!"); @@ -1573,6 +1594,24 @@ ErrCode AnsManagerStub::RemoveGroupByBundle( 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::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { ANS_LOGW("AnsManagerStub::ShellDump called!"); diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index d57d6fc..ec677c7 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -737,24 +737,6 @@ ErrCode AnsNotification::GetShowBadgeEnabled(bool &enabled) return ansManagerProxy_->GetShowBadgeEnabled(enabled); } -ErrCode AnsNotification::SetDisturbMode(NotificationConstant::DisturbMode mode) -{ - if (!GetAnsManagerProxy()) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return ansManagerProxy_->SetDisturbMode(mode); -} - -ErrCode AnsNotification::GetDisturbMode(NotificationConstant::DisturbMode &disturbMode) -{ - if (!GetAnsManagerProxy()) { - ANS_LOGE("GetAnsManagerProxy fail."); - return ERR_ANS_SERVICE_NOT_CONNECTED; - } - return ansManagerProxy_->GetDisturbMode(disturbMode); -} - ErrCode AnsNotification::CancelGroup(const std::string &groupName) { if (groupName.empty()) { @@ -787,6 +769,56 @@ ErrCode AnsNotification::RemoveGroupByBundle( 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); +} + void AnsNotification::ResetAnsManagerProxy() { ANS_LOGI("enter"); diff --git a/frameworks/ans/core/src/ans_subscriber_proxy.cpp b/frameworks/ans/core/src/ans_subscriber_proxy.cpp index 7cef65d..b1abfaf 100644 --- a/frameworks/ans/core/src/ans_subscriber_proxy.cpp +++ b/frameworks/ans/core/src/ans_subscriber_proxy.cpp @@ -253,24 +253,24 @@ 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; } } diff --git a/frameworks/ans/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp index 716affd..2b36124 100644 --- a/frameworks/ans/core/src/ans_subscriber_stub.cpp +++ b/frameworks/ans/core/src/ans_subscriber_stub.cpp @@ -42,8 +42,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() @@ -183,10 +184,10 @@ 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; } @@ -213,7 +214,7 @@ void AnsSubscriberStub::OnCanceled( void AnsSubscriberStub::OnUpdated(const sptr ¬ificationMap) {} -void AnsSubscriberStub::OnDisturbModeChanged(NotificationConstant::DisturbMode mode) +void AnsSubscriberStub::OnDoNotDisturbDateChange(const sptr &date) {} } // namespace Notification diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 835e149..f83983b 100755 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -48,6 +48,7 @@ ohos_shared_library("ans_innerkits") { "src/notification_content.cpp", "src/notification_conversational_content.cpp", "src/notification_conversational_message.cpp", + "src/notification_do_not_disturb_date.cpp", "src/notification_helper.cpp", "src/notification_long_text_content.cpp", "src/notification_media_content.cpp", 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 0000000..4492263 --- /dev/null +++ b/frameworks/ans/native/src/notification_do_not_disturb_date.cpp @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 7b2ae30..020fe4a 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -296,25 +296,30 @@ 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::CancelGroup(const std::string &groupName) +ErrCode NotificationHelper::SetDoNotDisturbDate(const NotificationDoNotDisturbDate & doNotDisturbDate) { - return DelayedSingleton::GetInstance()->CancelGroup(groupName); + return DelayedSingleton::GetInstance()->SetDoNotDisturbDate(doNotDisturbDate); } -ErrCode NotificationHelper::RemoveGroupByBundle( - const NotificationBundleOption &bundleOption, const std::string &groupName) +ErrCode NotificationHelper::GetDoNotDisturbDate(NotificationDoNotDisturbDate & doNotDisturbDate) { - return DelayedSingleton::GetInstance()->RemoveGroupByBundle(bundleOption, groupName); + return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(doNotDisturbDate); +} + +ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); } } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index e26174d..62e2c09 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -87,9 +87,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() diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index f2edf40..85cc90d 100755 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -82,6 +82,7 @@ ohos_moduletest("ans_fw_module_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -112,6 +113,7 @@ ohos_moduletest("ans_fw_module_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -163,6 +165,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -193,6 +196,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -243,6 +247,7 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -271,6 +276,7 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -321,6 +327,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -349,6 +356,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index b906561..b4e5d98 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -40,13 +40,12 @@ using namespace OHOS::Media; namespace OHOS { namespace Notification { - 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, @@ -117,22 +116,23 @@ 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 { @@ -252,9 +252,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); } @@ -826,6 +826,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_Subscriber_00100, Function | MediumTest | Le } EXPECT_TRUE(waitOnSubscriber); subscriber.ClearEvents(); + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber, info), ERR_OK); SleepForFC(); } @@ -1193,5 +1194,345 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_PublishNotificationWithPixelMap_00300, Funct EXPECT_EQ(NotificationHelper::PublishNotification(req), (int)ERR_ANS_ICON_OVER_SIZE); } +/** + * + * @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()); +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp index e32c361..aae3d31 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -53,9 +53,6 @@ const int32_t CASE_TEN = 10; const int32_t CASE_ELEVEN = 11; const int32_t CASE_TWELVE = 12; const int32_t CASE_THIRTEEN = 13; -const int32_t CASE_FOURTEEN = 14; -const int32_t CASE_FIFTEEN = 15; -const int32_t CASE_SIXTEEN = 16; const int32_t CALLING_UID = 9999; const int32_t PIXEL_MAP_TEST_WIDTH = 32; @@ -90,7 +87,7 @@ 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 @@ -108,7 +105,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()) { @@ -134,15 +130,6 @@ 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 { @@ -1007,111 +994,6 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_03000, Function WaitOnUnsubscribeResult(); } -/** - * @tc.number : ANS_Interface_MT_Publish_04000 - * @tc.name : Publish_04000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification in - * disturbed mode (mode is ALLOW_ALARMS) - * @tc.expected : Add notification slot success, make a subscriber and a publish notification in undisturbed mode - * success. - */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function | MediumTest | Level1) -{ - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); - auto subscriber = TestAnsSubscriber(); - g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); - WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALARMS)); - MessageUser messageUser; - std::shared_ptr normalContent = std::make_shared(); - 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.SetClassification(CLASSIFICATION_ALARM); - req.SetNotificationId(CASE_THIRTEEN); - g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - WaitOnConsumed(); - g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); - WaitOnUnsubscribeResult(); -} - -/** - * @tc.number : ANS_Interface_MT_Publish_05000 - * @tc.name : Publish_05000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification - * in disturbed mode (mode is ALLOW_ALL) - * @tc.expected : Add notification slot success, make a subscriber and pulish a notification in undisturbed mode - * success. - */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_05000, Function | MediumTest | Level1) -{ - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); - auto subscriber = TestAnsSubscriber(); - g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); - WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_ALL)); - MessageUser messageUser; - std::shared_ptr normalContent = std::make_shared(); - 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.SetNotificationId(CASE_FOURTEEN); - g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - WaitOnConsumed(); - // Wait OnUnsubscribeResult - g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); - WaitOnUnsubscribeResult(); -} - -/** - * @tc.number : ANS_Interface_MT_Publish_06000 - * @tc.name : Publish_06000 - * @tc.desc : Add notification slot(type is SOCIAL_COMMUNICATION), make a subscriber and publish a notification - * in disturbed mode (mode is ALLOW_NONE) - * @tc.expected : Add notification slot success, make a subscriber and pulush a notification in undisturbed mode - * success. - */ -HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_06000, Function | MediumTest | Level1) -{ - NotificationSlot slot(NotificationConstant::SOCIAL_COMMUNICATION); - slot.EnableBypassDnd(true); - EXPECT_EQ(0, NotificationHelper::AddNotificationSlot(slot)); - auto subscriber = TestAnsSubscriber(); - g_subscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::SubscribeNotification(subscriber)); - WaitOnSubscribeResult(); - EXPECT_EQ(0, NotificationHelper::SetDisturbMode(NotificationConstant::ALLOW_NONE)); - MessageUser messageUser; - std::shared_ptr normalContent = std::make_shared(); - 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.SetNotificationId(CASE_FIFTEEN); - g_consumed_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); - WaitOnConsumed(); - g_unsubscribe_mtx.lock(); - EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber)); - WaitOnUnsubscribeResult(); -} - /** * @tc.number : ANS_Interface_MT_Publish_07000 * @tc.name : Publish_07000 @@ -1138,7 +1020,7 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_07000, Function req.SetSlotType(NotificationConstant::SOCIAL_COMMUNICATION); req.SetGroupName("groupnotifcation"); req.SetGroupOverview(true); - req.SetNotificationId(CASE_SIXTEEN); + req.SetNotificationId(CASE_THIRTEEN); req.SetGroupAlertType(NotificationRequest::GroupAlertType::ALL); g_consumed_mtx.lock(); EXPECT_EQ(0, NotificationHelper::PublishNotification(req)); diff --git a/frameworks/ans/test/moduletest/ans_mt_constant.h b/frameworks/ans/test/moduletest/ans_mt_constant.h index 99d2a27..855cf4d 100644 --- a/frameworks/ans/test/moduletest/ans_mt_constant.h +++ b/frameworks/ans/test/moduletest/ans_mt_constant.h @@ -20,7 +20,6 @@ namespace OHOS { namespace Notification { - namespace { const std::string APP_NAME = "bundleName"; const std::string NOTIFICATION_LABEL_0 = "Label0"; @@ -34,7 +33,6 @@ constexpr int CANCEL_REASON_DELETE = 2; constexpr int APP_CANCEL_REASON_DELETE = 8; constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; } // namespace - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/permission_kit.cpp b/frameworks/ans/test/moduletest/mock/permission_kit.cpp new file mode 100644 index 0000000..36855b9 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/permission_kit.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission/permission_kit.h" + +namespace OHOS { +namespace Security { +namespace Permission { +using namespace std; + +int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) +{ + return TypePermissionState::PERMISSION_GRANTED; +} + +bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::AddUserGrantedReqPermissions( + const string &bundleName, const std::vector &permList, int userId) +{ + return 0; +} + +int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) +{ + return 0; +} + +int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::AddDefPermissions(const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveDefPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) +{ + return 0; +} +} // namespace Permission +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/frameworks/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index 5b3c49c..fcb6d27 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -152,6 +152,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) { diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index 5546997..dcf4fe9 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -22,16 +22,6 @@ 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. @@ -94,6 +84,13 @@ public: SECRET }; + enum class DoNotDisturbType { + NONE = 0, + ONCE = 1, // only once + DAILY = 2, // every day + CLEARLY = 3, // time period + }; + /** * Indicates that a notification is deleted because it is clicked. */ diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h index 5b91d30..7ff86ba 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -52,7 +52,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); 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 0000000..0f08ea7 --- /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_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index f0873ff..73bd56b 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); @@ -569,25 +570,6 @@ 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. - * @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. - */ - static ErrCode SetDisturbMode(NotificationConstant::DisturbMode mode); - - /** - * Obtains the Disturb Mode. - * @param disturbMode The current type of the Do Not Disturb mode. - * @return Returns get disturb mode result. - */ - static ErrCode GetDisturbMode(NotificationConstant::DisturbMode &disturbMode); - /** * Cancel the notification of the specified group of this application. * @@ -604,6 +586,32 @@ public: * @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 doNotDisturbDate Indicates the do not disturb time to set. + * @return Returns set do not disturb time result. + */ + static 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. + */ + 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); }; } // 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 f9594c6..b8adaaf 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot.h +++ b/interfaces/innerkits/ans/native/include/notification_slot.h @@ -240,8 +240,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 f979cdd..7231289 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot_group.h +++ b/interfaces/innerkits/ans/native/include/notification_slot_group.h @@ -30,7 +30,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). */ diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 114a52f..54ce4f3 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -20,7 +20,6 @@ #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" @@ -98,11 +97,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 { @@ -139,7 +138,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/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index bf19774..c95b1a1 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -87,6 +87,8 @@ enum DisturbMode { ALLOW_UNKNOWN, ALLOW_ALL, ALLOW_PRIORITY, ALLOW_NONE, ALLOW_A enum InputEditType { EDIT_AUTO, EDIT_DISABLED, EDIT_ENABLED }; +enum DoNotDisturbType { TYPE_NONE, TYPE_ONCE, TYPE_DAILY, TYPE_CLEARLY }; + struct NotificationSubscribeInfo { std::vector bundleNames; int userId = 0; @@ -140,6 +142,8 @@ public: 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); @@ -180,6 +184,9 @@ public: static napi_value SetNotificationActionButton( const napi_env &env, const std::shared_ptr &actionButton, 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); @@ -212,7 +219,9 @@ 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 napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); @@ -221,6 +230,8 @@ private: 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_; }; diff --git a/interfaces/kits/napi/ans/include/constant.h b/interfaces/kits/napi/ans/include/constant.h index 249864a..96cb86f 100644 --- a/interfaces/kits/napi/ans/include/constant.h +++ b/interfaces/kits/napi/ans/include/constant.h @@ -30,6 +30,7 @@ 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 ConstantInit(napi_env env, napi_value exports); } // namespace NotificationNapi diff --git a/interfaces/kits/napi/ans/include/disturb_mode.h b/interfaces/kits/napi/ans/include/disturb_mode.h index 9a199f9..5b86d6e 100644 --- a/interfaces/kits/napi/ans/include/disturb_mode.h +++ b/interfaces/kits/napi/ans/include/disturb_mode.h @@ -21,7 +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 diff --git a/interfaces/kits/napi/ans/include/subscribe.h b/interfaces/kits/napi/ans/include/subscribe.h index 77a3174..08c0df5 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -45,7 +45,7 @@ public: 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,8 @@ private: CallbackInfo unsubscribeCallbackInfo_; CallbackInfo dieCallbackInfo_; CallbackInfo disturbModeCallbackInfo_; + CallbackInfo disturbDateCallbackInfo_; + }; struct SubscriberInstancesInfo { diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 62765bf..0db4a19 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -200,6 +200,27 @@ napi_value Common::JSParaError(const napi_env &env, const napi_ref &callback) } } +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[ONLY_CALLBACK_MIN_PARA], &valuetype)); + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + napi_create_reference(env, argv[ONLY_CALLBACK_MIN_PARA], 1, &callback); + } + + return Common::NapiGetNull(env); +} + napi_value Common::SetNotification( const napi_env &env, OHOS::Notification::Notification *notification, napi_value &result) { @@ -987,6 +1008,34 @@ napi_value Common::SetNotificationActionButton( return NapiGetboolean(env, true); } +napi_value Common::SetDoNotDisturbDate( + const napi_env &env, const NotificationDoNotDisturbDate &date, napi_value &result) +{ + ANS_LOGI("enter"); + enum DoNotDisturbType outType = DoNotDisturbType::TYPE_NONE; + if (DoNotDisturbTypeCToJS(date.GetDoNotDisturbType(), outType)) { + // type:DoNotDisturbType + napi_value typeNapi = nullptr; + napi_create_int32(env, 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); + } else { + return NapiGetboolean(env, false); + } + return NapiGetboolean(env, true); +} + napi_value Common::GetNotificationSubscriberInfo( const napi_env &env, const napi_value &value, NotificationSubscribeInfo &subscriberInfo) { @@ -2733,18 +2782,6 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va slot.SetLockscreenVisibleness(NotificationConstant::VisiblenessType(lockscreenVisibility)); } - // 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); - } - // sound?: string NAPI_CALL(env, napi_has_named_property(env, value, "sound", &hasProperty)); if (hasProperty) { @@ -2805,6 +2842,19 @@ 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); } @@ -3050,26 +3100,45 @@ 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 DisturbMode::ALLOW_UNKNOWN: - outType = NotificationConstant::DisturbMode::ALLOW_UNKNOWN; + 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 DisturbMode::ALLOW_ALL: - outType = NotificationConstant::DisturbMode::ALLOW_ALL; + 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 DisturbMode::ALLOW_PRIORITY: - outType = NotificationConstant::DisturbMode::ALLOW_PRIORITY; + case NotificationConstant::DoNotDisturbType::ONCE: + outType = DoNotDisturbType::TYPE_ONCE; break; - case DisturbMode::ALLOW_NONE: - outType = NotificationConstant::DisturbMode::ALLOW_NONE; + case NotificationConstant::DoNotDisturbType::DAILY: + outType = DoNotDisturbType::TYPE_DAILY; break; - case DisturbMode::ALLOW_ALARMS: - outType = NotificationConstant::DisturbMode::ALLOW_ALARMS; + case NotificationConstant::DoNotDisturbType::CLEARLY: + outType = DoNotDisturbType::TYPE_CLEARLY; break; default: - ANS_LOGE("DisturbMode %{public}d is an invalid value", inType); + ANS_LOGE("DoNotDisturbType %{public}d is an invalid value", inType); return false; } return true; diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index 3b16f77..e3946a9 100644 --- a/interfaces/kits/napi/ans/src/constant.cpp +++ b/interfaces/kits/napi/ans/src/constant.cpp @@ -208,6 +208,26 @@ 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, DoNotDisturbType::TYPE_NONE, "TYPE_NONE"); + SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_ONCE, "TYPE_ONCE"); + SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_DAILY, "TYPE_DAILY"); + SetNamedPropertyByInteger(env, obj, 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 ConstantInit(napi_env env, napi_value exports) { NotificationReasonInit(env, exports); @@ -218,6 +238,7 @@ napi_value ConstantInit(napi_env env, napi_value exports) DoNotDisturbMode(env, exports); InputEditTypeInit(env, exports); ContentTypeInit(env, exports); + DoNotDisturbTypeInit(env, exports); return exports; } diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index 5bb64c1..2c261eb 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 disturbMode = 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)); + + return Common::NapiGetNull(env); +} + +napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, SetDoNotDisturbDateParams ¶ms) { ANS_LOGI("enter"); - size_t argc = DISTURB_MODE_MAX_PARA; - napi_value argv[DISTURB_MODE_MAX_PARA] = {nullptr}; + 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_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + if (GetDoNotDisturbDate(env, argv[0], 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[SET_DISTURB_MIN_PARA], &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[SET_DISTURB_MIN_PARA], 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,19 @@ 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); }, [](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 +184,138 @@ 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); + }, + 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->disturbMode); + ANS_LOGI("asynccallbackinfo->disturbMode = %{public}d", asynccallbackinfo->disturbMode); + ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", asynccallbackinfo->info.errorCode); + }, + [](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->disturbMode, &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/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 46ccbec..e72edda 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -62,7 +62,9 @@ napi_value NotificationInit(napi_env env, napi_value exports) 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), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index 7bcaf88..d94182c 100644 --- a/interfaces/kits/napi/ans/src/publish.cpp +++ b/interfaces/kits/napi/ans/src/publish.cpp @@ -26,12 +26,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; }; @@ -92,7 +90,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 +109,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/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 54bfade..ee5de83 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -28,12 +28,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; @@ -292,8 +294,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); @@ -624,8 +626,87 @@ void SubscriberInstance::OnDied() } } -void SubscriberInstance::OnDisturbModeChanged(int disturbMode) -{} +void UvQueueWorkOnDoNotDisturbDateChange(uv_work_t *work, int status) +{ + ANS_LOGI("OnDoNotDisturbDateChange 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 (!Common::SetDoNotDisturbDate(dataWorkerData->env, dataWorkerData->date, result)) { + result = Common::NapiGetNull(dataWorkerData->env); + } + + Common::SetCallback(dataWorkerData->env, dataWorkerData->ref, result); + + delete dataWorkerData; + dataWorkerData = nullptr; + delete work; + work = nullptr; +} + +void SubscriberInstance::OnDoNotDisturbDateChange(const std::shared_ptr &date) +{ + ANS_LOGI("enter"); + + if (disturbDateCallbackInfo_.ref == nullptr) { + ANS_LOGI("disturbDateCallbackInfo_ callback unset"); + return; + } + + if (date == nullptr) { + ANS_LOGE("date is null"); + return; + } + + uv_loop_s *loop = nullptr; + napi_get_uv_event_loop(disturbDateCallbackInfo_.env, &loop); + if (loop == nullptr) { + ANS_LOGE("loop instance is nullptr"); + return; + } + + NotificationReceiveDataWorker *dataWorker = new (std::nothrow) NotificationReceiveDataWorker(); + if (dataWorker == nullptr) { + ANS_LOGE("new dataWorker failed"); + return; + } + + 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; + + 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) { @@ -669,6 +750,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) { @@ -685,6 +772,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"); } @@ -801,6 +890,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); } diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml index ccaa7c4..55c3ff3 100755 --- a/sa_profile/3203.xml +++ b/sa_profile/3203.xml @@ -17,6 +17,7 @@ 3203 /system/lib/libans.z.so + 1301 3299 5000 true diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 180ec3c..249f437 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -38,7 +38,6 @@ 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", @@ -57,6 +56,7 @@ ohos_shared_library("libans") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index c05bd30..a476c59 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -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,6 +99,9 @@ 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; @@ -144,7 +145,10 @@ private: ErrCode SetRecentNotificationCount(const std::string arg); void UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason); + void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); + private: + bool CheckPermission(const std::string &bundleName); static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/disturb_filter.h b/services/ans/include/disturb_filter.h index 7ced699..3a28a32 100644 --- a/services/ans/include/disturb_filter.h +++ b/services/ans/include/disturb_filter.h @@ -30,6 +30,9 @@ public: void OnStop() override; ErrCode OnPublish(const std::shared_ptr &record) override; + +private: + void GetTimeInterval(int64_t &beginDate, int64_t &endDate); }; } // namespace Notification diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index 103c4c1..3104edf 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); @@ -61,33 +66,35 @@ public: 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 GetDoNotDisturbDate(sptr &date); + ErrCode SetDoNotDisturbDate(const sptr date); + 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, - 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, + 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 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); + 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); + 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 GetBundleProperty( + const sptr &bundleOption, const BundleType &type, T &value) const; std::string GenerateBundleKey(const sptr &bundleOption) const; private: @@ -95,7 +102,6 @@ private: 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 b88bafb..9b6526d 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -39,7 +39,7 @@ public: 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 PutDoNotDisturbDate(const sptr &date); bool ParseFromDisturbeDB(NotificationPreferencesInfo &info); @@ -87,6 +87,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 +103,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); @@ -121,7 +124,7 @@ 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; diff --git a/services/ans/include/notification_preferences_info.h b/services/ans/include/notification_preferences_info.h index 4e78453..ac53056 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" @@ -81,8 +82,8 @@ public: {} void SetEnabledAllNotification(const bool &value); bool GetEnabledAllNotification() const; - void SetDisturbMode(const NotificationConstant::DisturbMode &mode); - NotificationConstant::DisturbMode GetDisturbMode() const; + void SetDoNotDisturbDate(const sptr &date); + sptr GetDoNotDisturbDate() const; void SetBundleInfo(const BundleInfo &info); bool GetBundleInfo(const sptr &bundleOption, BundleInfo &info) const; bool RemoveBundleInfo(const sptr &bundleOption); @@ -91,7 +92,7 @@ public: private: bool isEnabledAllNotification_ = true; - NotificationConstant::DisturbMode disturbMode_ = NotificationConstant::DisturbMode::ALLOW_ALL; + sptr doNotDisturbDate_ = new NotificationDoNotDisturbDate(); std::map infos_; }; } // namespace Notification diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index 0758789..ea96bfa 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -45,7 +45,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: @@ -67,7 +67,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_ {}; diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index 30702e8..f4ced93 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -19,7 +19,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 = "_"; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index f91e697..cde4d34 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -22,8 +22,8 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "ans_permission_define.h" #include "bundle_manager_helper.h" -#include "disturb_filter.h" #include "ipc_skeleton.h" #include "notification_constant.h" #include "notification_filter.h" @@ -31,6 +31,7 @@ #include "notification_slot.h" #include "notification_slot_filter.h" #include "notification_subscriber_manager.h" +#include "permission/permission_kit.h" #include "permission_filter.h" namespace OHOS { @@ -46,6 +47,8 @@ static const int32_t NOTIFICATION_MAX_COUNT = 1024; static const int32_t DEFAULT_RECENT_COUNT = 16; +constexpr int HOURS_IN_ONE_DAY = 24; + struct RecentNotification { sptr notification = nullptr; bool isActive = false; @@ -65,7 +68,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() @@ -661,37 +663,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; @@ -1721,5 +1692,183 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( 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 (date == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + + ErrCode result = ERR_OK; + + int64_t beginDate = ResetSeconds(date->GetBeginDate()); + int64_t endDate = ResetSeconds(date->GetEndDate()); + + if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { + beginDate = 0; + endDate = 0; + } + if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::ONCE) { + AdjustDateForDndTypeOnce(beginDate, endDate); + } + + const sptr newConfig = new NotificationDoNotDisturbDate( + date->GetDoNotDisturbType(), + beginDate, + endDate + ); + + handler_->PostSyncTask(std::bind([&]() { + result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(newConfig); + if (result == ERR_OK) { + NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig); + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr &date) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind([&]() { + sptr currentConfig = nullptr; + result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(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(date); + } else { + date = currentConfig; + } + break; + default: + date = currentConfig; + break; + } + } + })); + + return ERR_OK; +} + +ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSupport) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + doesSupport = SUPPORT_DO_NOT_DISTRUB; + return ERR_OK; +} + +bool AdvancedNotificationService::CheckPermission(const std::string &bundleName) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + bool isGranted = false; + if (bundleName.empty()) { + ANS_LOGE("Bundle name is empty."); + return isGranted; + } + int result = Security::Permission::PermissionKit::VerifyPermission(bundleName, ANS_PERMISSION_CONTROLLER, 0); + if (Security::Permission::TypePermissionState::PERMISSION_GRANTED == result) { + isGranted = true; + } else { + ANS_LOGE("Permission granted failed."); + } + return isGranted; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/disturb_filter.cpp b/services/ans/src/disturb_filter.cpp deleted file mode 100644 index d5ebca7..0000000 --- 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 a95b1fc..dcf3080 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -512,18 +512,18 @@ ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) return result; } -ErrCode NotificationPreferences::GetDisturbMode(NotificationConstant::DisturbMode &mode) +ErrCode NotificationPreferences::GetDoNotDisturbDate(sptr &date) { - mode = preferencesInfo_.GetDisturbMode(); + date = preferencesInfo_.GetDoNotDisturbDate(); return ERR_OK; } -ErrCode NotificationPreferences::SetDisturbMode(const NotificationConstant::DisturbMode &mode) +ErrCode NotificationPreferences::SetDoNotDisturbDate(const sptr date) { NotificationPreferencesInfo preferencesInfo = preferencesInfo_; - preferencesInfo.SetDisturbMode(mode); + preferencesInfo.SetDoNotDisturbDate(date); ErrCode result = ERR_OK; - if (!preferncesDB_->PutDisturbMode(mode)) { + if (!preferncesDB_->PutDoNotDisturbDate(date)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index d9e16a8..1243e40 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -78,7 +78,7 @@ const std::map &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; + type.key = OHOS::DistributedKv::Key(KEY_DO_NOT_DISTURB_TYPE); + type.value = OHOS::DistributedKv::Value(std::to_string((int)date->GetDoNotDisturbType())); + + OHOS::DistributedKv::Entry beginDate; + beginDate.key = OHOS::DistributedKv::Key(KEY_DO_NOT_DISTURB_BEGIN_DATE); + beginDate.value = OHOS::DistributedKv::Value(std::to_string(date->GetBeginDate())); + + OHOS::DistributedKv::Entry endDate; + endDate.key = OHOS::DistributedKv::Key(KEY_DO_NOT_DISTURB_END_DATE); + 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; } @@ -485,7 +506,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()) { @@ -784,7 +807,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), @@ -919,6 +942,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 +990,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,15 +1101,16 @@ 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) { + KEY_DO_NOT_DISTURB_TYPE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDisturbMode(info.GetDisturbMode()); + PutDoNotDisturbDate(info.GetDoNotDisturbDate()); } else if (status == OHOS::DistributedKv::Status::SUCCESS) { if (!value.ToString().empty()) { - info.SetDisturbMode(static_cast(StringToInt(value.ToString()))); + auto date = info.GetDoNotDisturbDate(); + date->SetDoNotDisturbType((NotificationConstant::DoNotDisturbType)StringToInt(value.ToString())); } } else { ANS_LOGW("Parse disturbe mode failed, use defalut value."); @@ -1080,6 +1118,40 @@ void NotificationPreferencesDatabase::ParseDisturbeMode(NotificationPreferencesI }); } +void NotificationPreferencesDatabase::ParseDoNotDisturbBeginDate(NotificationPreferencesInfo &info) +{ + GetValueFromDisturbeDB( + KEY_DO_NOT_DISTURB_BEGIN_DATE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDoNotDisturbDate(info.GetDoNotDisturbDate()); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + auto date = info.GetDoNotDisturbDate(); + date->SetBeginDate(StringToInt64(value.ToString())); + } + } else { + ANS_LOGW("Parse disturbe start time failed, use defalut value."); + } + }); +} + +void NotificationPreferencesDatabase::ParseDoNotDisturbEndDate(NotificationPreferencesInfo &info) +{ + GetValueFromDisturbeDB( + KEY_DO_NOT_DISTURB_END_DATE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { + if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { + PutDoNotDisturbDate(info.GetDoNotDisturbDate()); + } else if (status == OHOS::DistributedKv::Status::SUCCESS) { + if (!value.ToString().empty()) { + auto date = info.GetDoNotDisturbDate(); + date->SetEndDate(StringToInt64(value.ToString())); + } + } else { + ANS_LOGW("Parse disturbe end time failed, use defalut value."); + } + }); +} + void NotificationPreferencesDatabase::ParseEnableAllNotification(NotificationPreferencesInfo &info) { GetValueFromDisturbeDB( @@ -1213,6 +1285,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 +1294,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); diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 9e58416..539035f 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -238,14 +238,14 @@ bool NotificationPreferencesInfo::GetEnabledAllNotification() const return isEnabledAllNotification_; } -void NotificationPreferencesInfo::SetDisturbMode(const NotificationConstant::DisturbMode &mode) +void NotificationPreferencesInfo::SetDoNotDisturbDate(const sptr &date) { - disturbMode_ = mode; + doNotDisturbDate_ = date; } -NotificationConstant::DisturbMode NotificationPreferencesInfo::GetDisturbMode() const +sptr NotificationPreferencesInfo::GetDoNotDisturbDate() const { - return disturbMode_; + return doNotDisturbDate_; } void NotificationPreferencesInfo::SetBundleInfo(const BundleInfo &info) diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 5f0eadd..0f4a21b 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -118,17 +118,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) @@ -295,10 +295,10 @@ void NotificationSubscriberManager::NotifyUpdatedInner(const sptr &date) { for (auto record : subscriberRecordList_) { - record->subscriber->OnDisturbModeChanged(mode); + record->subscriber->OnDoNotDisturbDateChange(date); } } } // namespace Notification diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 0f88ad8..d131b5f 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -41,7 +41,6 @@ ohos_unittest("ans_unit_test") { sources = [ "${services_path}/ans/src/advanced_notification_service.cpp", "${services_path}/ans/src/advanced_notification_service_ability.cpp", - "${services_path}/ans/src/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", @@ -53,13 +52,13 @@ ohos_unittest("ans_unit_test") { "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/autils/src/constant.cpp", "advanced_notification_service_ability_test.cpp", "advanced_notification_service_test.cpp", - "disturb_filter_test.cpp", "mock/blob.cpp", "mock/distributed_kv_data_manager.cpp", "mock/mock_bundle_manager_helper.cpp", "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", "notification_preferences_database_test.cpp", "notification_preferences_test.cpp", "notification_slot_filter_test.cpp", @@ -87,6 +86,7 @@ ohos_unittest("ans_unit_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] 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 a13769a..e447dec 100644 --- a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -33,7 +33,7 @@ public: /** * @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( diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index de51a5b..1d6b79c 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -88,7 +88,7 @@ public: {} 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,7 +617,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02700, /** * @tc.number : AdvancedNotificationServiceTest_02800 - * @tc.name : AMS_ANS_GetShowBadgeEnabledForBundle_0100 + * @tc.name : ANS_GetShowBadgeEnabledForBundle_0100 * @tc.desc : Test GetShowBadgeEnabledForBundle function */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, Function | SmallTest | Level1) @@ -634,7 +634,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_02800, /** * @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) @@ -643,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) @@ -681,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) @@ -693,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) @@ -703,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) @@ -718,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) @@ -754,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) @@ -770,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) @@ -794,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) @@ -806,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) @@ -819,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) @@ -837,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) @@ -852,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) @@ -863,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) @@ -875,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) @@ -890,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) @@ -903,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) @@ -921,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) @@ -940,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) @@ -951,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) @@ -963,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) @@ -974,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) @@ -988,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) @@ -1004,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) @@ -1020,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) @@ -1036,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) @@ -1052,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) @@ -1064,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) @@ -1077,7 +1052,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_06900, /** * @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) @@ -1088,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) @@ -1099,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) @@ -1111,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) @@ -1121,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) @@ -1134,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) @@ -1152,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) @@ -1165,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) @@ -1182,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) @@ -1193,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) @@ -1204,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) @@ -1218,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) @@ -1232,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) @@ -1246,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) @@ -1260,7 +1235,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_09800, /** * @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) @@ -1295,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) @@ -1327,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) @@ -1359,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) @@ -1391,7 +1366,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10200, /** * @tc.number : AdvancedNotificationServiceTest_10300 - * @tc.name : AMS_ANS_Cancel_By_Group_10300 + * @tc.name : ANS_Cancel_By_Group_10300 * @tc.desc : Cancel notification by group name. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10300, Function | SmallTest | Level1) @@ -1416,7 +1391,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10300, /** * @tc.number : AdvancedNotificationServiceTest_10400 - * @tc.name : AMS_ANS_Remove_By_Group_10400 + * @tc.name : ANS_Remove_By_Group_10400 * @tc.desc : Remove notification by group name. */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10400, Function | SmallTest | Level1) @@ -1439,5 +1414,148 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10400, 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); +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp index 69f6b11..dc710da 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -36,7 +36,7 @@ public: /** * @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 +48,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/permission_kit.cpp b/services/ans/test/unittest/mock/permission_kit.cpp new file mode 100644 index 0000000..36855b9 --- /dev/null +++ b/services/ans/test/unittest/mock/permission_kit.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission/permission_kit.h" + +namespace OHOS { +namespace Security { +namespace Permission { +using namespace std; + +int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) +{ + return TypePermissionState::PERMISSION_GRANTED; +} + +bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::AddUserGrantedReqPermissions( + const string &bundleName, const std::vector &permList, int userId) +{ + return 0; +} + +int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) +{ + return 0; +} + +int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::AddDefPermissions(const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveDefPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) +{ + return 0; +} +} // namespace Permission +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index 36f044d..6cb5f77 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -241,17 +241,71 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutNotificationsEnabled_00100, Fun } /** - * @tc.number : PutDisturbMode_00100 + * @tc.number : PutDoNotDisturbDate_00100 * @tc.name : - * @tc.desc : Put disturbe mode into disturbe DB, return is true. + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is NONE, return is true. */ -HWTEST_F(NotificationPreferencesDatabaseTest, PutDisturbMode_00100, Function | SmallTest | Level1) +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00100, 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)); + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(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(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(date)); +} + +/** + * @tc.number : PutDoNotDisturbDate_00400 + * @tc.name : + * @tc.desc : Put disturbe mode into disturbe DB when DoNotDisturbType is CLEARLY, return is true. + */ +HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00400, 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::CLEARLY, beginDate, endDate); + + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(date)); } /** @@ -387,7 +441,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) diff --git a/services/ans/test/unittest/notification_preferences_test.cpp b/services/ans/test/unittest/notification_preferences_test.cpp index f212153..6c53534 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1036,29 +1036,46 @@ HWTEST_F(NotificationPreferencesTest, GetNotificationsEnabled_00100, Function | } /** - * @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(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(date), (int)ERR_OK); + sptr getDate; + EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(getDate), (int)ERR_OK); + EXPECT_EQ(getDate->GetDoNotDisturbType(), NotificationConstant::DoNotDisturbType::DAILY); + EXPECT_EQ(getDate->GetBeginDate(), beginDate); + EXPECT_EQ(getDate->GetEndDate(), endDate); +} } // 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 1d8582a..15e72a0 100644 --- a/services/ans/test/unittest/notification_slot_filter_test.cpp +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -32,7 +32,7 @@ public: /** * @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 +43,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 +54,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 40b26ce..6ce1eee 100644 --- a/services/ans/test/unittest/notification_subscriber_manager_test.cpp +++ b/services/ans/test/unittest/notification_subscriber_manager_test.cpp @@ -44,7 +44,7 @@ private: {} 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 +92,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 +104,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 +130,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 +145,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 +158,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 +169,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 +181,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 6472f51..3aa2fa8 100644 --- a/services/ans/test/unittest/permission_filter_test.cpp +++ b/services/ans/test/unittest/permission_filter_test.cpp @@ -47,7 +47,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 +58,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/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index e982028..02ebb5b 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -40,7 +40,6 @@ ohos_moduletest("ans_module_test") { "${services_path}/ans/src/advanced_notification_service.cpp", "${services_path}/ans/src/advanced_notification_service_ability.cpp", "${services_path}/ans/src/bundle_manager_helper.cpp", - "${services_path}/ans/src/disturb_filter.cpp", "${services_path}/ans/src/notification_preferences.cpp", "${services_path}/ans/src/notification_preferences_database.cpp", "${services_path}/ans/src/notification_preferences_info.cpp", @@ -58,6 +57,7 @@ ohos_moduletest("ans_module_test") { "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", + "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -86,6 +86,7 @@ ohos_moduletest("ans_module_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index 1a76cf3..a967f8b 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -33,8 +33,6 @@ sptr g_advancedNotificationService; bool passed = false; class TestAnsSubscriber : public NotificationSubscriber { public: - ~TestAnsSubscriber(){}; - void OnConnected() override { if (subscriberCb_ != nullptr) { @@ -51,7 +49,7 @@ public: {} 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 {} @@ -124,7 +122,7 @@ void TestAddSlots() /** * @tc.number : AnsModuleTest_001 - * @tc.name : AMS_ANS_Subscribe_Publish_0100 + * @tc.name : ANS_Subscribe_Publish_0100 * @tc.desc : Test the functions of subscribing, publishing, and canceling */ HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) @@ -152,7 +150,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_001, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_002 - * @tc.name : AMS_ANS_GetActiveNotifications_0200 + * @tc.name : ANS_Module_Test_0200 * @tc.desc : Test the function of getting notifications and getting all notifications */ HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) @@ -184,7 +182,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_002, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_003 - * @tc.name : AMS_ANS_GetActiveNotifications_0300 + * @tc.name : ANS_Module_Test_0300 * @tc.desc : Test publish notifications when slot are not allowed publish. */ HWTEST_F(AnsModuleTest, AnsModuleTest_003, Function | SmallTest | Level1) @@ -216,44 +214,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_003, Function | SmallTest | Level1) g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); } -/** - * @tc.number : AnsModuleTest_004 - * @tc.name : AMS_ANS_GetActiveNotifications_0400 - * @tc.desc : Test publish notifications when Disturb are not allowed publish. - */ -HWTEST_F(AnsModuleTest, AnsModuleTest_004, Function | SmallTest | Level1) -{ - // subscriber - auto subscriber = new TestAnsSubscriber(); - sptr subscriberInfo = new NotificationSubscribeInfo(); - g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); - subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { - passed = true; - }; - - // add slot - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - slots.push_back(slot0); - g_advancedNotificationService->AddSlots(slots); - - // create request - std::string label = "testLabel"; - sptr req = new NotificationRequest(0); - req->SetLabel(label); - req->SetStatusBarText("text"); - - g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); - - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(false, passed); - g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); -} - /** * @tc.number : AnsModuleTest_005 - * @tc.name : AMS_ANS_GetActiveNotifications_0500 - * @tc.desc : Test publish notifications when Disturb are not allowed publish. + * @tc.name : ANS_Module_Test_0500 + * @tc.desc : Test publish notification when slot type is SERVICE_REMINDER. */ HWTEST_F(AnsModuleTest, AnsModuleTest_005, Function | SmallTest | Level1) { @@ -299,7 +263,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_005, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_006 - * @tc.name : AMS_ANS_GetActiveNotifications_0600 + * @tc.name : ANS_Module_Test_0600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_006, Function | SmallTest | Level1) @@ -332,8 +296,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_006, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_007 - * @tc.name : AMS_ANS_GetActiveNotifications_0700 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + * @tc.name : ANS_Module_Test_0700 + * @tc.desc : Test publish notification when slot type is OTHER. */ HWTEST_F(AnsModuleTest, AnsModuleTest_007, Function | SmallTest | Level1) { @@ -379,8 +343,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_007, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0013 - * @tc.name : AMS_ANS_GetActiveNotifications_01300 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + * @tc.name : ANS_Module_Test_01300 + * @tc.desc : Test publish notification when slot type is SOCIAL_COMMUNICATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0013, Function | SmallTest | Level1) { @@ -412,8 +376,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0013, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0014 - * @tc.name : AMS_ANS_GetActiveNotifications_01400 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + * @tc.name : ANS_Module_Test_01400 + * @tc.desc : Test publish notification when slot type is SOCIAL_COMMUNICATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0014, Function | SmallTest | Level1) { @@ -450,8 +414,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0014, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0015 - * @tc.name : AMS_ANS_GetActiveNotifications_01500 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + * @tc.name : ANS_Module_Test_01500 + * @tc.desc : Test publish notification when slot type is SOCIAL_COMMUNICATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0015, Function | SmallTest | Level1) { @@ -488,8 +452,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0015, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0017 - * @tc.name : AMS_ANS_GetActiveNotifications_01700 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. + * @tc.name : ANS_Module_Test_01700 + * @tc.desc : Test publish notification when slot type is SOCIAL_COMMUNICATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0017, Function | SmallTest | Level1) { @@ -526,7 +490,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0017, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0019 - * @tc.name : AMS_ANS_GetActiveNotifications_01900 + * @tc.name : ANS_Module_Test_01900 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0019, Function | SmallTest | Level1) @@ -564,7 +528,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0019, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0021 - * @tc.name : AMS_ANS_GetActiveNotifications_02100 + * @tc.name : ANS_Module_Test_02100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0021, Function | SmallTest | Level1) @@ -617,7 +581,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0021, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0023 - * @tc.name : AMS_ANS_GetActiveNotifications_02300 + * @tc.name : ANS_Module_Test_02300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0023, Function | SmallTest | Level1) @@ -655,7 +619,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0023, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0031 - * @tc.name : AMS_ANS_GetActiveNotifications_03100 + * @tc.name : ANS_Module_Test_03100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0031, Function | SmallTest | Level1) @@ -708,7 +672,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0031, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0033 - * @tc.name : AMS_ANS_GetActiveNotifications_03300 + * @tc.name : ANS_Module_Test_03300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0033, Function | SmallTest | Level1) @@ -752,7 +716,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0033, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0034 - * @tc.name : AMS_ANS_GetActiveNotifications_03400 + * @tc.name : ANS_Module_Test_03400 * @tc.desc : Test publish notification when slot type is SOCIAL_COMMUNICATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0034, Function | SmallTest | Level1) @@ -796,7 +760,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0034, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0035 - * @tc.name : AMS_ANS_GetActiveNotifications_03500 + * @tc.name : ANS_Module_Test_03500 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0035, Function | SmallTest | Level1) @@ -836,7 +800,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0035, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0036 - * @tc.name : AMS_ANS_GetActiveNotifications_03600 + * @tc.name : ANS_Module_Test_03600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0036, Function | SmallTest | Level1) @@ -876,7 +840,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0036, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0039 - * @tc.name : AMS_ANS_GetActiveNotifications_03900 + * @tc.name : ANS_Module_Test_03900 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0039, Function | SmallTest | Level1) @@ -930,7 +894,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0039, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0040 - * @tc.name : AMS_ANS_GetActiveNotifications_04000 + * @tc.name : ANS_Module_Test_04000 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0040, Function | SmallTest | Level1) @@ -968,7 +932,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0040, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0041 - * @tc.name : AMS_ANS_GetActiveNotifications_04100 + * @tc.name : ANS_Module_Test_04100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0041, Function | SmallTest | Level1) @@ -1006,7 +970,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0041, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0042 - * @tc.name : AMS_ANS_GetActiveNotifications_04200 + * @tc.name : ANS_Module_Test_04200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0042, Function | SmallTest | Level1) @@ -1044,7 +1008,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0042, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0043 - * @tc.name : AMS_ANS_GetActiveNotifications_04300 + * @tc.name : ANS_Module_Test_04300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0043, Function | SmallTest | Level1) @@ -1082,7 +1046,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0043, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0049 - * @tc.name : AMS_ANS_GetActiveNotifications_04900 + * @tc.name : ANS_Module_Test_04900 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0049, Function | SmallTest | Level1) @@ -1103,7 +1067,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0049, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0051 - * @tc.name : AMS_ANS_GetActiveNotifications_05100 + * @tc.name : ANS_Module_Test_05100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0051, Function | SmallTest | Level1) @@ -1129,7 +1093,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0051, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0052 - * @tc.name : AMS_ANS_GetActiveNotifications_05200 + * @tc.name : ANS_Module_Test_05200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0052, Function | SmallTest | Level1) @@ -1154,7 +1118,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0052, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0054 - * @tc.name : AMS_ANS_GetActiveNotifications_05400 + * @tc.name : ANS_Module_Test_05400 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0054, Function | SmallTest | Level1) @@ -1186,7 +1150,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0054, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0055 - * @tc.name : AMS_ANS_GetActiveNotifications_05500 + * @tc.name : ANS_Module_Test_05500 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0055, Function | SmallTest | Level1) @@ -1204,7 +1168,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0055, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0056 - * @tc.name : AMS_ANS_GetActiveNotifications_05600 + * @tc.name : ANS_Module_Test_05600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0056, Function | SmallTest | Level1) @@ -1228,7 +1192,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0056, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0058 - * @tc.name : AMS_ANS_GetActiveNotifications_05800 + * @tc.name : ANS_Module_Test_05800 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) @@ -1269,7 +1233,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0058, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0060 - * @tc.name : AMS_ANS_GetActiveNotifications_06000 + * @tc.name : ANS_Module_Test_06000 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0060, Function | SmallTest | Level1) @@ -1316,7 +1280,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0060, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0061 - * @tc.name : AMS_ANS_GetActiveNotifications_06100 + * @tc.name : ANS_Module_Test_06100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0061, Function | SmallTest | Level1) @@ -1363,7 +1327,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0061, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_062 - * @tc.name : AMS_ANS_GetActiveNotifications_06200 + * @tc.name : ANS_Module_Test_06200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0062, Function | SmallTest | Level1) @@ -1410,7 +1374,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0062, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_063 - * @tc.name : AMS_ANS_GetActiveNotifications_06300 + * @tc.name : ANS_Module_Test_06300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0063, Function | SmallTest | Level1) @@ -1455,7 +1419,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0063, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_064 - * @tc.name : AMS_ANS_GetActiveNotifications_06400 + * @tc.name : ANS_Module_Test_06400 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0064, Function | SmallTest | Level1) @@ -1472,7 +1436,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0064, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_065 - * @tc.name : AMS_ANS_GetActiveNotifications_06500 + * @tc.name : ANS_Module_Test_06500 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0065, Function | SmallTest | Level1) @@ -1487,7 +1451,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0065, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_066 - * @tc.name : AMS_ANS_GetActiveNotifications_06600 + * @tc.name : ANS_Module_Test_06600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0066, Function | SmallTest | Level1) @@ -1515,7 +1479,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0066, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_100 - * @tc.name : AMS_ANS_GetActiveNotifications_10000 + * @tc.name : ANS_Module_Test_10000 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0100, Function | SmallTest | Level1) @@ -1558,7 +1522,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0100, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_101 - * @tc.name : AMS_ANS_GetActiveNotifications_10100 + * @tc.name : ANS_Module_Test_10100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0101, Function | SmallTest | Level1) @@ -1589,7 +1553,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0101, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_102 - * @tc.name : AMS_ANS_GetActiveNotifications_10200 + * @tc.name : ANS_Module_Test_10200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0102, Function | SmallTest | Level1) @@ -1620,7 +1584,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0102, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_103 - * @tc.name : AMS_ANS_GetActiveNotifications_10300 + * @tc.name : ANS_Module_Test_10300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) @@ -1649,44 +1613,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); } -/** - * @tc.number : AnsModuleTest_104 - * @tc.name : AMS_ANS_GetActiveNotifications_10400 - * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. - */ -HWTEST_F(AnsModuleTest, AnsModuleTest_0104, Function | SmallTest | Level1) -{ - // subscriber - auto subscriber = new TestAnsSubscriber(); - sptr subscriberInfo = new NotificationSubscribeInfo(); - g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); - subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { - passed = true; - }; - - // add slot - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - slots.push_back(slot0); - g_advancedNotificationService->AddSlots(slots); - - // create request - std::string label = "testLabel"; - sptr req = new NotificationRequest(0); - req->SetLabel(label); - req->SetStatusBarText("text"); - req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - - g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); - - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(false, passed); - g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); -} - /** * @tc.number : AnsModuleTest_105 - * @tc.name : AMS_ANS_GetActiveNotifications_10500 + * @tc.name : ANS_Module_Test_10500 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0105, Function | SmallTest | Level1) @@ -1711,7 +1640,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0105, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_106 - * @tc.name : AMS_ANS_GetActiveNotifications_10600 + * @tc.name : ANS_Module_Test_10600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0106, Function | SmallTest | Level1) @@ -1746,7 +1675,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0106, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_107 - * @tc.name : AMS_ANS_GetActiveNotifications_10700 + * @tc.name : ANS_Module_Test_10700 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0107, Function | SmallTest | Level1) @@ -1793,7 +1722,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0107, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_108 - * @tc.name : AMS_ANS_GetActiveNotifications_10800 + * @tc.name : ANS_Module_Test_10800 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0108, Function | SmallTest | Level1) @@ -1839,7 +1768,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0108, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_110 - * @tc.name : AMS_ANS_GetActiveNotifications_11000 + * @tc.name : ANS_Module_Test_11000 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0110, Function | SmallTest | Level1) @@ -1858,7 +1787,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0110, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_111 - * @tc.name : AMS_ANS_GetActiveNotifications_11100 + * @tc.name : ANS_Module_Test_11100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0111, Function | SmallTest | Level1) @@ -1875,7 +1804,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0111, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_112 - * @tc.name : AMS_ANS_GetActiveNotifications_11200 + * @tc.name : ANS_Module_Test_11200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0112, Function | SmallTest | Level1) @@ -1932,7 +1861,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0112, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_113 - * @tc.name : AMS_ANS_GetActiveNotifications_11300 + * @tc.name : ANS_Module_Test_11300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0113, Function | SmallTest | Level1) @@ -1991,7 +1920,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0113, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_114 - * @tc.name : AMS_ANS_GetActiveNotifications_11400 + * @tc.name : ANS_Module_Test_11400 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0114, Function | SmallTest | Level1) @@ -2050,7 +1979,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0114, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_116 - * @tc.name : AMS_ANS_GetActiveNotifications_11600 + * @tc.name : ANS_Module_Test_11600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0116, Function | SmallTest | Level1) @@ -2110,7 +2039,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0116, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_117 - * @tc.name : AMS_ANS_GetActiveNotifications_11700 + * @tc.name : ANS_Module_Test_11700 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0117, Function | SmallTest | Level1) @@ -2168,48 +2097,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0117, Function | SmallTest | Level1) g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); } -/** - * @tc.number : AnsModuleTest_118 - * @tc.name : AMS_ANS_GetActiveNotifications_11800 - * @tc.desc : Test publish notifications when Disturb are not allowed publish. - */ -HWTEST_F(AnsModuleTest, AnsModuleTest_0118, Function | SmallTest | Level1) -{ - // subscriber - auto subscriber = new TestAnsSubscriber(); - sptr subscriberInfo = new NotificationSubscribeInfo(); - g_advancedNotificationService->Subscribe(subscriber->GetImpl(), subscriberInfo); - subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { - passed = true; - }; - - // add slot - std::vector> slots; - sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); - slots.push_back(slot0); - g_advancedNotificationService->AddSlots(slots); - - // create request - std::string label = "testLabel"; - sptr req = new NotificationRequest(0); - req->SetLabel(label); - req->SetStatusBarText("text"); - std::shared_ptr contentImpl = std::make_shared(); - contentImpl->SetText("1"); - contentImpl->SetTitle("1"); - std::shared_ptr content = std::make_shared(contentImpl); - req->SetContent(content); - - g_advancedNotificationService->SetDisturbMode(NotificationConstant::DisturbMode::ALLOW_NONE); - - g_advancedNotificationService->Publish(label, req); - EXPECT_EQ(false, passed); - g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), subscriberInfo); -} - /** * @tc.number : AnsModuleTest_120 - * @tc.name : AMS_ANS_GetActiveNotifications_12000 + * @tc.name : ANS_Module_Test_12000 * @tc.desc : Test publish notifications when Disturb are not allowed publish. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0120, Function | SmallTest | Level1) @@ -2249,7 +2139,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0120, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0121 - * @tc.name : AMS_ANS_GetActiveNotifications_12100 + * @tc.name : ANS_Module_Test_12100 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0121, Function | SmallTest | Level1) @@ -2278,7 +2168,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0121, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0122 - * @tc.name : AMS_ANS_GetActiveNotifications_12200 + * @tc.name : ANS_Module_Test_12200 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0122, Function | SmallTest | Level1) @@ -2327,7 +2217,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0122, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0123 - * @tc.name : AMS_ANS_GetActiveNotifications_12300 + * @tc.name : ANS_Module_Test_12300 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) @@ -2382,7 +2272,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0123, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0124 - * @tc.name : AMS_ANS_GetActiveNotifications_12400 + * @tc.name : ANS_Module_Test_12400 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0124, Function | SmallTest | Level1) @@ -2420,7 +2310,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0124, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0125 - * @tc.name : AMS_ANS_GetActiveNotifications_12500 + * @tc.name : ANS_Module_Test_12500 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0125, Function | SmallTest | Level1) @@ -2453,7 +2343,7 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0125, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0126 - * @tc.name : AMS_ANS_GetActiveNotifications_12600 + * @tc.name : ANS_Module_Test_12600 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0126, Function | SmallTest | Level1) @@ -2491,11 +2381,13 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0126, Function | SmallTest | Level1) /** * @tc.number : AnsModuleTest_0127 - * @tc.name : AMS_ANS_GetActiveNotifications_12700 + * @tc.name : ANS_Module_Test_12700 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0127, Function | SmallTest | Level1) { + const int EXPECT_REQUST_NUM = 2; + int ret = 0; // subscriber auto subscriber = new TestAnsSubscriber(); @@ -2542,17 +2434,21 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0127, Function | SmallTest | Level1) req1->SetSlotType(NotificationConstant::SlotType::SERVICE_REMINDER); // publish - EXPECT_EQ(0, ret); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req1), ERR_OK); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_EQ(ret, EXPECT_REQUST_NUM); } /** * @tc.number : AnsModuleTest_0128 - * @tc.name : AMS_ANS_GetActiveNotifications_12800 + * @tc.name : ANS_Module_Test_12800 * @tc.desc : Test publish notification when slot type is CONTENT_INFORMATION. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0128, Function | SmallTest | Level1) { + const int EXPECT_REQUST_NUM = 2; + int ret = 0; // subscriber auto subscriber = new TestAnsSubscriber(); @@ -2599,13 +2495,15 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0128, Function | SmallTest | Level1) req1->SetSlotType(NotificationConstant::SlotType::OTHER); // publish - EXPECT_EQ(0, ret); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Publish(label, req1), ERR_OK); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); + EXPECT_EQ(ret, EXPECT_REQUST_NUM); } /** * @tc.number : AnsModuleTest_0130 - * @tc.name : AMS_ANS_GetActiveNotifications_13000 + * @tc.name : ANS_Module_Test_13000 * @tc.desc : Test publish notification when slot type is OTHER. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0130, Function | SmallTest | Level1) @@ -2615,8 +2513,8 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0130, Function | SmallTest | Level1) g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); subscriber->consumedCb_ = [](const std::shared_ptr notification, const std::shared_ptr sortingMap) { - EXPECT_EQ(false, notification->EnableVibrate()); - EXPECT_EQ(NotificationConstant::VisiblenessType::PUBLIC, notification->GetLockscreenVisibleness()); + EXPECT_FALSE(notification->EnableVibrate()); + EXPECT_FALSE(notification->EnableSound()); }; // add slot @@ -2632,13 +2530,13 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0130, Function | SmallTest | Level1) req->SetSlotType(NotificationConstant::SlotType::OTHER); req->SetLabel(label); // publish - + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); } /** * @tc.number : AnsModuleTest_0131 - * @tc.name : AMS_ANS_GetActiveNotifications_13100 + * @tc.name : ANS_Module_Test_13100 * @tc.desc : Test publish notification when cancel a notification. */ HWTEST_F(AnsModuleTest, AnsModuleTest_0131, Function | SmallTest | Level1) @@ -2649,10 +2547,170 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0131, Function | SmallTest | Level1) subscriber->canceledCb_ = [](const std::shared_ptr &request, const std::shared_ptr &sortingMap, int deleteReason) { passed = true; }; - // g_advancedNotificationService->Cancel(1, "1"); + g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr); EXPECT_EQ(false, passed); } +/** + * @tc.number : AnsModuleTest_0132 + * @tc.name : ANS_Module_Test_13200 + * @tc.desc : Test publish notifications when Dnd type is NONE. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0132, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + EXPECT_EQ(g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr), ERR_OK); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + + sptr date = + new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); + EXPECT_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); + EXPECT_TRUE(passed); +} + +/** + * @tc.number : AnsModuleTest_0133 + * @tc.name : ANS_Module_Test_13300 + * @tc.desc : Test publish notifications when Dnd type is ONCE. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0133, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + EXPECT_EQ(g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr), ERR_OK); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + 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(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); + EXPECT_TRUE(passed); +} + +/** + * @tc.number : AnsModuleTest_0134 + * @tc.name : ANS_Module_Test_13400 + * @tc.desc : Test publish notifications when Dnd type is DAILY. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0134, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + 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(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); + EXPECT_TRUE(passed); +} + +/** + * @tc.number : AnsModuleTest_0135 + * @tc.name : ANS_Module_Test_13500 + * @tc.desc : Test publish notifications when Dnd type is CLEARLY. + */ +HWTEST_F(AnsModuleTest, AnsModuleTest_0135, Function | SmallTest | Level1) +{ + // subscriber + auto subscriber = new TestAnsSubscriber(); + g_advancedNotificationService->Subscribe(subscriber->GetImpl(), nullptr); + subscriber->consumedCb_ = [](const std::shared_ptr, const std::shared_ptr) { + passed = true; + }; + + // add slot + std::vector> slots; + sptr slot0 = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + slots.push_back(slot0); + g_advancedNotificationService->AddSlots(slots); + + // create request + std::string label = "testLabel"; + sptr req = new NotificationRequest(0); + req->SetLabel(label); + req->SetStatusBarText("text"); + req->SetSlotType(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); + + 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_EQ(g_advancedNotificationService->SetDoNotDisturbDate(date), ERR_OK); + + EXPECT_EQ(g_advancedNotificationService->Publish(label, req), ERR_OK); + EXPECT_EQ(g_advancedNotificationService->Unsubscribe(subscriber->GetImpl(), nullptr), ERR_OK); + EXPECT_TRUE(passed); +} } // namespace Notification } // namespace OHOS diff --git a/services/test/moduletest/mock/permission_kit.cpp b/services/test/moduletest/mock/permission_kit.cpp new file mode 100644 index 0000000..36855b9 --- /dev/null +++ b/services/test/moduletest/mock/permission_kit.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "permission/permission_kit.h" + +namespace OHOS { +namespace Security { +namespace Permission { +using namespace std; + +int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) +{ + return TypePermissionState::PERMISSION_GRANTED; +} + +bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) +{ + return 0; +} + +int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) +{ + return 0; +} + +int PermissionKit::AddUserGrantedReqPermissions( + const string &bundleName, const std::vector &permList, int userId) +{ + return 0; +} + +int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) +{ + return 0; +} + +int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::AddDefPermissions(const std::vector &permList) +{ + return 0; +} + +int PermissionKit::RemoveDefPermissions(const string &bundleName) +{ + return 0; +} + +int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) +{ + return 0; +} +} // namespace Permission +} // namespace Security +} // namespace OHOS \ No newline at end of file diff --git a/test/resource/notificationfuzztest/include/notificationgetparam.h b/test/resource/notificationfuzztest/include/notificationgetparam.h index 4fdcba8..2216a49 100644 --- a/test/resource/notificationfuzztest/include/notificationgetparam.h +++ b/test/resource/notificationfuzztest/include/notificationgetparam.h @@ -188,7 +188,6 @@ sptr GetParamNotificationSortingMapS OHOS::Notification::NotificationSlot::NotificationLevel GetParamNotificationLevel(); std::shared_ptr GetParamNotificationSubscriber(); std::shared_ptr GetParamNotificationSubscribeInfo(); -OHOS::Notification::NotificationConstant::DisturbMode GetParamDisturbMode(); std::shared_ptr GetParamWantAgentInfo(); OHOS::Notification::WantAgent::WantAgentConstant::OperationType GetParamOperationType(); @@ -223,6 +222,8 @@ OHOS::Notification::NotificationConstant::SubscribeResult GetParamSubscribeResul OHOS::AppExecFwk::MissionInformation GetParamMissionInformation(); std::shared_ptr GetParamAbilityLifecycleCallbacks(); std::shared_ptr GetParamIAbilityManager(); +std::shared_ptr GetParamNotificationDoNotDisturbDate(); +OHOS::Notification::NotificationConstant::DoNotDisturbType GetParamDoNotDisturbType(); class TestRemoteObject : public IRemoteObject { public: TestRemoteObject(); @@ -380,7 +381,7 @@ public: {} 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 {} diff --git a/test/resource/notificationfuzztest/notificationfuzzconfig/config.json b/test/resource/notificationfuzztest/notificationfuzzconfig/config.json index ec41e63..a7fc3f8 100644 --- a/test/resource/notificationfuzztest/notificationfuzzconfig/config.json +++ b/test/resource/notificationfuzztest/notificationfuzzconfig/config.json @@ -83,8 +83,8 @@ "SetShowBadgeEnabledForBundle": [], "GetShowBadgeEnabledForBundle": [], "GetShowBadgeEnabled": [], - "SetDisturbMode": [], - "GetDisturbMode": [] + "SetDoNotDisturbDate": [], + "GetDoNotDisturbDate": [] }, "WantAgentHelper": { "GetWantAgentOHOSAppExecFwkContextWantAgentInfo": [], diff --git a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp index cef442c..edb736b 100644 --- a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp +++ b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp @@ -364,12 +364,12 @@ void NotificationFuzzTestManager::RegisterNotificationHelper() OHOS::Notification::NotificationHelper::GetShowBadgeEnabled(param); }); - callFunctionMap_.emplace("NotificationHelperSetDisturbMode", - []() { OHOS::Notification::NotificationHelper::SetDisturbMode(GetParamDisturbMode()); }); + callFunctionMap_.emplace("NotificationHelperSetDoNotDisturbDate", + []() { OHOS::Notification::NotificationHelper::SetDoNotDisturbDate(*GetParamNotificationDoNotDisturbDate()); }); - callFunctionMap_.emplace("NotificationHelperGetDisturbMode", []() { - OHOS::Notification::NotificationConstant::DisturbMode param = GetParamDisturbMode(); - OHOS::Notification::NotificationHelper::GetDisturbMode(param); + callFunctionMap_.emplace("NotificationHelperGetDoNotDisturbDate", []() { + OHOS::Notification::NotificationDoNotDisturbDate doNotDisturbDate; + OHOS::Notification::NotificationHelper::GetDoNotDisturbDate(doNotDisturbDate); }); } @@ -506,8 +506,7 @@ void NotificationFuzzTestManager::RegisterNotificationSubscriber() callFunctionMap_.emplace("NotificationSubscriberOnDisturbModeChanged", []() { std::shared_ptr temp = GetParamNotificationSubscriber(); - int disturbMode = GetIntParam(); - temp->OnDisturbModeChanged(disturbMode); + temp->OnDoNotDisturbDateChange(GetParamNotificationDoNotDisturbDate()); }); } diff --git a/test/resource/notificationfuzztest/src/notificationgetparam.cpp b/test/resource/notificationfuzztest/src/notificationgetparam.cpp index 48badd2..0ff93b7 100644 --- a/test/resource/notificationfuzztest/src/notificationgetparam.cpp +++ b/test/resource/notificationfuzztest/src/notificationgetparam.cpp @@ -1091,29 +1091,6 @@ std::shared_ptr GetParamNotificat return std::make_shared(); } -OHOS::Notification::NotificationConstant::DisturbMode GetParamDisturbMode() -{ - switch (GetIntParam() % INDEX_FIVE) { - case INDEX_ZERO: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS; - break; - case INDEX_ONE: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALL; - break; - case INDEX_TWO: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_NONE; - break; - case INDEX_THREE: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_PRIORITY; - break; - case INDEX_FOUR: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_UNKNOWN; - break; - default: - return OHOS::Notification::NotificationConstant::DisturbMode::ALLOW_ALARMS; - break; - } -} std::shared_ptr GetParamWantAgentInfo() { switch (GetIntParam() % INDEX_THREE) { @@ -1445,5 +1422,36 @@ std::shared_ptr GetParamIAbilityManager() DelayedSingleton::GetInstance(); return param; } + +std::shared_ptr GetParamNotificationDoNotDisturbDate() +{ + if (GetBoolParam()) { + return std::make_shared(); + } else { + return std::make_shared( + GetParamDoNotDisturbType(), GetS64Param(), GetS64Param()); + } +} + +OHOS::Notification::NotificationConstant::DoNotDisturbType GetParamDoNotDisturbType() +{ + switch (GetIntParam() % INDEX_FOUR) { + case INDEX_ZERO: + return OHOS::Notification::NotificationConstant::DoNotDisturbType::NONE; + break; + case INDEX_ONE: + return OHOS::Notification::NotificationConstant::DoNotDisturbType::ONCE; + break; + case INDEX_TWO: + return OHOS::Notification::NotificationConstant::DoNotDisturbType::DAILY; + break; + case INDEX_THREE: + return OHOS::Notification::NotificationConstant::DoNotDisturbType::CLEARLY; + break; + default: + return OHOS::Notification::NotificationConstant::DoNotDisturbType::NONE; + break; + } +} } // namespace Notification } // namespace OHOS \ No newline at end of file -- Gitee From c64020eddffb613c597abed590a93efe6b7aee6f Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 22 Nov 2021 23:54:32 +0800 Subject: [PATCH 019/131] Fix codex Signed-off-by: zhaoyuan17 --- .../test/moduletest/ans_fw_module_test.cpp | 15 ++++++- .../ans/test/moduletest/ans_mt_constant.h | 39 ------------------- 2 files changed, 14 insertions(+), 40 deletions(-) delete mode 100644 frameworks/ans/test/moduletest/ans_mt_constant.h diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index b4e5d98..c89d452 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -26,7 +26,6 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.h" -#include "ans_mt_constant.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" #include "notification_content.h" @@ -40,6 +39,20 @@ 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 = "_"; + +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, diff --git a/frameworks/ans/test/moduletest/ans_mt_constant.h b/frameworks/ans/test/moduletest/ans_mt_constant.h deleted file mode 100644 index 855cf4d..0000000 --- a/frameworks/ans/test/moduletest/ans_mt_constant.h +++ /dev/null @@ -1,39 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H -#define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_TEST_MODULETEST_ANS_MT_CONSTANT_H - -#include - -namespace OHOS { -namespace Notification { -namespace { -const std::string APP_NAME = "bundleName"; -const std::string NOTIFICATION_LABEL_0 = "Label0"; -const std::string NOTIFICATION_LABEL_1 = "Label1"; -const std::string NOTIFICATION_LABEL_2 = "Label2"; -const std::string AN_NOT_EXIST_KEY = "AN_NOT_EXIST_KEY"; -const std::string KEY_SPLITER = "_"; - -constexpr int UID = 1; -constexpr int CANCEL_REASON_DELETE = 2; -constexpr int APP_CANCEL_REASON_DELETE = 8; -constexpr int APP_CANCEL_ALL_REASON_DELETE = 9; -} // namespace -} // namespace Notification -} // namespace OHOS - -#endif -- Gitee From f65a4e6f4ee24658d8206702fe0166c8977b5bb1 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 22 Nov 2021 16:42:52 +0000 Subject: [PATCH 020/131] Modify test bug Signed-off-by: zhaoyuan17 --- frameworks/wantagent/src/want_agent_helper.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/frameworks/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index 5b3c49c..fcb6d27 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -152,6 +152,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) { -- Gitee From 9ff1158d3ece28697a20c9537005e3f4fc38e544 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 24 Nov 2021 11:58:47 +0000 Subject: [PATCH 021/131] Add pixelmapInit Signed-off-by: zhaoyuan17 --- .../ans/core/include/ans_notification.h | 16 +- frameworks/ans/core/src/ans_manager_stub.cpp | 2 - frameworks/ans/core/src/ans_notification.cpp | 127 ++++++----- .../test/moduletest/ans_fw_module_test.cpp | 206 +++++++++--------- interfaces/kits/napi/ans/src/init.cpp | 3 + 5 files changed, 199 insertions(+), 155 deletions(-) diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index 066b03b..4c26613 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -643,6 +643,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 * @@ -655,7 +670,6 @@ private: sptr ansManagerProxy_; sptr recipient_; }; - } // 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 8928488..2e8da5e 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -1190,7 +1190,6 @@ ErrCode AnsManagerStub::HandleCancelGroup(MessageParcel &data, MessageParcel &re ANS_LOGW("[HandleCancelGroup] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } - return ERR_OK; } @@ -1214,7 +1213,6 @@ ErrCode AnsManagerStub::HandleRemoveGroupByBundle(MessageParcel &data, MessagePa ANS_LOGW("[HandleRemoveGroupByBundle] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; } - return ERR_OK; } diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index ec677c7..fb2a0e2 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -907,61 +907,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(); @@ -969,10 +1000,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; } } @@ -982,10 +1012,9 @@ 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; } } diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index c89d452..b9db098 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -352,7 +352,7 @@ public: ~EventParser() {} - void parse(std::list> events) + void Parse(std::list> events) { for (auto event : events) { if (event->GetType() == SubscriberEventType::ON_SUBSCRIBERESULT) { @@ -384,87 +384,87 @@ public: } } - 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; } - bool getWaitOnSubscriber() + bool GetWaitOnSubscriber() const { return waitOnSubscriber_; } - bool 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() { return onCanceledWithSortingMapDelRea_; } @@ -545,7 +545,7 @@ 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); @@ -555,21 +555,21 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L stream << UID << KEY_SPLITER << notificationLabel << KEY_SPLITER << notificationIdInt; std::string notificationKey = stream.str(); NotificationSorting sorting; - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetLabel().c_str(), notificationLabel); - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetId(), notificationIdInt); - EXPECT_EQ(eventParser.getOnConsumedReq()[i]->GetKey(), notificationKey); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetLabel().c_str(), notificationLabel); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetId(), notificationIdInt); - EXPECT_EQ(eventParser.getOnConsumedWithSortingMapReq()[i]->GetKey(), notificationKey); + EXPECT_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_TRUE(eventParser.getWaitOnSubscriber()); - EXPECT_TRUE(eventParser.getWaitOnUnSubscriber()); + 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(); } @@ -601,21 +601,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; 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(); } @@ -646,19 +646,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(); } @@ -685,9 +685,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); @@ -695,8 +695,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; @@ -706,9 +706,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(); } @@ -730,11 +730,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(); } @@ -874,21 +874,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; 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(); } @@ -919,19 +919,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(); } @@ -969,33 +969,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; 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; 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(); @@ -1036,11 +1036,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(); } @@ -1079,11 +1079,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(); } diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index e72edda..358865a 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -20,6 +20,7 @@ #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" @@ -82,6 +83,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; } -- Gitee From 3cb7789de525890d409129ff28b06f208e8bd4fc Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 24 Nov 2021 16:25:02 +0000 Subject: [PATCH 022/131] Add permission check Signed-off-by: zhaoyuan17 --- .../common/include/ans_permission_define.h | 28 -- frameworks/ans/test/moduletest/BUILD.gn | 8 - .../test/moduletest/mock/permission_kit.cpp | 90 ---- services/ans/BUILD.gn | 1 - .../ans/src/advanced_notification_service.cpp | 67 ++- services/ans/test/unittest/BUILD.gn | 2 - .../ans/test/unittest/mock/permission_kit.cpp | 90 ---- services/test/moduletest/BUILD.gn | 2 - .../test/moduletest/mock/permission_kit.cpp | 90 ---- .../include/notificationfuzzconfigparser.h | 6 +- .../include/notificationfuzztestmanager.h | 49 +- .../include/notificationgetparam.h | 186 +------ .../src/notificationfuzztestmanager.cpp | 73 ++- .../src/notificationgetparam.cpp | 461 ++---------------- 14 files changed, 149 insertions(+), 1004 deletions(-) delete mode 100644 frameworks/ans/core/common/include/ans_permission_define.h delete mode 100644 frameworks/ans/test/moduletest/mock/permission_kit.cpp delete mode 100644 services/ans/test/unittest/mock/permission_kit.cpp delete mode 100644 services/test/moduletest/mock/permission_kit.cpp diff --git a/frameworks/ans/core/common/include/ans_permission_define.h b/frameworks/ans/core/common/include/ans_permission_define.h deleted file mode 100644 index 058c75d..0000000 --- a/frameworks/ans/core/common/include/ans_permission_define.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#ifndef BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H -#define BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H - -#include - -namespace OHOS { -namespace Notification { -// Permission -const std::string ANS_PERMISSION_CONTROLLER = "ohos.permission.NOTIFICATION_CONTROLLER"; -} // namespace Notification -} // namespace OHOS - -#endif // BASE_NOTIFICATION_ANS_STANDARD_INNERKITS_BASE_INCLUDE_ANS_PERMISSION_DEFINE_H diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index 85cc90d..f2edf40 100755 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -82,7 +82,6 @@ ohos_moduletest("ans_fw_module_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -113,7 +112,6 @@ ohos_moduletest("ans_fw_module_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -165,7 +163,6 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -196,7 +193,6 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -247,7 +243,6 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -276,7 +271,6 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] @@ -327,7 +321,6 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "mock/mock_bundle_mgr_proxy.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -356,7 +349,6 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] diff --git a/frameworks/ans/test/moduletest/mock/permission_kit.cpp b/frameworks/ans/test/moduletest/mock/permission_kit.cpp deleted file mode 100644 index 36855b9..0000000 --- a/frameworks/ans/test/moduletest/mock/permission_kit.cpp +++ /dev/null @@ -1,90 +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 "permission/permission_kit.h" - -namespace OHOS { -namespace Security { -namespace Permission { -using namespace std; - -int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) -{ - return TypePermissionState::PERMISSION_GRANTED; -} - -bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::AddUserGrantedReqPermissions( - const string &bundleName, const std::vector &permList, int userId) -{ - return 0; -} - -int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) -{ - return 0; -} - -int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::AddDefPermissions(const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveDefPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) -{ - return 0; -} -} // namespace Permission -} // namespace Security -} // namespace OHOS \ No newline at end of file diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 249f437..1f8e18f 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -56,7 +56,6 @@ ohos_shared_library("libans") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", - "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index cde4d34..538f26b 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -22,7 +22,6 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" -#include "ans_permission_define.h" #include "bundle_manager_helper.h" #include "ipc_skeleton.h" #include "notification_constant.h" @@ -31,7 +30,6 @@ #include "notification_slot.h" #include "notification_slot_filter.h" #include "notification_subscriber_manager.h" -#include "permission/permission_kit.h" #include "permission_filter.h" namespace OHOS { @@ -828,6 +826,10 @@ 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; @@ -853,6 +855,10 @@ 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; @@ -1012,6 +1018,10 @@ ErrCode AdvancedNotificationService::Subscribe( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + return NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info); } @@ -1024,6 +1034,10 @@ ErrCode AdvancedNotificationService::Unsubscribe( return ERR_ANS_INVALID_PARAM; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + if (!IsSystemApp()) { ANS_LOGE("Client is not a system app"); return ERR_ANS_NON_SYSTEM_APP; @@ -1079,6 +1093,10 @@ ErrCode AdvancedNotificationService::GetAllActiveNotifications(std::vectorPostSyncTask(std::bind([&]() { notifications.clear(); @@ -1154,6 +1172,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; @@ -1513,6 +1535,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; @@ -1557,6 +1583,10 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1792,12 +1822,21 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptrGetBeginDate()); int64_t endDate = ResetSeconds(date->GetEndDate()); - if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::NONE) { - beginDate = 0; - endDate = 0; - } - if (date->GetDoNotDisturbType() == NotificationConstant::DoNotDisturbType::ONCE) { - AdjustDateForDndTypeOnce(beginDate, endDate); + 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( @@ -1857,18 +1896,12 @@ ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSuppo bool AdvancedNotificationService::CheckPermission(const std::string &bundleName) { ANS_LOGD("%{public}s", __FUNCTION__); - bool isGranted = false; if (bundleName.empty()) { ANS_LOGE("Bundle name is empty."); - return isGranted; - } - int result = Security::Permission::PermissionKit::VerifyPermission(bundleName, ANS_PERMISSION_CONTROLLER, 0); - if (Security::Permission::TypePermissionState::PERMISSION_GRANTED == result) { - isGranted = true; - } else { - ANS_LOGE("Permission granted failed."); + return false; } - return isGranted; + // Add permission check in future + return true; } } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index d131b5f..b404f89 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -58,7 +58,6 @@ ohos_unittest("ans_unit_test") { "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", "notification_preferences_database_test.cpp", "notification_preferences_test.cpp", "notification_slot_filter_test.cpp", @@ -86,7 +85,6 @@ ohos_unittest("ans_unit_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] diff --git a/services/ans/test/unittest/mock/permission_kit.cpp b/services/ans/test/unittest/mock/permission_kit.cpp deleted file mode 100644 index 36855b9..0000000 --- a/services/ans/test/unittest/mock/permission_kit.cpp +++ /dev/null @@ -1,90 +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 "permission/permission_kit.h" - -namespace OHOS { -namespace Security { -namespace Permission { -using namespace std; - -int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) -{ - return TypePermissionState::PERMISSION_GRANTED; -} - -bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::AddUserGrantedReqPermissions( - const string &bundleName, const std::vector &permList, int userId) -{ - return 0; -} - -int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) -{ - return 0; -} - -int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::AddDefPermissions(const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveDefPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) -{ - return 0; -} -} // namespace Permission -} // namespace Security -} // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 02ebb5b..0440b8b 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -57,7 +57,6 @@ ohos_moduletest("ans_module_test") { "mock/mock_event_handler.cpp", "mock/mock_ipc.cpp", "mock/mock_single_kv_store.cpp", - "mock/permission_kit.cpp", ] configs = [ "//utils/native/base:utils_config" ] @@ -86,7 +85,6 @@ ohos_moduletest("ans_module_test") { "ces_standard:cesfwk_innerkits", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", - "permission_standard:libpermissionsdk_standard", "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] diff --git a/services/test/moduletest/mock/permission_kit.cpp b/services/test/moduletest/mock/permission_kit.cpp deleted file mode 100644 index 36855b9..0000000 --- a/services/test/moduletest/mock/permission_kit.cpp +++ /dev/null @@ -1,90 +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 "permission/permission_kit.h" - -namespace OHOS { -namespace Security { -namespace Permission { -using namespace std; - -int PermissionKit::VerifyPermission(const string &bundleName, const string &permissionName, int userId) -{ - return TypePermissionState::PERMISSION_GRANTED; -} - -bool PermissionKit::CanRequestPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::GrantSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::RevokeUserGrantedPermission(const string &bundleName, const string &permissionName, int userId) -{ - return 0; -} - -int PermissionKit::RevokeSystemGrantedPermission(const string &bundleName, const string &permissionName) -{ - return 0; -} - -int PermissionKit::AddUserGrantedReqPermissions( - const string &bundleName, const std::vector &permList, int userId) -{ - return 0; -} - -int PermissionKit::AddSystemGrantedReqPermissions(const string &bundleName, const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveUserGrantedReqPermissions(const string &bundleName, int userId) -{ - return 0; -} - -int PermissionKit::RemoveSystemGrantedReqPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::AddDefPermissions(const std::vector &permList) -{ - return 0; -} - -int PermissionKit::RemoveDefPermissions(const string &bundleName) -{ - return 0; -} - -int PermissionKit::GetDefPermission(const string &permissionName, PermissionDef &permissionDefResult) -{ - return 0; -} -} // namespace Permission -} // namespace Security -} // namespace OHOS \ No newline at end of file diff --git a/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h index d6d96c2..d0a492b 100644 --- a/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h +++ b/test/resource/notificationfuzztest/include/notificationfuzzconfigparser.h @@ -15,8 +15,8 @@ #ifndef NOTIFICATION_FUZZ_CONFIG_PARSER_H #define NOTIFICATION_FUZZ_CONFIG_PARSER_H -#include #include +#include #include #include @@ -31,9 +31,9 @@ struct FuzzTestData { std::vector methodVec {}; }; -class FuzzConfigParser { +class NotificationFuzzConfigParser { public: - void ParseFromFile4FuzzTest(const std::string &path, FuzzTestData &ftd) + void ParseFromFile4FuzzTest(const std::string &path, FuzzTestData &ftd) const { std::cout << __func__ << std::endl; if (path.empty()) { diff --git a/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h index c17922a..cce8989 100644 --- a/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h +++ b/test/resource/notificationfuzztest/include/notificationfuzztestmanager.h @@ -28,11 +28,11 @@ public: {} static Ptr GetInstance() { - if (instance_ == nullptr) { - auto pObj = new NotificationFuzzTestManager(); - instance_ = std::shared_ptr(pObj); + if (instance == nullptr) { + NotificationFuzzTestManager* pObj = new NotificationFuzzTestManager(); + instance = std::shared_ptr(pObj); } - return instance_; + return instance; } void StartFuzzTest(); @@ -41,47 +41,16 @@ private: void SetJsonFunction(std::string functionName); void SetCycle(uint16_t cycle); NotificationFuzzTestManager(); - NotificationFuzzTestManager(NotificationFuzzTestManager &) = delete; + NotificationFuzzTestManager(const NotificationFuzzTestManager &) = delete; NotificationFuzzTestManager &operator=(const NotificationFuzzTestManager &) = delete; - static Ptr instance_; - uint16_t cycle_; + static Ptr instance; + uint16_t cycle_ = 0; std::unordered_map remainderMap_ {}; std::unordered_map> callFunctionMap_ {}; const int COLOR_R = 100; const int COLOR_G = 100; const int COLOR_B = 100; - - void RegisterAsyncCommonEventResult(); - void RegisterCommonEventData(); - void RegisterCommonEventManager(); - void RegisterCommonEventPublishInfo(); - void RegisterCommonEventSubscribeInfo(); - void RegisterCommonEventSubscriber(); - void RegisterCommonEventSupport(); - void RegisterMatchingSkills(); - void RegisterDumper(); - void RegisterEventHandler(); - void RegisterEventQueue(); - void RegisterEventRunner(); - void RegisterFileDescriptorListener(); - void RegisterInnerEvent(); - void RegisterEventRunnerNativeImplement(); - void RegisterAbilityManager(); - void RegisterWantParams(); - void RegisterWant(); - void RegisterElementName(); - void RegisterBundleMgrProxy(); - - void RegisterOHOSApplication(); - void RegisterAbility(); - void RegisterDataAbilityHelper(); - void RegisterDataUriUtils(); - void RegisterLifeCycle(); - - void RegisterAbilityContext(); - void RegisterProcessInfo(); - void RegisterNotificationHelper(); void RegisterNotificationSorting(); void RegisterNotificationSortingMap(); @@ -93,8 +62,8 @@ private: void RegisterIAbilityContinuation(); void RegisterRevocable(); void RegisterTaskDispatcher(); - void RegisterAbility_(); - void RegisterAbilityContext_(); + void RegisterAbility(); + void RegisterAbilityContext(); void RegisterContext(); void RegisterAbilityLifecycleCallbacks(); void RegisterIAbilityManager(); diff --git a/test/resource/notificationfuzztest/include/notificationgetparam.h b/test/resource/notificationfuzztest/include/notificationgetparam.h index 2216a49..b18017d 100644 --- a/test/resource/notificationfuzztest/include/notificationgetparam.h +++ b/test/resource/notificationfuzztest/include/notificationgetparam.h @@ -14,54 +14,40 @@ */ #ifndef NOTIFICATION_GET_PARAM_H #define NOTIFICATION_GET_PARAM_H +#include #include +#include +#include + #include "ability.h" #include "ability_handler.h" #include "ability_manager.h" #include "ability_manager_interface.h" -#include "async_common_event_result.h" -#include "bundle_info.h" -#include "common_event_manager.h" -#include "common_event_data.h" -#include "common_event_publish_info.h" -#include "common_event_subscribe_info.h" -#include "common_event_subscriber.h" -#include "common_event_support.h" +#include "ability_manager_service.h" +#include "base_task_dispatcher.h" #include "data_uri_utils.h" #include "element_name.h" -#include "event_handler.h" #include "event_runner.h" -#include "inner_event.h" -#include "key_event.h" -#include "logger.h" -#include "matching_skills.h" -#include "module_info.h" -#include "native_implement_eventhandler.h" -#include "pac_map.h" -#include "parcel.h" -#include "patterns_matcher.h" +#include "launcher_ability_info.h" +#include "launcher_service.h" +#include "spec_task_dispatcher.h" +#include "task_dispatcher.h" +#include "task_dispatcher_context.h" #include "uri.h" #include "want.h" -#include "bundle_mgr_proxy.h" -#include "notification_sorting_map.h" -#include "notification_helper.h" -#include "want_agent_helper.h" -#include "notification.h" + #ifdef PRINT_LOG #undef PRINT_LOG #endif -#include "launcher_service.h" -#include "launcher_ability_info.h" -#include "task_dispatcher.h" -#include "base_task_dispatcher.h" -#include "spec_task_dispatcher.h" -#include "task_dispatcher_context.h" -#include "ability_manager_service.h" + +#include "notification.h" +#include "notification_helper.h" +#include "notification_sorting_map.h" +#include "want_agent_helper.h" using Want = OHOS::AAFwk::Want; namespace OHOS { namespace Notification { -class TestDumper; bool GetBoolParam(); uint8_t GetU8Param(); unsigned int GetUIntParam(); @@ -97,79 +83,16 @@ std::vector GetS8VectorParam(); std::vector GetS16VectorParam(); std::vector GetS32VectorParam(); std::vector GetS64VectorParam(); - -std::shared_ptr GetParamParcel(); std::shared_ptr GetParamWant(); -std::vector> GetParamWantVector(); -OHOS::AAFwk::Operation GetParamOperation(); -std::shared_ptr GetParamAsyncCommonEventResult(); -std::shared_ptr GetParamCommonEventData(); -std::shared_ptr GetParamCommonEventManager(); -std::shared_ptr GetParamCommonEventPublishInfo(); -std::shared_ptr GetParamCommonEventSubscribeInfo(); -std::shared_ptr GetParamCommonEventSubscriber(); -std::shared_ptr GetParamCommonEventSupport(); -std::shared_ptr GetParamMatchingSkills(); sptr GetParamSptrRemote(); std::shared_ptr GetParamEventRunner(); -std::shared_ptr GetParamEventHandler(); -std::shared_ptr GetParamEventQueue(); -std::shared_ptr GetParamEventRunnerNativeImplement(); -std::shared_ptr GetParamFileDescriptorListener(); -std::shared_ptr GetParamLogger(); -OHOS::AppExecFwk::EventQueue::Priority GetParamPriority(); -TestDumper GetParamDumper(); -OHOS::AppExecFwk::InnerEvent::Pointer GetParamInnerEvent(); -OHOS::AppExecFwk::InnerEvent::Callback GetParamCallback(); -OHOS::AppExecFwk::InnerEvent::TimePoint GetParamTimePoint(); -OHOS::EventFwk::CommonEventSubscribeInfo::ThreadMode GetParamThreadMode(); - -std::shared_ptr GetParamAbilityContext(); -std::shared_ptr GetParamIAbilityEvent(); -sptr GetParamAbilityThread(); -std::shared_ptr GetParamAbilityHandler(); -std::shared_ptr GetParamAbilityStartSetting(); std::shared_ptr GetParamAbility(); -std::shared_ptr GetParamOHOSApplication(); -std::shared_ptr GetParamKeyEvent(); -OHOS::Uri GetParamUri(); - -NativeRdb::ValuesBucket GetParamValuesBucket(); -OHOS::AppExecFwk::Configuration GetParamConfiguration(); -NativeRdb::DataAbilityPredicates GetParamDataAbilityPredicates(); -OHOS::AppExecFwk::PacMap GetParamPacMap(); -std::shared_ptr GetParamComponentContainer(); -sptr GetParamIAbilityConnection(); - -std::shared_ptr GetParamProcessInfo(); -std::shared_ptr GetParamDataUriUtils(); -std::shared_ptr GetParamDataAbilityHelper(); -std::shared_ptr GetParamLifeCycle(); -OHOS::AppExecFwk::LifeCycle::Event GetParamLifeCycleEvent(); -std::shared_ptr GetParamElementName(); std::shared_ptr GetParamWantParams(); -std::shared_ptr GetParamAbilityManager(); -OHOS::AAFwk::PatternsMatcher GetParamPatternsMatcher(); -OHOS::AAFwk::MatchType GetParamMatchType(); std::shared_ptr GetParamContext(); - -std::shared_ptr GetParamBundleMgrProxy(); OHOS::AppExecFwk::ApplicationFlag GetParamApplicationFlag(); OHOS::AppExecFwk::ApplicationInfo GetParamApplicationInfo(); -std::vector GetParamApplicationInfoVector(); -OHOS::AppExecFwk::BundleFlag GetParamBundleFlag(); -OHOS::AppExecFwk::BundleInfo GetParamBundleInfo(); OHOS::AppExecFwk::AbilityInfo GetParamAbilityInfo(); -std::vector GetParamBundleInfoVector(); -OHOS::AppExecFwk::HapModuleInfo GetParamHapModuleInfo(); -OHOS::AppExecFwk::PermissionDef GetParamPermissionDef(); -std::vector GetParamPermissionDefVector(); -OHOS::AppExecFwk::IBundleMgr::Message GetParamIBundleMgrMessage(); -OHOS::MessageParcel GetParamMessageParcel(); -OHOS::AppExecFwk::DumpFlag GetParamDumpFlag(); -sptr GetParamICleanCacheCallback(); sptr GetParamIBundleStatusCallback(); - std::shared_ptr GetParamNotificationSorting(); std::vector GetParamNotificationSortingVector(); std::shared_ptr GetParamNotificationSortingMap(); @@ -281,74 +204,7 @@ public: } }; -class TestCommonEventSubscriber : public OHOS::EventFwk::CommonEventSubscriber { -public: - TestCommonEventSubscriber() - {} - ~TestCommonEventSubscriber() - {} - virtual void OnReceiveEvent(const OHOS::EventFwk::CommonEventData &data) - { - printf("Fuzz Test Reveive Event\n"); - } -}; - -class TestDumper : public OHOS::AppExecFwk::Dumper { -public: - void Dump(const std::string &message) - { - return; - } - std::string GetTag() - { - return GetStringParam(); - } -}; - -class TestFileDescriptorListener : public OHOS::AppExecFwk::FileDescriptorListener { -public: - TestFileDescriptorListener() - {} - ~TestFileDescriptorListener() - {} -}; -class TestIAbilityConnection : public OHOS::AAFwk::IAbilityConnection { -public: - void OnAbilityConnectDone( - const OHOS::AppExecFwk::ElementName &element, const sptr &remoteObject, int resultCode) override - {} - void OnAbilityDisconnectDone(const OHOS::AppExecFwk::ElementName &element, int resultCode) override - {} - virtual ~TestIAbilityConnection() - {} -}; - -class TestAbilityEvent : public OHOS::AppExecFwk::IAbilityEvent { -public: - virtual void OnBackPressed() - { - printf("Fuzz Test Back Pressed."); - } -}; - -class TestLogger : public OHOS::AppExecFwk::Logger { -public: - void Log(const std::string &line) - {} - virtual ~TestLogger() - {} -}; - -class TestICleanCacheCallback : public OHOS::AppExecFwk::ICleanCacheCallback { -public: - TestICleanCacheCallback() - {} - void OnCleanCacheFinished(bool succeeded) override - {} - virtual ~TestICleanCacheCallback() - {} -}; class TestIBundleStatusCallback : public OHOS::AppExecFwk::IBundleStatusCallback { public: @@ -370,12 +226,12 @@ public: void OnConnected() override { std::cout << "TestAnsSubscriber OnConnected" << std::endl; - mutex_.unlock(); + mutex.unlock(); } void OnDisconnected() override { std::cout << "TestAnsSubscriber OnDisconnected" << std::endl; - mutex_.unlock(); + mutex.unlock(); } void OnDied() override {} @@ -394,8 +250,8 @@ public: const std::shared_ptr &sortingMap) override {} -private: - static std::mutex mutex_; +public: + static std::mutex mutex; }; class TestCompletedCallback : public OHOS::Notification::WantAgent::CompletedCallback { diff --git a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp index edb736b..b2c7ef2 100644 --- a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp +++ b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp @@ -12,21 +12,17 @@ * See the License for the specific language governing permissions and * limitations under the License. */ -#define private public -#define protected public #include "datetime_ex.h" #include "../include/notificationfuzzconfigparser.h" #include "../include/notificationfuzztestmanager.h" #include "../include/notificationgetparam.h" -#undef private -#undef protected using namespace OHOS::AppExecFwk; using namespace OHOS::EventFwk; namespace OHOS { namespace Notification { -std::shared_ptr NotificationFuzzTestManager::instance_ = nullptr; +std::shared_ptr NotificationFuzzTestManager::instance = nullptr; // RegisterNotificationHelper void NotificationFuzzTestManager::RegisterNotificationHelper() { @@ -163,37 +159,37 @@ void NotificationFuzzTestManager::RegisterNotificationHelper() }); callFunctionMap_.emplace("NotificationHelperSubscribeNotificationNotificationSubscriber", []() { - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.lock(); std::shared_ptr subscriber = GetParamNotificationSubscriber(); struct tm start = {0}; OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber); struct tm end = {0}; int64_t timeout = 0; - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.unlock(); + TestAnsSubscriber::mutex.lock(); OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber); - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex.unlock(); }); callFunctionMap_.emplace( "NotificationHelperSubscribeNotificationNotificationSubscriberNotificationSubscribeInfo", []() { - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.lock(); std::shared_ptr subscriber = GetParamNotificationSubscriber(); std::shared_ptr subscribeInfo = GetParamNotificationSubscribeInfo(); @@ -202,59 +198,59 @@ void NotificationFuzzTestManager::RegisterNotificationHelper() OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber, *subscribeInfo); struct tm end = {0}; int64_t timeout = 0; - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.unlock(); + TestAnsSubscriber::mutex.lock(); OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber, *subscribeInfo); - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex.unlock(); }); callFunctionMap_.emplace("NotificationHelperUnSubscribeNotificationNotificationSubscriber", []() { - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.lock(); std::shared_ptr subscriber = GetParamNotificationSubscriber(); struct tm start = {0}; OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber); struct tm end = {0}; int64_t timeout = 0; - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.unlock(); + TestAnsSubscriber::mutex.lock(); OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber); - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex.unlock(); }); callFunctionMap_.emplace( "NotificationHelperUnSubscribeNotificationNotificationSubscriberNotificationSubscribeInfo", []() { - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.lock(); std::shared_ptr subscriber = GetParamNotificationSubscriber(); std::shared_ptr subscribeInfo = GetParamNotificationSubscribeInfo(); @@ -263,25 +259,25 @@ void NotificationFuzzTestManager::RegisterNotificationHelper() OHOS::Notification::NotificationHelper::SubscribeNotification(*subscriber, *subscribeInfo); struct tm end = {0}; int64_t timeout = 0; - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); - TestAnsSubscriber::mutex_.lock(); + TestAnsSubscriber::mutex.unlock(); + TestAnsSubscriber::mutex.lock(); OHOS::GetSystemCurrentTime(&start); OHOS::Notification::NotificationHelper::UnSubscribeNotification(*subscriber, *subscribeInfo); - while (!TestAnsSubscriber::mutex_.try_lock()) { + while (!TestAnsSubscriber::mutex.try_lock()) { OHOS::GetSystemCurrentTime(&end); timeout = OHOS::GetSecondsBetween(start, end); if (timeout >= 5L) { break; } } - TestAnsSubscriber::mutex_.unlock(); + TestAnsSubscriber::mutex.unlock(); }); callFunctionMap_.emplace("NotificationHelperRemoveNotificationstring", @@ -666,8 +662,8 @@ void NotificationFuzzTestManager::RegisterIAbilityContinuation() }); } -// RegisterAbility_ -void NotificationFuzzTestManager::RegisterAbility_() +// RegisterAbility +void NotificationFuzzTestManager::RegisterAbility() { callFunctionMap_.emplace("AbilityOnRequestPermissionsFromUserResult", []() { std::shared_ptr temp = GetParamAbility(); @@ -684,8 +680,8 @@ void NotificationFuzzTestManager::RegisterAbility_() }); } -// RegisterAbilityContext_ -void NotificationFuzzTestManager::RegisterAbilityContext_() +// RegisterAbilityContext +void NotificationFuzzTestManager::RegisterAbilityContext() { callFunctionMap_.emplace("AbilityStartAbility", []() { std::shared_ptr temp = GetParamAbility(); @@ -841,8 +837,8 @@ NotificationFuzzTestManager::NotificationFuzzTestManager() RegisterWantAgentHelper(); RegisterLauncherService(); RegisterIAbilityContinuation(); - RegisterAbility_(); - RegisterAbilityContext_(); + RegisterAbility(); + RegisterAbilityContext(); RegisterContext(); RegisterAbilityLifecycleCallbacks(); RegisterIAbilityManager(); @@ -866,15 +862,10 @@ int GetRandomInt(int minNum, int maxNum) return GetU16Param() % (maxNum - minNum + 1) + minNum; } -void action(int a) -{ - std::cout << "Interrupt signal (" << a << ") received.\n"; -} - void NotificationFuzzTestManager::StartFuzzTest() { std::cout << __func__ << std::endl; - OHOS::FuzzConfigParser jsonParser; + OHOS::NotificationFuzzConfigParser jsonParser; OHOS::FuzzTestData tempData; std::cout << "parseFromFile start" << std::endl; diff --git a/test/resource/notificationfuzztest/src/notificationgetparam.cpp b/test/resource/notificationfuzztest/src/notificationgetparam.cpp index 0ff93b7..29b8d46 100644 --- a/test/resource/notificationfuzztest/src/notificationgetparam.cpp +++ b/test/resource/notificationfuzztest/src/notificationgetparam.cpp @@ -28,6 +28,7 @@ using namespace OHOS::AppExecFwk; using namespace OHOS::EventFwk; using Uri = OHOS::Uri; +namespace { static const int INDEX_ZERO = 0; static const int INDEX_ONE = 1; static const int INDEX_TWO = 2; @@ -39,13 +40,14 @@ static const int INDEX_SEVEN = 7; static const int INDEX_EIGHT = 8; static const int INDEX_NINE = 9; static const int INDEX_TEN = 10; -static const int MESSAGE_INDEX = 36; static const int CHAR_MINCOUNT = -128; static const int CHAR_MAXCOUNT = 127; +static const int MAX_LENGTH = 255; +} // namespace namespace OHOS { namespace Notification { -std::mutex TestAnsSubscriber::mutex_ = std::mutex(); +std::mutex TestAnsSubscriber::mutex = std::mutex(); bool GetBoolParam() { bool param; @@ -238,7 +240,7 @@ string GetStringParam() { string param = ""; char ch = GetCharParam(); - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { ch = GetCharParam(); param += ch; @@ -250,7 +252,7 @@ template vector GetUnsignVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { T t = GetUnsignParam(); param.push_back(t); @@ -268,7 +270,7 @@ T GetClassParam() std::vector GetBoolVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int t = GetBoolParam(); param.push_back(t); @@ -279,7 +281,7 @@ std::vector GetBoolVectorParam() std::vector GetShortVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { short t = GetShortParam(); param.push_back(t); @@ -290,7 +292,7 @@ std::vector GetShortVectorParam() std::vector GetLongVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { long t = GetLongParam(); param.push_back(t); @@ -301,7 +303,7 @@ std::vector GetLongVectorParam() vector GetIntVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int t = GetIntParam(); param.push_back(t); @@ -312,7 +314,7 @@ vector GetIntVectorParam() std::vector GetFloatVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { float t = GetIntParam(); param.push_back(t); @@ -323,7 +325,7 @@ std::vector GetFloatVectorParam() std::vector GetDoubleVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { double t = GetIntParam(); param.push_back(t); @@ -334,7 +336,7 @@ std::vector GetDoubleVectorParam() vector GetCharVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { char t = GetCharParam(); param.push_back(t); @@ -345,7 +347,7 @@ vector GetCharVectorParam() vector GetChar32VectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { char32_t t = GetChar32Param(); param.push_back(t); @@ -356,7 +358,7 @@ vector GetChar32VectorParam() vector GetStringVectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { string t = GetStringParam(); param.push_back(t); @@ -367,7 +369,7 @@ vector GetStringVectorParam() vector GetS8VectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int8_t temp = GetS8Param(); param.push_back(temp); @@ -378,7 +380,7 @@ vector GetS8VectorParam() vector GetS16VectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int16_t temp = GetS16Param(); param.push_back(temp); @@ -389,7 +391,7 @@ vector GetS16VectorParam() vector GetS32VectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int32_t temp = GetS32Param(); param.push_back(temp); @@ -400,7 +402,7 @@ vector GetS32VectorParam() vector GetS64VectorParam() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { int64_t temp = GetS64Param(); param.push_back(temp); @@ -420,7 +422,7 @@ std::shared_ptr GetParamWant() std::vector> GetParamWantVector() { vector> param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { std::shared_ptr t = GetParamWant(); param.push_back(t); @@ -433,47 +435,6 @@ OHOS::AAFwk::Operation GetParamOperation() return OHOS::AAFwk::Operation(); } -std::shared_ptr GetParamAsyncCommonEventResult() -{ - return make_shared( - GetIntParam(), GetStringParam(), GetBoolParam(), GetBoolParam(), GetParamSptrRemote()); -} - -std::shared_ptr GetParamCommonEventData() -{ - return make_shared(); -} - -std::shared_ptr GetParamCommonEventManager() -{ - return make_shared(); -} - -std::shared_ptr GetParamCommonEventPublishInfo() -{ - return make_shared(); -} - -std::shared_ptr GetParamCommonEventSubscribeInfo() -{ - return make_shared(); -} - -std::shared_ptr GetParamCommonEventSubscriber() -{ - return make_shared(); -} - -std::shared_ptr GetParamCommonEventSupport() -{ - return make_shared(); -} - -std::shared_ptr GetParamMatchingSkills() -{ - return make_shared(); -} - sptr GetParamSptrRemote() { return sptr(); @@ -483,289 +444,21 @@ std::shared_ptr GetParamEventRunner() { return EventRunner::Create(GetCharArryParam()); } - -std::shared_ptr GetParamEventHandler() -{ - return make_shared(GetParamEventRunner()); -} - -std::shared_ptr GetParamEventQueue() -{ - return make_shared(); -} - -std::shared_ptr GetParamEventRunnerNativeImplement() -{ - return make_shared(GetBoolParam()); -} - -std::shared_ptr GetParamFileDescriptorListener() -{ - return make_shared(); -} - -TestDumper GetParamDumper() -{ - return GetClassParam(); -} - -InnerEvent::Pointer GetParamInnerEvent() -{ - return InnerEvent::Get(GetU32Param(), GetS64Param()); -} - -CommonEventSubscribeInfo::ThreadMode GetParamThreadMode() -{ - switch (GetIntParam() % INDEX_FOUR) { - case INDEX_ZERO: - return CommonEventSubscribeInfo::ThreadMode::HANDLER; - break; - case INDEX_ONE: - return CommonEventSubscribeInfo::ThreadMode::POST; - break; - case INDEX_TWO: - return CommonEventSubscribeInfo::ThreadMode::ASYNC; - break; - case INDEX_THREE: - return CommonEventSubscribeInfo::ThreadMode::BACKGROUND; - break; - default: - return CommonEventSubscribeInfo::ThreadMode::HANDLER; - break; - } -} - -EventQueue::Priority GetParamPriority() -{ - switch (GetIntParam() % INDEX_FOUR) { - case INDEX_ZERO: - return EventQueue::Priority::IMMEDIATE; - break; - case INDEX_ONE: - return EventQueue::Priority::HIGH; - break; - case INDEX_TWO: - return EventQueue::Priority::LOW; - break; - case INDEX_THREE: - return EventQueue::Priority::IDLE; - break; - default: - return EventQueue::Priority::LOW; - break; - } -} - -std::shared_ptr GetParamLogger() -{ - return make_shared(); -} - -InnerEvent::Callback GetParamCallback() -{ - auto callback = []() { printf("Fuzz Test Inner Event Callback."); }; - return callback; -} - -OHOS::AppExecFwk::InnerEvent::TimePoint GetParamTimePoint() -{ - std::chrono::steady_clock::time_point param = std::chrono::steady_clock::now(); - return param; -} - -std::shared_ptr GetParamAbilityStartSetting() -{ - return AbilityStartSetting::GetEmptySetting(); -} - -sptr GetParamIAbilityConnection() -{ - return sptr(); -} - -std::shared_ptr GetParamAbilityContext() -{ - return make_shared(); -} -std::shared_ptr GetParamIAbilityEvent() -{ - return make_shared(); -} - -sptr GetParamAbilityThread() -{ - return sptr(); -} - -std::shared_ptr GetParamAbilityHandler() -{ - return make_shared(GetParamEventRunner(), GetParamAbilityThread()); -} - std::shared_ptr GetParamAbility() { return make_shared(); } -std::shared_ptr GetParamComponentContainer() -{ - return make_shared(); -} - -std::shared_ptr GetParamOHOSApplication() -{ - return make_shared(); -} - -std::shared_ptr GetParamKeyEvent() -{ - return make_shared(); -} - -OHOS::Uri GetParamUri() -{ - return OHOS::Uri(GetStringParam()); -} - -NativeRdb::ValuesBucket GetParamValuesBucket() -{ - if (GetBoolParam()) { - NativeRdb::ValuesBucket val; - val.PutNull(GetStringParam()); - return val; - } else { - return NativeRdb::ValuesBucket(); - } -} - -OHOS::AppExecFwk::Configuration GetParamConfiguration() -{ - if (GetBoolParam()) { - return OHOS::AppExecFwk::Configuration(GetStringParam()); - } else { - return OHOS::AppExecFwk::Configuration(); - } -} - -NativeRdb::DataAbilityPredicates GetParamDataAbilityPredicates() -{ - if (GetBoolParam()) { - return NativeRdb::DataAbilityPredicates(GetStringParam()); - } else { - return NativeRdb::DataAbilityPredicates(); - } -} - -OHOS::AppExecFwk::PacMap GetParamPacMap() -{ - return OHOS::AppExecFwk::PacMap(); -} - -std::shared_ptr GetParamProcessInfo() -{ - pid_t id = GetIntParam(); - if (GetBoolParam()) { - return make_shared(GetStringParam(), id); - } else { - return make_shared(); - } -} - -std::shared_ptr GetParamDataUriUtils() -{ - return make_shared(); -} - std::shared_ptr GetParamContext() { return make_shared(); } -std::shared_ptr GetParamLifeCycle() -{ - return make_shared(); -} - -OHOS::AppExecFwk::LifeCycle::Event GetParamLifeCycleEvent() -{ - switch (GetIntParam() % INDEX_SEVEN) { - case INDEX_ZERO: - return OHOS::AppExecFwk::LifeCycle::Event::ON_ACTIVE; - break; - case INDEX_ONE: - return OHOS::AppExecFwk::LifeCycle::Event::ON_BACKGROUND; - break; - case INDEX_TWO: - return OHOS::AppExecFwk::LifeCycle::Event::ON_FOREGROUND; - break; - case INDEX_THREE: - return OHOS::AppExecFwk::LifeCycle::Event::ON_INACTIVE; - break; - case INDEX_FOUR: - return OHOS::AppExecFwk::LifeCycle::Event::ON_START; - break; - case INDEX_FIVE: - return OHOS::AppExecFwk::LifeCycle::Event::ON_STOP; - break; - case INDEX_SIX: - return OHOS::AppExecFwk::LifeCycle::Event::UNDEFINED; - break; - default: - return OHOS::AppExecFwk::LifeCycle::Event::ON_ACTIVE; - break; - } -} - -std::shared_ptr GetParamElementName() -{ - if (GetBoolParam()) { - return make_shared(GetStringParam(), GetStringParam(), GetStringParam()); - } else { - return make_shared(); - } -} - std::shared_ptr GetParamWantParams() { return make_shared(); } -std::shared_ptr GetParamAbilityManager() -{ - return make_shared(); -} - -OHOS::AAFwk::PatternsMatcher GetParamPatternsMatcher() -{ - return OHOS::AAFwk::PatternsMatcher(); -} - -OHOS::AAFwk::MatchType GetParamMatchType() -{ - switch (GetIntParam() % INDEX_FOUR) { - case INDEX_ZERO: - return OHOS::AAFwk::MatchType::DEFAULT; - break; - case INDEX_ONE: - return OHOS::AAFwk::MatchType::PREFIX; - break; - case INDEX_TWO: - return OHOS::AAFwk::MatchType::PATTERN; - break; - case INDEX_THREE: - return OHOS::AAFwk::MatchType::GLOBAL; - break; - default: - return OHOS::AAFwk::MatchType::DEFAULT; - break; - } -} - -std::shared_ptr GetParamBundleMgrProxy() -{ - return make_shared(GetParamSptrRemote()); -} - OHOS::AppExecFwk::ApplicationFlag GetParamApplicationFlag() { if (GetBoolParam()) { @@ -779,101 +472,16 @@ OHOS::AppExecFwk::ApplicationInfo GetParamApplicationInfo() { return OHOS::AppExecFwk::ApplicationInfo(); } - -std::vector GetParamApplicationInfoVector() -{ - vector param; - size_t len = GenRandom(0, 255); - while (len--) { - OHOS::AppExecFwk::ApplicationInfo t = GetParamApplicationInfo(); - param.push_back(t); - } - return param; -} - -OHOS::AppExecFwk::BundleFlag GetParamBundleFlag() -{ - if (GetBoolParam()) { - return OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_DEFAULT; - } else { - return OHOS::AppExecFwk::BundleFlag::GET_BUNDLE_WITH_ABILITIES; - } -} - -OHOS::AppExecFwk::BundleInfo GetParamBundleInfo() -{ - return OHOS::AppExecFwk::BundleInfo(); -} - OHOS::AppExecFwk::AbilityInfo GetParamAbilityInfo() { return OHOS::AppExecFwk::AbilityInfo(); } -OHOS::AppExecFwk::HapModuleInfo GetParamHapModuleInfo() -{ - return OHOS::AppExecFwk::HapModuleInfo(); -} - -OHOS::AppExecFwk::PermissionDef GetParamPermissionDef() -{ - return OHOS::AppExecFwk::PermissionDef(); -} - -std::vector GetParamPermissionDefVector() -{ - vector param; - size_t len = GenRandom(0, 255); - while (len--) { - OHOS::AppExecFwk::PermissionDef t = GetParamPermissionDef(); - param.push_back(t); - } - return param; -} - -OHOS::AppExecFwk::IBundleMgr::Message GetParamIBundleMgrMessage() -{ - return (OHOS::AppExecFwk::IBundleMgr::Message)(GetIntParam() % MESSAGE_INDEX); -} - -OHOS::MessageParcel GetParamMessageParcel() -{ - return OHOS::MessageParcel(); -} - -OHOS::AppExecFwk::DumpFlag GetParamDumpFlag() -{ - switch (GetIntParam() % INDEX_THREE) { - case INDEX_ZERO: - return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_LIST; - break; - case INDEX_ONE: - return OHOS::AppExecFwk::DumpFlag::DUMP_ALL_BUNDLE_INFO; - break; - case INDEX_TWO: - return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_INFO; - break; - default: - return OHOS::AppExecFwk::DumpFlag::DUMP_BUNDLE_LIST; - break; - } -} - -sptr GetParamICleanCacheCallback() -{ - return sptr(); -} - sptr GetParamIBundleStatusCallback() { return sptr(); } -std::shared_ptr GetParamDataAbilityHelper() -{ - return OHOS::AppExecFwk::DataAbilityHelper::Creator(std::make_shared()); -} - std::shared_ptr GetParamNotificationSorting() { return std::make_shared(); @@ -882,7 +490,7 @@ std::shared_ptr GetParamNotificationSorting() std::vector GetParamNotificationSortingVector() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { NotificationSorting t; param.push_back(t); @@ -907,8 +515,7 @@ std::shared_ptr GetParamNotificationSlot() sptr GetParamNotificationSlotSptr() { - sptr param = - new OHOS::Notification::NotificationSlot(GetParamSlotType()); + sptr param = new OHOS::Notification::NotificationSlot(GetParamSlotType()); return param; } @@ -938,7 +545,7 @@ OHOS::Notification::NotificationConstant::SlotType GetParamSlotType() std::vector> GetParamNotificationSlotSptrVector() { vector> param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { sptr t = GetParamNotificationSlotSptr(); param.push_back(t); @@ -949,7 +556,7 @@ std::vector> GetParamNotificationSlot std::vector GetParamNotificationSlotVector() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { NotificationSlot t = *GetParamNotificationSlot(); param.push_back(t); @@ -960,7 +567,7 @@ std::vector GetParamNotificationSlotVector std::vector GetParamNotificationSlotGroupVector() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::Notification::NotificationSlotGroup t = *GetParamNotificationSlotGroup(); param.push_back(t); @@ -976,7 +583,7 @@ sptr GetParamNotificationSlotGroup() std::vector> GetParamNotificationSlotGroupSptrVector() { vector> param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { sptr t = GetParamNotificationSlotGroup(); param.push_back(t); @@ -1036,7 +643,7 @@ sptr GetParamNotificationRequestSptr() std::vector> GetParamNotificationRequestVector() { vector> param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { sptr t = GetParamNotificationRequestSptr(); param.push_back(t); @@ -1180,7 +787,7 @@ OHOS::Notification::WantAgent::WantAgentConstant::Flags GetParamFlags() std::vector GetParamFlagsVector() { vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::Notification::WantAgent::WantAgentConstant::Flags t = GetParamFlags(); param.push_back(t); @@ -1204,7 +811,7 @@ sptr GetParamNotificationSptr() std::vector> GetParamNotificationSptrVector() { std::vector> param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { sptr t = GetParamNotificationSptr(); param.push_back(t); @@ -1254,7 +861,7 @@ std::shared_ptr GetParamLauncherService() std::vector GetParamLauncherAbilityInfoVector() { std::vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::AppExecFwk::LauncherAbilityInfo t; param.push_back(t); @@ -1268,7 +875,7 @@ std::shared_ptr GetParamLauncherAbilityIn std::vector GetParamLauncherShortcutInfoVector() { std::vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::AppExecFwk::LauncherShortcutInfo t; param.push_back(t); @@ -1278,7 +885,7 @@ std::vector GetParamLauncherShortcutInfo std::vector GetParamFormInfoVector() { std::vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::AppExecFwk::FormInfo t; param.push_back(t); @@ -1288,7 +895,7 @@ std::vector GetParamFormInfoVector() std::vector GetParamShortcutInfoVector() { std::vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::AppExecFwk::ShortcutInfo t; param.push_back(t); @@ -1298,7 +905,7 @@ std::vector GetParamShortcutInfoVector() std::vector GetParamModuleUsageRecordVector() { std::vector param; - size_t len = GenRandom(0, 255); + size_t len = GenRandom(0, MAX_LENGTH); while (len--) { OHOS::AppExecFwk::ModuleUsageRecord t; param.push_back(t); -- Gitee From d946528131f4f23169d6484e884d64a5316b1065 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 24 Nov 2021 16:35:01 +0000 Subject: [PATCH 023/131] Fix codex Signed-off-by: zhaoyuan17 --- .../notificationfuzztest/include/notificationgetparam.h | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/test/resource/notificationfuzztest/include/notificationgetparam.h b/test/resource/notificationfuzztest/include/notificationgetparam.h index b18017d..80aa444 100644 --- a/test/resource/notificationfuzztest/include/notificationgetparam.h +++ b/test/resource/notificationfuzztest/include/notificationgetparam.h @@ -16,7 +16,7 @@ #define NOTIFICATION_GET_PARAM_H #include #include -#include +#include #include #include "ability.h" @@ -204,8 +204,6 @@ public: } }; - - class TestIBundleStatusCallback : public OHOS::AppExecFwk::IBundleStatusCallback { public: TestIBundleStatusCallback() -- Gitee From bbf405a579ba422b3af3578bfcfedea641daddf4 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 25 Nov 2021 15:01:43 +0000 Subject: [PATCH 024/131] Fix codex Signed-off-by: zhaoyuan17 --- .../ans/native/src/notification_slot.cpp | 2 +- .../test/moduletest/ans_fw_module_test.cpp | 2 +- .../ans_innerkits_module_slot_test.cpp | 8 +- interfaces/kits/napi/ans/src/cancel.cpp | 25 +----- interfaces/kits/napi/ans/src/get_active.cpp | 61 +++----------- interfaces/kits/napi/ans/src/slot.cpp | 79 +++++-------------- 6 files changed, 37 insertions(+), 140 deletions(-) diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 3ff67a5..a54224d 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -14,8 +14,8 @@ */ #include "notification_slot.h" -#include "ans_log_wrapper.h" #include "ans_const_define.h" +#include "ans_log_wrapper.h" namespace OHOS { namespace Notification { diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index b9db098..9b2b770 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -464,7 +464,7 @@ public: return onCanceledWithSortingMapSor_; } - std::vector GetOnCanceledWithSortingMapDelRea() + std::vector GetOnCanceledWithSortingMapDelRea() const { return onCanceledWithSortingMapDelRea_; } 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 91ab5d6..caef96a 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -15,15 +15,15 @@ #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; @@ -363,7 +363,7 @@ HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00800, Fu EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, slot.GetLockScreenVisibleness()); EXPECT_EQ("", slot.GetSound().ToString()); EXPECT_FALSE(slot.CanVibrate()); - EXPECT_EQ(0, slot.GetVibrationStyle().size()); + EXPECT_EQ(0U, slot.GetVibrationStyle().size()); EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_LOW, slot.GetLevel()); } @@ -380,7 +380,7 @@ HWTEST_F(AnsInterfaceModuleSlotTest, ANS_Interface_MT_NotificationSlot_00900, Fu EXPECT_EQ(NotificationConstant::VisiblenessType::SECRET, slot.GetLockScreenVisibleness()); EXPECT_EQ("", slot.GetSound().ToString()); EXPECT_FALSE(slot.CanVibrate()); - EXPECT_EQ(0, slot.GetVibrationStyle().size()); + EXPECT_EQ(0U, slot.GetVibrationStyle().size()); EXPECT_EQ(NotificationSlot::NotificationLevel::LEVEL_MIN, slot.GetLevel()); } diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 3edad37..0ba7a44 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -17,9 +17,7 @@ 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; @@ -91,25 +89,6 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, return Common::NapiGetNull(env); } -napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); - - size_t argc = CANCEL_ALL_MAX_PARA; - napi_value argv[CANCEL_ALL_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= CANCEL_ALL_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); - } - return Common::NapiGetNull(env); -} - napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, ParametersInfoCancelGroup ¶s) { ANS_LOGI("enter"); @@ -202,7 +181,7 @@ napi_value CancelAll(napi_env env, napi_callback_info info) ANS_LOGI("enter"); napi_ref callback = nullptr; - if (ParseParameters(env, info, callback) == nullptr) { + if (Common::ParseParaOnlyCallback(env, info, callback) == nullptr) { return Common::NapiGetUndefined(env); } @@ -257,7 +236,7 @@ napi_value CancelGroup(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); - ParametersInfoCancelGroup params; + ParametersInfoCancelGroup params {}; if (ParseParameters(env, info, params) == nullptr) { return Common::NapiGetUndefined(env); } diff --git a/interfaces/kits/napi/ans/src/get_active.cpp b/interfaces/kits/napi/ans/src/get_active.cpp index c424913..f924d7f 100644 --- a/interfaces/kits/napi/ans/src/get_active.cpp +++ b/interfaces/kits/napi/ans/src/get_active.cpp @@ -17,9 +17,6 @@ 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; @@ -29,46 +26,6 @@ struct AsyncCallbackInfoActive { int32_t num = 0; }; -napi_value ParseParametersByAllActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); - - size_t argc = ALL_ACTIVE_MAX_PARA; - napi_value argv[ALL_ACTIVE_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= ALL_ACTIVE_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); - } - - return Common::NapiGetNull(env); -} - -napi_value ParseParametersByGetActive(const napi_env &env, const napi_callback_info &info, napi_ref &callback) -{ - ANS_LOGI("enter"); - - size_t argc = ACTIVE_OR_NUMS_MAX_PARA; - napi_value argv[ACTIVE_OR_NUMS_MAX_PARA] = {nullptr}; - napi_value thisVar = nullptr; - NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc >= ACTIVE_OR_NUMS_MAX_PARA) { - napi_valuetype valuetype = napi_undefined; - // argv[0]:callback - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); - napi_create_reference(env, argv[0], 1, &callback); - } - - return Common::NapiGetNull(env); -} - void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status status, void *data) { ANS_LOGI("GetAllActiveNotifications napi_create_async_work end"); @@ -78,7 +35,7 @@ void AsyncCompleteCallbackGetAllActiveNotifications(napi_env env, napi_status st return; } - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -126,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); } @@ -147,7 +104,7 @@ 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; asynccallbackinfo->info.errorCode = NotificationHelper::GetAllActiveNotifications(asynccallbackinfo->notifications); @@ -174,7 +131,7 @@ void AsyncCompleteCallbackGetActiveNotifications(napi_env env, napi_status statu return; } - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -221,7 +178,7 @@ 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); } @@ -242,7 +199,7 @@ 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; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotifications(asynccallbackinfo->requests); @@ -269,7 +226,7 @@ void AsyncCompleteCallbackGetActiveNotificationCount(napi_env env, napi_status s return; } - AsyncCallbackInfoActive *asynccallbackinfo = (AsyncCallbackInfoActive *)data; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -295,7 +252,7 @@ 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); } @@ -316,7 +273,7 @@ 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; + auto asynccallbackinfo = (AsyncCallbackInfoActive *)data; asynccallbackinfo->info.errorCode = NotificationHelper::GetActiveNotificationNums(asynccallbackinfo->num); ANS_LOGI("GetActiveNotificationCount count = %{public}d", asynccallbackinfo->num); diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index 4590c92..faa723f 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; @@ -316,24 +314,6 @@ napi_value ParseParametersGetSlotNumByBundle( 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) { @@ -394,24 +374,6 @@ napi_value ParseParametersByRemoveSlot( 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); - } - return Common::NapiGetNull(env); -} - napi_value AddSlot(napi_env env, napi_callback_info info) { ANS_LOGI("enter"); @@ -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,7 +520,7 @@ 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); @@ -568,7 +530,7 @@ napi_value SetSlotByBundle(napi_env env, napi_callback_info info) }, [](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)); @@ -604,7 +566,7 @@ void AsyncCompleteCallbackGetSlot(napi_env env, napi_status status, void *data) return; } - AsyncCallbackInfoGetSlot *asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlot *)data; napi_value result = Common::NapiGetNull(env); if (asynccallbackinfo->info.errorCode == ERR_OK) { if (asynccallbackinfo->slot == nullptr) { @@ -655,7 +617,7 @@ 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; asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlot(asynccallbackinfo->outType, asynccallbackinfo->slot); @@ -698,18 +660,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; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; NotificationBundleOption bundleOption; bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); bundleOption.SetUid(asynccallbackinfo->params.option.uid); asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, asynccallbackinfo->num); - }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlotNumByBundle napi_create_async_work end"); - AsyncCallbackInfoGetSlotNumByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; napi_value result = nullptr; napi_create_int32(env, asynccallbackinfo->num, &result); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); @@ -741,7 +702,7 @@ 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); } @@ -761,12 +722,12 @@ 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; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(asynccallbackinfo->slots); }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlots napi_create_async_work end"); - AsyncCallbackInfoGetSlots *asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { result = Common::NapiGetNull(env); @@ -843,7 +804,7 @@ 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); @@ -853,7 +814,7 @@ napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) }, [](napi_env env, napi_status status, void *data) { ANS_LOGI("GetSlotsByBundle napi_create_async_work end"); - AsyncCallbackInfoGetSlotsByBundle *asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; + auto asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; napi_value result = nullptr; if (asynccallbackinfo->info.errorCode != ERR_OK) { @@ -931,12 +892,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)); @@ -967,7 +928,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); } @@ -987,12 +948,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)); -- Gitee From 2d46bcad88d0e19e54eb718b7967fbea48a7ed67 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 29 Nov 2021 13:28:19 +0000 Subject: [PATCH 025/131] Modify WantAgent NAPI Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/wantagent/napi_want_agent.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index 4cb4152..727f54f 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -197,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); -- Gitee From 251d1cf893a266c4800f0f17c89dba168d960e5c Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Tue, 30 Nov 2021 17:23:41 +0800 Subject: [PATCH 026/131] change inner kits to be better Signed-off-by: Sven Wang --- .../notification_preferences_database.h | 2 +- .../src/notification_preferences_database.cpp | 25 ++++++------------- 2 files changed, 8 insertions(+), 19 deletions(-) diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 9b6526d..d037fe4 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -139,7 +139,7 @@ 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_; }; diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 1243e40..a839e14 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -140,35 +140,24 @@ void NotificationPreferencesDatabase::TryTwice(const std::function - 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() -- Gitee From 364831afbdf56a662dc413dbb4dc6c58f5565183 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Wed, 1 Dec 2021 15:10:22 +0800 Subject: [PATCH 027/131] change inner kits to be better Signed-off-by: Sven Wang --- .../mock/distributed_kv_data_manager.cpp | 14 +++---- .../mock/include/mock_single_kv_store.h | 21 ++++++---- .../moduletest/mock/mock_single_kv_store.cpp | 40 ++++++++++++++----- 3 files changed, 49 insertions(+), 26 deletions(-) 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 d755b01..dbe6474 100644 --- a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -28,22 +28,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)); + kvStore = std::make_share(); + 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/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h index 59a5d5c..70a3135 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 @@ -38,16 +38,15 @@ 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; @@ -95,8 +94,14 @@ public: virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const 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/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp index 85aed3f..38aaf86 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -34,19 +34,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; } @@ -170,5 +175,20 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam 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 -- Gitee From 6c50688dce0fd8578e667d43e12cb3d9deb2e5c6 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Wed, 1 Dec 2021 17:50:03 +0800 Subject: [PATCH 028/131] fixed mock error Signed-off-by: Sven Wang --- .../moduletest/mock/mock_single_kv_store.cpp | 2 +- .../mock/include/mock_single_kv_store.h | 21 ++++++---- .../unittest/mock/mock_single_kv_store.cpp | 42 ++++++++++++++----- 3 files changed, 45 insertions(+), 20 deletions(-) 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 38aaf86..dd5c05e 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -170,7 +170,7 @@ 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; } 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 f32d46b..811ef90 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,16 +39,15 @@ 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; @@ -96,8 +95,14 @@ public: virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const 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_single_kv_store.cpp b/services/ans/test/unittest/mock/mock_single_kv_store.cpp index 85aed3f..dd5c05e 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -34,19 +34,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; } @@ -165,10 +170,25 @@ 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::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 -- Gitee From a2a9192b850743a125184dec50fc095e58d864ca Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Wed, 1 Dec 2021 20:25:35 +0800 Subject: [PATCH 029/131] change to be better Signed-off-by: Sven Wang --- .../ans/test/moduletest/mock/distributed_kv_data_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 dbe6474..a223023 100644 --- a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -32,7 +32,7 @@ Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const std::shared_ptr &kvStore) { std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); - kvStore = std::make_share(); + kvStore = std::make_shared(); return Status::SUCCESS; } -- Gitee From 48b619afea7fb902f156a2aff639dcb217fa8c10 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Thu, 2 Dec 2021 09:10:54 +0800 Subject: [PATCH 030/131] change inner kits to be better Signed-off-by: Sven Wang --- .../unittest/mock/distributed_kv_data_manager.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) 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 d755b01..a223023 100644 --- a/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp +++ b/services/ans/test/unittest/mock/distributed_kv_data_manager.cpp @@ -28,22 +28,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)); + 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; } -- Gitee From ca2767e7df4f81ffcc05113e48639ac4207bd0a8 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Thu, 2 Dec 2021 09:34:25 +0800 Subject: [PATCH 031/131] change inner kits to be better Signed-off-by: Sven Wang --- .../mock/distributed_kv_data_manager.cpp | 14 +++---- .../mock/include/mock_single_kv_store.h | 21 ++++++---- .../moduletest/mock/mock_single_kv_store.cpp | 42 ++++++++++++++----- 3 files changed, 50 insertions(+), 27 deletions(-) diff --git a/services/test/moduletest/mock/distributed_kv_data_manager.cpp b/services/test/moduletest/mock/distributed_kv_data_manager.cpp index d755b01..a223023 100644 --- a/services/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/services/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -28,22 +28,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)); + 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/test/moduletest/mock/include/mock_single_kv_store.h b/services/test/moduletest/mock/include/mock_single_kv_store.h index f32d46b..811ef90 100644 --- a/services/test/moduletest/mock/include/mock_single_kv_store.h +++ b/services/test/moduletest/mock/include/mock_single_kv_store.h @@ -39,16 +39,15 @@ 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; @@ -96,8 +95,14 @@ public: virtual Status GetSecurityLevel(SecurityLevel &securityLevel) const 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/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index 85aed3f..dd5c05e 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/mock/mock_single_kv_store.cpp @@ -34,19 +34,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; } @@ -165,10 +170,25 @@ 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::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 -- Gitee From bf66569f04b3830546af68870b145143b52baeb6 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Thu, 2 Dec 2021 11:50:50 +0800 Subject: [PATCH 032/131] change inner kits to be better Signed-off-by: Sven Wang --- frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp | 2 +- services/ans/test/unittest/mock/mock_single_kv_store.cpp | 2 +- services/test/moduletest/mock/mock_single_kv_store.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) 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 dd5c05e..bc79b19 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -176,7 +176,7 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam } Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const + std::shared_ptr &snapshot) const { return Status::NOT_SUPPORT; } 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 dd5c05e..bc79b19 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -176,7 +176,7 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam } Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const + std::shared_ptr &snapshot) const { return Status::NOT_SUPPORT; } diff --git a/services/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index dd5c05e..bc79b19 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/mock/mock_single_kv_store.cpp @@ -176,7 +176,7 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam } Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const + std::shared_ptr &snapshot) const { return Status::NOT_SUPPORT; } -- Gitee From 0222a98896bf51c00732af7f423679dd15cdd4d0 Mon Sep 17 00:00:00 2001 From: Sven Wang Date: Thu, 2 Dec 2021 14:16:15 +0800 Subject: [PATCH 033/131] change inner kits to be better Signed-off-by: Sven Wang --- .../ans/test/moduletest/mock/include/mock_single_kv_store.h | 1 - 1 file changed, 1 deletion(-) 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 70a3135..0e2a140 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 @@ -29,7 +29,6 @@ namespace OHOS { namespace DistributedKv { - class AnsTestSingleKvStore : public SingleKvStore { public: virtual Status GetEntries(const Key &prefixKey, std::vector &entries) const override; -- Gitee From e9f59e073d659e276582e519c4a9dcf1dfdfc676 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 2 Dec 2021 10:35:45 +0000 Subject: [PATCH 034/131] Long-term tasks are related to UserInput Signed-off-by: zhaoyuan17 --- .../core/common/include/ans_const_define.h | 1 + .../core/common/include/ans_inner_errors.h | 1 + .../ans/core/include/ans_manager_interface.h | 10 +- .../ans/core/include/ans_manager_proxy.h | 2 + .../ans/core/include/ans_manager_stub.h | 4 + .../ans/core/include/ans_notification.h | 17 + frameworks/ans/core/src/ans_manager_proxy.cpp | 67 + frameworks/ans/core/src/ans_manager_stub.cpp | 57 + frameworks/ans/core/src/ans_notification.cpp | 27 + frameworks/ans/native/src/notification.cpp | 139 +- .../ans/native/src/notification_helper.cpp | 10 + .../ans/native/src/notification_request.cpp | 2 +- .../test/moduletest/ans_fw_module_test.cpp | 179 ++ .../ans/native/include/notification.h | 28 +- .../native/include/notification_constant.h | 15 + .../ans/native/include/notification_helper.h | 17 + .../ans/native/include/notification_request.h | 2 +- interfaces/kits/js/@ohos.notification.d.ts | 285 +- interfaces/kits/js/@ohos.wantAgent.d.ts | 143 +- ...utton.ts => notificationActionButton.d.ts} | 15 +- .../js/notification/notificationContent.d.ts | 74 +- .../js/notification/notificationRequest.d.ts | 104 +- .../js/notification/notificationSlot.d.ts | 26 +- ...Info.ts => notificationSubscribeInfo.d.ts} | 0 interfaces/kits/js/wantAgent/triggerInfo.d.ts | 24 +- .../kits/js/wantAgent/wantAgentInfo.d.ts | 22 +- interfaces/kits/napi/ans/include/common.h | 227 +- interfaces/kits/napi/ans/src/common.cpp | 2830 ++++++++++------- interfaces/kits/napi/ans/src/constant.cpp | 136 +- interfaces/kits/napi/ans/src/subscribe.cpp | 12 +- .../include/advanced_notification_service.h | 5 +- .../ans/src/advanced_notification_service.cpp | 104 +- .../advanced_notification_service_test.cpp | 72 +- 33 files changed, 3268 insertions(+), 1389 deletions(-) rename interfaces/kits/js/notification/{notificationActionButton.ts => notificationActionButton.d.ts} (83%) rename interfaces/kits/js/notification/{notificationSubscribeInfo.ts => notificationSubscribeInfo.d.ts} (100%) diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 60a2cc4..8e1cb00 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -32,6 +32,7 @@ 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; // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index a671871..8e59ee7 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, diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 70caf0f..fae8fdf 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -22,8 +22,8 @@ #include "ans_subscriber_interface.h" #include "iremote_broker.h" #include "notification_bundle_option.h" -#include "notification_do_not_disturb_date.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" @@ -103,14 +103,16 @@ 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 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 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; protected: enum TransactId : uint32_t { @@ -168,6 +170,8 @@ protected: CANCEL_GROUP, REMOVE_GROUP_BY_BUNDLE, SHELL_DUMP, + PUBLISH_LONG_TASK_NOTIFICATION, + CANCEL_LONG_TASK_NOTIFICATION, }; }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index b780d0d..77cd702 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -99,6 +99,8 @@ public: const sptr &bundleOption, const std::string &groupName) 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; private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index 04338d6..7947df7 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -104,6 +104,8 @@ public: const sptr &bundleOption, const std::string &groupName) 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; private: static const std::map> @@ -163,6 +165,8 @@ private: ErrCode HandleSetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleGetDoNotDisturbDate(MessageParcel &data, MessageParcel &reply); ErrCode HandleDoesSupportDoNotDisturbMode(MessageParcel &data, MessageParcel &reply); + ErrCode HandlePublishContinuousTaskNotification(MessageParcel &data, MessageParcel &reply); + ErrCode HandleCancelContinuousTaskNotification(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 4c26613..0f879f0 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -618,6 +618,23 @@ public: */ ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + /** + * Publishes a long task notification. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish long task notification result. + */ + ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); + + /** + * Cancels a published long task notification matching the specified label and notificationId. + * + * @param label Indicates the label of the long task notification to cancel. + * @param notificationId Indicates the ID of the long task notification to cancel. + * @return Returns cancel long task notification result. + */ + ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId); + /** * Reset ans manager proxy when OnRemoteDied called. */ diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 69c1809..7729d7a 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1876,6 +1876,73 @@ 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_LONG_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_LONG_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::InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply) { auto remote = Remote(); diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 2e8da5e..7fac8fd 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -188,6 +188,12 @@ const std::map 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; +} + ErrCode AnsManagerStub::HandleIsNotificationPolicyAccessGranted(MessageParcel &data, MessageParcel &reply) { bool granted = false; @@ -1616,5 +1662,16 @@ ErrCode AnsManagerStub::ShellDump(const std::string &dumpOption, std::vector &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; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index fb2a0e2..7171c38 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -819,6 +819,33 @@ ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &doesSupport) return ansManagerProxy_->DoesSupportDoNotDisturbMode(doesSupport); } +ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationRequest &request) +{ + if (!GetAnsManagerProxy()) { + ANS_LOGE("GetAnsManagerProxy fail."); + return ERR_ANS_SERVICE_NOT_CONNECTED; + } + + auto pReq = new (std::nothrow) NotificationRequest(request); + if (pReq == nullptr) { + ANS_LOGE("create NotificationRequest failed."); + return ERR_ANS_NO_MEMORY; + } + + sptr sptrReq(pReq); + 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); +} + void AnsNotification::ResetAnsManagerProxy() { ANS_LOGI("enter"); diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 9e82978..100e122 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -41,6 +41,8 @@ Notification::Notification(const Notification &other) postTime_ = other.postTime_; sound_ = other.sound_; vibrationStyle_ = other.vibrationStyle_; + isRemoveAllowed_ = other.isRemoveAllowed_; + sourceType_ = other.sourceType_; } Notification::~Notification() @@ -171,7 +173,17 @@ bool Notification::IsFloatingIcon() const return request_->IsFloatingIcon(); } -bool Notification::Marshalling(Parcel &parcel) const +bool Notification::IsRemoveAllowed() const +{ + return isRemoveAllowed_; +} + +NotificationConstant::SourceType Notification::GetSourceType() const +{ + return sourceType_; +} + +bool Notification::MarshallingBool(Parcel &parcel) const { if (!parcel.WriteBool(enableLight_)) { ANS_LOGE("Can't write enableLight_"); @@ -188,10 +200,33 @@ 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; + } + } + + return true; +} + +bool Notification::MarshallingInt32(Parcel &parcel) const +{ if (!parcel.WriteInt32(ledLightColor_)) { ANS_LOGE("Can't write ledLigthColor"); return false; @@ -202,23 +237,21 @@ bool Notification::Marshalling(Parcel &parcel) const return false; } - if (!parcel.WriteStrongParcelable(request_)) { - ANS_LOGE("Can't write request"); + if (!parcel.WriteInt32(static_cast(sourceType_))) { + ANS_LOGE("Can't write sourceType"); return false; } + return true; +} + +bool Notification::MarshallingInt64(Parcel &parcel) const +{ if (!parcel.WriteInt64(postTime_)) { ANS_LOGE("Can't write postTime"); return false; } - if (enableSound_ && sound_ != nullptr) { - if (!parcel.WriteString(sound_->ToString())) { - ANS_LOGE("Can't write sound"); - return false; - } - } - if (!parcel.WriteInt64Vector(vibrationStyle_)) { ANS_LOGE("Can't write vibrationStyle"); return false; @@ -227,7 +260,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,28 +302,55 @@ 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()); + } +} +void Notification::ReadFromParcelInt32(Parcel &parcel) +{ // Read ledLightColor_ ledLightColor_ = parcel.ReadInt32(); // Read lockscreenVisibleness_ lockscreenVisibleness_ = static_cast(parcel.ReadInt32()); - // Read request_ - request_ = parcel.ReadStrongParcelable(); + // 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; } @@ -325,10 +416,22 @@ std::string Notification::GenerateNotificationKey(int32_t uid, const std::string 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_)) + + ", isRemoveAllowed = " + (isRemoveAllowed_ ? "true" : "false") + + ", sourceType = " + std::to_string(static_cast(sourceType_)) + ",request = "; if (request_ == nullptr) { dump += "nullptr"; diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 020fe4a..038e5f9 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -321,5 +321,15 @@ ErrCode NotificationHelper::DoesSupportDoNotDisturbMode(bool &doesSupport) { return DelayedSingleton::GetInstance()->DoesSupportDoNotDisturbMode(doesSupport); } + +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); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 801fb1e..1ea18d3 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -387,7 +387,7 @@ uint32_t NotificationRequest::GetColor() const return color_; } -bool NotificationRequest::IsColorEnabled() +bool NotificationRequest::IsColorEnabled() const { if (!colorEnabled_) { return false; diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index 9b2b770..ef727d9 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -28,6 +28,7 @@ #include "ans_manager_proxy.h" #include "if_system_ability_manager.h" #include "iservice_registry.h" +#include "mock_ipc_skeleton.h" #include "notification_content.h" #include "notification_helper.h" #include "notification_long_text_content.h" @@ -1547,5 +1548,183 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_07000, Function | Medium EXPECT_EQ(srcDate.GetDoNotDisturbType(), disDate.GetDoNotDisturbType()); } + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishLongTask_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_PulbishLongTask_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_ANS_NOTIFICATION_NOT_EXISTS); + 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_PulbishLongTask_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_PulbishLongTask_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_PulbishLongTask_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_PulbishLongTask_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]->IsRemoveAllowed(), false); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetSourceType(), NotificationConstant::SourceType::TYPE_CONTINUOUS); + + EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); + SleepForFC(); + subscriber.ClearEvents(); + IPCSkeleton::SetCallingUid(1); +} } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index e515d61..1b125e4 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -181,6 +181,18 @@ public: */ bool IsFloatingIcon() 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 Dumps a string representation of the object. * @@ -216,16 +228,30 @@ private: void SetPostTime(const int64_t &time); void SetSound(const Uri &sound); void SetVibrationStyle(const std::vector &style); - bool ReadFromParcel(Parcel &parcel); + void SetRemoveAllowed(bool removeAllowed); + void SetSourceType(NotificationConstant::SourceType sourceType); std::string GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id); + bool ReadFromParcel(Parcel &parcel); + 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_ {""}; int32_t ledLightColor_ {0}; NotificationConstant::VisiblenessType lockscreenVisibleness_ {NotificationConstant::VisiblenessType::NO_OVERRIDE}; + 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_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index dcf4fe9..fb8f4aa 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -91,6 +91,21 @@ public: CLEARLY = 3, // time period }; + 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_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 73bd56b..cbc3d46 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -612,6 +612,23 @@ public: * @return Returns check result. */ static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); + + /** + * Publishes a long task notification. + * @param request Indicates the NotificationRequest object for setting the notification content. + * This parameter must be specified. + * @return Returns publish long task notification result. + */ + static ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); + + /** + * Cancels a published long task notification matching the specified label and notificationId. + * + * @param label Indicates the label of the long task notification to cancel. + * @param notificationId Indicates the ID of the long task notification to cancel. + * @return Returns cancel long task notification result. + */ + static ErrCode CancelContinuousTaskNotification(const std::string &label, int32_t notificationId); }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index d5f6c81..ad1b078 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -454,7 +454,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. diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index 869beba..b1eb7f2 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}. - * - * @param label Indicates the label of the notification to cancel. - * @param id Indicates the ID of the notification to cancel. + * Cancels a notification with the specified label and ID. * - * @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. + * Removes a NotificationSlot of the specified SlotType created by the current application. * - * @param slotType Indicates the type of the slot. - * - * @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,33 @@ 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 - * - * @since 7 + * Describes a BundleOption. */ export interface BundleOption { bundle: string; @@ -354,9 +504,7 @@ declare namespace notification { } /** - * NotificationKey - * - * @since 7 + * Describes a NotificationKey, which can be used to identify a notification. */ export interface NotificationKey { id: number; @@ -367,7 +515,6 @@ declare namespace notification { * DisturbMode * * @systemapi Hide this for inner system use. - * @since 7 */ export enum DoNotDisturbMode { ALLOW_UNKNOWN, diff --git a/interfaces/kits/js/@ohos.wantAgent.d.ts b/interfaces/kits/js/@ohos.wantAgent.d.ts index f7eab8a..17dd1c8 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,177 @@ 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, + + /** + * Indicates that the created WantAgent should be immutable. + */ CONSTANT_FLAG, + + /** + * Indicates that the current value of element can be replaced when the WantAgent is triggered. + */ REPLACE_ELEMENT, + + /** + * Indicates that the current value of action can be replaced when the WantAgent is triggered. + */ REPLACE_ACTION, + + /** + * Indicates that the current value of uri can be replaced when the WantAgent is triggered. + */ REPLACE_URI, + + /** + * Indicates that the current value of entities can be replaced when the WantAgent is triggered. + */ REPLACE_ENTITIES, + + /** + * Indicates that the current value of packageName can be replaced when the WantAgent is triggered. + */ REPLACE_BUNDLE } /** - * 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 83% rename from interfaces/kits/js/notification/notificationActionButton.ts rename to interfaces/kits/js/notification/notificationActionButton.d.ts index 1402150..39cc3db 100644 --- a/interfaces/kits/js/notification/notificationActionButton.ts +++ b/interfaces/kits/js/notification/notificationActionButton.d.ts @@ -16,15 +16,26 @@ 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}; } diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts index 7624cd3..d2cc36e 100644 --- a/interfaces/kits/js/notification/notificationContent.d.ts +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -15,9 +15,8 @@ import notification from '../@ohos.notification'; import image from './@ohos.multimedia.image'; - /** - * Constructs basic notifications. + * Describes a normal text notification. * * @name NotificationBasicContent * @since 7 @@ -26,13 +25,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 +51,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 +77,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 +103,24 @@ 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. + * Describes notification types. * * @name NotificationContent * @since 7 @@ -86,9 +129,28 @@ 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; } diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index f3e2657..b7e6575 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -20,7 +20,7 @@ import { NotificationContent } from './notificationContent'; import { NotificationActionButton } from './notificationActionButton'; /** - * Carries notifications. + * Defines a NotificationRequest instance. * * @name NotificationRequest * @since 7 @@ -29,44 +29,140 @@ 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; + + /** + * 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; } diff --git a/interfaces/kits/js/notification/notificationSlot.d.ts b/interfaces/kits/js/notification/notificationSlot.d.ts index 56f987e..82ff360 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/wantAgent/triggerInfo.d.ts b/interfaces/kits/js/wantAgent/triggerInfo.d.ts index 20dfdea..8cd951d 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 d4d1c87..f33531d 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/include/common.h b/interfaces/kits/napi/ans/include/common.h index c95b1a1..c0ad43f 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -29,16 +29,15 @@ const std::int32_t LONG_STR_MAX_SIZE = 1024; const int NO_ERROR = 0; const int ERROR = -1; -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 +45,7 @@ enum SlotType { OTHER_TYPES = 0xFFFF, }; -enum SlotLevel { +enum class SlotLevel { LEVEL_NONE = 0, LEVEL_MIN = 1, LEVEL_LOW = 2, @@ -54,7 +53,7 @@ enum SlotLevel { LEVEL_HIGH = 4, }; -enum NotificationReason { +enum class NotificationReason { CLICK_REASON_DELETE, CANCEL_REASON_DELETE, CANCEL_ALL_REASON_DELETE, @@ -67,7 +66,7 @@ enum NotificationReason { APP_CANCEL_REASON_OTHER }; -enum SemanticActionButton { +enum class SemanticActionButton { NONE_ACTION_BUTTON, REPLY_ACTION_BUTTON, READ_ACTION_BUTTON, @@ -81,13 +80,35 @@ enum SemanticActionButton { CALL_ACTION_BUTTON }; -enum InputsSource { FREE_FORM_INPUT, OPTION }; +enum class InputsSource { + FREE_FORM_INPUT, + OPTION +}; + +enum class DisturbMode { + ALLOW_UNKNOWN, + ALLOW_ALL, + ALLOW_PRIORITY, + ALLOW_NONE, + ALLOW_ALARMS +}; -enum DisturbMode { ALLOW_UNKNOWN, ALLOW_ALL, ALLOW_PRIORITY, ALLOW_NONE, ALLOW_ALARMS }; +enum class InputEditType { + EDIT_AUTO, + EDIT_DISABLED, + EDIT_ENABLED +}; -enum InputEditType { EDIT_AUTO, EDIT_DISABLED, EDIT_ENABLED }; +enum class DoNotDisturbType { + TYPE_NONE, TYPE_ONCE, + TYPE_DAILY, TYPE_CLEARLY +}; -enum DoNotDisturbType { TYPE_NONE, TYPE_ONCE, TYPE_DAILY, TYPE_CLEARLY }; +enum class SourceType { + TYPE_NORMAL = 0x00000000, + TYPE_CONTINUOUS = 0x00000001, + TYPE_TIMER = 0x00000002 +}; struct NotificationSubscribeInfo { std::vector bundleNames; @@ -96,13 +117,13 @@ struct NotificationSubscribeInfo { }; struct BundleOption { - std::string bundle{}; - int uid{}; + std::string bundle {}; + int uid {}; }; struct NotificationKey { - int id{}; - std::string label{}; + int id {}; + std::string label {}; }; struct CallbackPromiseInfo { @@ -118,7 +139,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); @@ -145,10 +166,22 @@ public: 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 SetNotificationSortingMap( const napi_env &env, const std::shared_ptr &sortingMap, napi_value &result); @@ -160,29 +193,33 @@ 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 enum 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); @@ -192,6 +229,54 @@ public: 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); @@ -200,6 +285,90 @@ public: 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 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 GetNotificationSlotByCustom(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 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, BundleOption &option); @@ -223,6 +392,8 @@ public: static bool DoNotDisturbTypeCToJS(const NotificationConstant::DoNotDisturbType &inType, DoNotDisturbType &outType); + static bool SourceTypeCToJS(const NotificationConstant::SourceType &inType, SourceType &outType); + static napi_value CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent); private: diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 0db4a19..da6458c 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -26,66 +26,14 @@ 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); -static napi_value GetNotificationGroupName( - const napi_env &env, const napi_value &value, NotificationRequest &request); + 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); @@ -134,14 +82,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, info.errorCode, result); } - ANS_LOGI("ReturnCallbackPromise end"); + ANS_LOGI("end"); } void Common::SetCallback( @@ -222,18 +169,18 @@ napi_value Common::ParseParaOnlyCallback(const napi_env &env, const napi_callbac } 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 @@ -256,34 +203,66 @@ napi_value Common::SetNotification( napi_create_int32(env, notification->GetPid(), &value); napi_set_named_property(env, result, "creatorPid", value); - return NapiGetboolean(env, true); + // readonly isRemoveAllowed?: boolean + napi_get_boolean(env, notification->IsRemoveAllowed(), &value); + napi_set_named_property(env, result, "isRemoveAllowed", value); + + // readonly source?: number + enum 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); + + 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 @@ -293,11 +272,50 @@ napi_value Common::SetNotificationRequest( // slotType?: SlotType enum 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); @@ -306,18 +324,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) { @@ -328,15 +373,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; @@ -346,7 +383,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; @@ -356,68 +393,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; @@ -432,7 +421,7 @@ napi_value Common::SetNotificationRequest( } } - // largeIcon ?: image.PixelMap + // largeIcon?: image.PixelMap std::shared_ptr largeIcon = request->GetBigIcon(); if (largeIcon) { napi_value largeIconResult = nullptr; @@ -447,36 +436,104 @@ napi_value Common::SetNotificationRequest( } } - // groupName?: string - napi_create_string_utf8(env, request->GetGroupName().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "groupName", value); + return NapiGetBoolean(env, true); +} - // readonly creatorBundleName?: string - napi_create_string_utf8(env, request->GetCreatorBundleName().c_str(), NAPI_AUTO_LENGTH, &value); - napi_set_named_property(env, result, "creatorBundleName", value); +napi_value Common::SetNotificationRequestByCustom( + const napi_env &env, const OHOS::Notification::NotificationRequest *request, napi_value &result) +{ + ANS_LOGI("enter"); - // readonly creatorUid?: number - napi_create_int32(env, request->GetCreatorUid(), &value); - napi_set_named_property(env, result, "creatorUid", value); + if (request == nullptr) { + ANS_LOGE("request is nullptr"); + return NapiGetBoolean(env, false); + } - // readonly creatorPid?: number - napi_create_int32(env, request->GetCreatorPid(), &value); - napi_set_named_property(env, result, "creatorPid", value); + // 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); + + return NapiGetBoolean(env, true); +} - 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("SetNotificationSortingMap start"); + ANS_LOGI("enter"); if (sortingMap == nullptr) { ANS_LOGE("sortingMap is null"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } if (sortingMap->GetKey().size() == 0) { ANS_LOGE("sortingMap GetKey().size is empty"); - return NapiGetboolean(env, false); + return NapiGetBoolean(env, false); } size_t count = 0; @@ -498,7 +555,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++; @@ -509,12 +566,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; @@ -522,7 +579,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); @@ -554,7 +611,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) @@ -565,17 +622,17 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl // type: SlotType enum 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 }; 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 @@ -622,107 +679,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 enum 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); - } - - 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); + return ret; } - 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); @@ -735,25 +784,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); @@ -766,25 +821,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); @@ -801,30 +861,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); @@ -835,20 +901,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); @@ -856,28 +911,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); @@ -897,47 +959,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); @@ -946,6 +1051,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); @@ -954,24 +1068,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; @@ -985,7 +1091,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); @@ -999,13 +1105,107 @@ 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::SetNotificationActionButtonByExtras( + const napi_env &env, const std::shared_ptr &actionButton, napi_value &result) +{ + ANS_LOGI("enter"); + + // extras?: {[key: string]: any} + std::shared_ptr extras = nullptr; + if (extras) { + napi_value nExtras = nullptr; + nExtras = OHOS::AppExecFwk::WrapWantParams(env, *extras); + napi_set_named_property(env, result, "extras", nExtras); + } + return NapiGetBoolean(env, true); +} + +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]: any} + std::shared_ptr additionalData = nullptr; + 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( @@ -1013,32 +1213,34 @@ napi_value Common::SetDoNotDisturbDate( { ANS_LOGI("enter"); enum DoNotDisturbType outType = DoNotDisturbType::TYPE_NONE; - if (DoNotDisturbTypeCToJS(date.GetDoNotDisturbType(), outType)) { - // type:DoNotDisturbType - napi_value typeNapi = nullptr; - napi_create_int32(env, 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); - } else { - return NapiGetboolean(env, false); + if (!DoNotDisturbTypeCToJS(date.GetDoNotDisturbType(), outType)) { + return NapiGetBoolean(env, false); } - return NapiGetboolean(env, true); + + // 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; @@ -1080,144 +1282,157 @@ 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) { + if (GetNotificationId(env, value, request) == nullptr) { return nullptr; } - - // slotType?: notification.SlotType - if (GetSlotType(env, value, request) == nullptr) { + // deliveryTime?: number + if (GetNotificationDeliveryTime(env, value, request) == nullptr) { return nullptr; } - - // isOngoing?: boolean - if (GetNotificationIsOngoing(env, value, request) == nullptr) { + // autoDeletedTime?: number + if (GetNotificationAutoDeletedTime(env, value, request) == nullptr) { return nullptr; } - - // isUnremovable?: boolean - if (GetNotificationIsUnremovable(env, value, request) == nullptr) { + // color?: number + if (GetNotificationColor(env, value, request) == nullptr) { return nullptr; } - - // deliveryTime?: number - if (GetNotificationDeliveryTime(env, value, request) == nullptr) { + // badgeIconStyle?: number + if (GetNotificationBadgeIconStyle(env, value, request) == nullptr) { return nullptr; } + return NapiGetNull(env); +} - // tapDismissed?: boolean - if (GetNotificationtapDismissed(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; } - - // wantAgent?: WantAgent - if (GetNotificationWantAgent(env, value, request) == nullptr) { + // statusBarText?: string + if (GetNotificationStatusBarText(env, value, request) == nullptr) { return nullptr; } - - // extraInfo?: {[key: string]: any} - if (GetNotificationExtraInfo(env, value, request) == nullptr) { + // label?: string + if (GetNotificationLabel(env, value, request) == nullptr) { return nullptr; } - - // removalWantAgent?: WantAgent - if (GetNotificationRemovalWantAgent(env, value, request) == nullptr) { + // groupName?: string + if (GetNotificationGroupName(env, value, request) == nullptr) { return nullptr; } + return NapiGetNull(env); +} - // maxScreenWantAgent?: WantAgent - if (GetNotificationMaxScreenWantAgent(env, value, request) == nullptr) { - return nullptr; - } - - // 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; } + return NapiGetNull(env); +} - // groupName?: string - if (GetNotificationGroupName(env, value, request) == nullptr) { +napi_value Common::GetNotificationRequest(const napi_env &env, const napi_value &value, NotificationRequest &request) +{ + ANS_LOGI("enter"); + if (!GetNotificationRequestByNumber(env, value, request)) { return nullptr; } - - return Common::NapiGetNull(env); + 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"); @@ -1233,16 +1448,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"); @@ -1259,16 +1474,17 @@ napi_value GetSlotType(const napi_env &env, const napi_value &value, Notificatio napi_get_value_int32(env, result, &slotType); enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + 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) @@ -1281,10 +1497,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)); @@ -1322,18 +1535,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"); @@ -1351,10 +1560,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"); @@ -1372,10 +1582,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"); @@ -1393,10 +1604,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"); @@ -1414,7 +1626,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) @@ -1440,10 +1652,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"); @@ -1465,10 +1677,10 @@ napi_value GetNotificationExtraInfo(const napi_env &env, const napi_value &value request.SetAdditionalData(extras); } - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationGroupName(const napi_env &env, const napi_value &value, NotificationRequest &request) +napi_value Common::GetNotificationGroupName(const napi_env &env, const napi_value &value, NotificationRequest &request) { ANS_LOGI("enter"); @@ -1487,10 +1699,11 @@ napi_value GetNotificationGroupName(const napi_env &env, const napi_value &value request.SetGroupName(str); } - return Common::NapiGetNull(env); + 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"); @@ -1513,10 +1726,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"); @@ -1539,10 +1753,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"); @@ -1560,10 +1775,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"); @@ -1582,10 +1798,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"); @@ -1604,10 +1820,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"); @@ -1625,10 +1842,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"); @@ -1646,10 +1864,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"); @@ -1667,10 +1886,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"); @@ -1688,10 +1908,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"); @@ -1710,10 +1931,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"); @@ -1732,10 +1953,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"); @@ -1753,10 +1975,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"); @@ -1774,10 +1997,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"); @@ -1785,17 +2008,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) { @@ -1813,82 +2027,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"); @@ -1896,60 +2116,368 @@ 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); } - - 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_value contentResult = nullptr; napi_valuetype valuetype = napi_undefined; + napi_value userInputResult = nullptr; bool hasProperty = false; - NAPI_CALL(env, napi_has_named_property(env, result, "contentType", &hasProperty)); - if (!hasProperty) { - ANS_LOGE("Property contentType expected."); - return 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; - napi_get_named_property(env, result, "contentType", &contentResult); - NAPI_CALL(env, napi_typeof(env, contentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, contentResult, &type); + if (!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 Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +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 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)); + // 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; + } + + return NapiGetNull(env); +} + +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 value = nullptr; + bool hasProperty = false; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); + return nullptr; + } + + // tag: string + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "tag", &hasProperty)); + if (hasProperty) { + 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); + } + + 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; + } + + // options: Array + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "options", &hasProperty)); + if (hasProperty) { + 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, option, str, STR_MAX_SIZE - 1, &strLen)); + options.emplace_back(str); + } + userInput->SetOptions(options); + } + return NapiGetNull(env); +} + +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 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; + } + + // permitMimeTypes?: Array + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "permitMimeTypes", &hasProperty)); + if (hasProperty) { + 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); + } + } + + 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; + } + + // permitFreeFormInput?: boolean + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "permitFreeFormInput", &hasProperty)); + if (hasProperty) { + 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); + } + + return NapiGetNull(env); +} + +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; + } + + // editType?: number + NAPI_CALL(env, napi_has_named_property(env, userInputResult, "editType", &hasProperty)); + if (hasProperty) { + 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)); + } + return NapiGetNull(env); +} + +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 result = nullptr; + bool hasProperty = false; + + if (!userInput) { + ANS_LOGE("userInput is nullptr"); + return nullptr; + } + + // additionalData?: {[key: string]: any} + 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; + } + } + + 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::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 normalContent = std::make_shared(); @@ -1958,62 +2486,68 @@ napi_value GetNotificationBasicContent(const napi_env &env, const napi_value &re 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."); + 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)); - normalContent->SetText(str); - ANS_LOGI("normal::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)); - normalContent->SetAdditionalText(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); } - 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::GetNotificationLongTextContent( + const napi_env &env, const napi_value &result, NotificationRequest &request) { ANS_LOGI("enter"); napi_valuetype valuetype = napi_undefined; napi_value contentResult = nullptr; - napi_value longContentResult = nullptr; - napi_value basicContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; - char long_str[LONG_STR_MAX_SIZE + 1] = {0}; - size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "longText", &hasProperty)); NAPI_ASSERT(env, hasProperty, "Property longText expected."); @@ -2029,103 +2563,73 @@ napi_value GetNotificationLongTextContent(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)); - longContent->SetTitle(str); - ANS_LOGI("longText::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); + if (GetNotificationLongTextContentDetailed(env, contentResult, longContent) == nullptr) { 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)); - longContent->SetText(str); - ANS_LOGI("longText::text = %{public}s", str); - } else { - ANS_LOGE("Property text expected."); - return nullptr; - } + request.SetContent(std::make_shared(longContent)); - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetAdditionalText(str); - ANS_LOGI("longText::additionalText = %{public}s", str); + return 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)); - 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; - } + 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)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "briefText", &longContentResult); - NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetBriefText(str); - ANS_LOGI("longText::briefText = %{public}s", str); - } else { - ANS_LOGE("Property briefText expected."); - return nullptr; - } + 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", &longContentResult); - NAPI_CALL(env, napi_typeof(env, longContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, longContentResult, str, STR_MAX_SIZE - 1, &strLen)); - longContent->SetExpandedTitle(str); - ANS_LOGI("longText::expandedTitle = %{public}s", str); - } else { - ANS_LOGE("Property expandedTitle expected."); - return nullptr; - } - - request.SetContent(std::make_shared(longContent)); + 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 Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetNotificationPictureContent(const napi_env &env, const napi_value &result, NotificationRequest &request) +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; - napi_value pictureContentResult = nullptr; - napi_value basicContentResult = nullptr; bool hasProperty = false; - char str[STR_MAX_SIZE] = {0}; - size_t strLen = 0; NAPI_CALL(env, napi_has_named_property(env, result, "picture", &hasProperty)); NAPI_ASSERT(env, hasProperty, "Property picture expected."); @@ -2139,241 +2643,305 @@ napi_value GetNotificationPictureContent(const napi_env &env, const napi_value & ANS_LOGE("pictureContent is null"); return nullptr; } + if (GetNotificationPictureContentDetailed(env, contentResult, pictureContent) == 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)); - pictureContent->SetTitle(str); - ANS_LOGI("pictureText::title = %{public}s", str); - } else { - ANS_LOGE("Property title expected."); + 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; } - // 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."); + // 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)); + 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; } - // additionalText?: string - NAPI_CALL(env, napi_has_named_property(env, contentResult, "additionalText", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "additionalText", &basicContentResult); - NAPI_CALL(env, napi_typeof(env, basicContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); - NAPI_CALL(env, napi_get_value_string_utf8(env, basicContentResult, str, STR_MAX_SIZE - 1, &strLen)); - pictureContent->SetAdditionalText(str); - ANS_LOGI("pictureText::additionalText = %{public}s", str); + if (GetNotificationBasicContentDetailed(env, contentResult, conversationalContent) == nullptr) { + return nullptr; } - - // 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."); + if (GetNotificationConversationalContentTitle(env, contentResult, conversationalContent) == nullptr) { return nullptr; } - - // 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."); + if (GetNotificationConversationalContentGroup(env, contentResult, conversationalContent) == nullptr) { + return nullptr; + } + if (GetNotificationConversationalContentMessages(env, contentResult, conversationalContent) == nullptr) { return nullptr; } - // picture: image.PixelMap - NAPI_CALL(env, napi_has_named_property(env, contentResult, "picture", &hasProperty)); - if (hasProperty) { - napi_get_named_property(env, contentResult, "picture", &pictureContentResult); - NAPI_CALL(env, napi_typeof(env, pictureContentResult, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); - std::shared_ptr pixelMap = nullptr; - pixelMap = Media::PixelMapNapi::GetPixelMap(env, pictureContentResult); - if (pixelMap == nullptr) { - ANS_LOGE("Invalid object pixelMap"); - return nullptr; - } - pictureContent->SetBigPicture(pixelMap); - } else { - ANS_LOGE("Property picture expected."); + 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; } - request.SetContent(std::make_shared(pictureContent)); - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetMessageUser(const napi_env &env, const napi_value &result, MessageUser &messageUser) +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; - // 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; - } + // 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); - // 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; - } + return NapiGetNull(env); +} - // 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; +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 message = nullptr; + if (!GetConversationalMessage(env, conversationalMessage, message)) { + return nullptr; + } + conversationalContent->AddConversationalMessage(message); } - // 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."); + 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; } - - // 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."); + if (GetConversationalMessageOtherInfo(env, conversationalMessage, message) == nullptr) { return nullptr; } - - return Common::NapiGetNull(env); + return NapiGetNull(env); } -napi_value GetConversationalMessage(const napi_env &env, const napi_value &conversationalMessage, +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; - 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."); - } + 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); // 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."); + 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); + + // 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; + } + + message = std::make_shared(text, timestamp, sender); + if (!message) { + ANS_LOGE("Failed to create NotificationConversationalMessage object"); + return nullptr; } + return NapiGetNull(env); +} + +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 mimeType; + std::string uri; + // 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; @@ -2383,184 +2951,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; @@ -2578,90 +3109,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"); @@ -2689,48 +3173,36 @@ 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; - NAPI_CALL(env, napi_has_named_property(env, value, "type", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property type expected."); - napi_get_named_property(env, value, "type", &nobj); - NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, nobj, &slotType); - enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - if (!SlotTypeJSToC(SlotType(slotType), outType)) { + if (GetNotificationSlotByString(env, value, slot) == nullptr) { return nullptr; } - slot.SetType(outType); + if (GetNotificationSlotByNumber(env, value, slot) == nullptr) { + return nullptr; + } + if (GetNotificationSlotByCustom(env, value, slot) == nullptr) { + return nullptr; + } + if (GetNotificationSlotByBool(env, value, slot) == nullptr) { + return nullptr; + } + return NapiGetNull(env); +} - // 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); +napi_value Common::GetNotificationSlotByString(const napi_env &env, const napi_value &value, NotificationSlot &slot) +{ + ANS_LOGI("enter"); - NotificationSlot::NotificationLevel outLevel {NotificationSlot::NotificationLevel::LEVEL_NONE}; - if (!SlotLevelJSToC(SlotLevel(inLevel), outLevel)) { - return nullptr; - } - slot.SetLevel(outLevel); - } + 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)); @@ -2746,6 +3218,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) { @@ -2770,32 +3266,6 @@ 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)); - } - - // 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)); - } - // lightEnabled?: boolean NAPI_CALL(env, napi_has_named_property(env, value, "lightEnabled", &hasProperty)); if (hasProperty) { @@ -2808,6 +3278,57 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va slot.SetEnableLight(lightEnabled); } + // 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::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) { + 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 (!Common::SlotLevelJSToC(SlotLevel(inLevel), outLevel)) { + return nullptr; + } + slot.SetLevel(outLevel); + } + + // 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)); + } + // lightColor?: number NAPI_CALL(env, napi_has_named_property(env, value, "lightColor", &hasProperty)); if (hasProperty) { @@ -2819,6 +3340,30 @@ 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::GetNotificationSlotByCustom(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; + + // type: notification.SlotType + int slotType = 0; + NAPI_CALL(env, napi_has_named_property(env, value, "type", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + napi_get_named_property(env, value, "type", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &slotType); + enum NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + slot.SetType(outType); // vibrationValues?: Array NAPI_CALL(env, napi_has_named_property(env, value, "vibrationValues", &hasProperty)); @@ -2843,18 +3388,6 @@ 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); } @@ -2935,6 +3468,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; @@ -2957,6 +3493,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; @@ -3067,31 +3606,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); @@ -3144,6 +3683,25 @@ bool Common::DoNotDisturbTypeCToJS(const NotificationConstant::DoNotDisturbType return true; } +bool Common::SourceTypeCToJS(const NotificationConstant::SourceType &inType, SourceType &outType) +{ + switch (inType) { + case NotificationConstant::SourceType::TYPE_NORMAL: + outType = SourceType::TYPE_NORMAL; + break; + case NotificationConstant::SourceType::TYPE_CONTINUOUS: + outType = SourceType::TYPE_CONTINUOUS; + break; + case NotificationConstant::SourceType::TYPE_TIMER: + outType = SourceType::TYPE_TIMER; + break; + default: + ANS_LOGE("SourceType %{public}d is an invalid value", inType); + return false; + } + return true; +} + napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_ptr &agent) { if (agent == nullptr) { @@ -3189,4 +3747,4 @@ napi_value Common::CreateWantAgentByJS(const napi_env &env, const std::shared_pt return wantAgent; } } // namespace NotificationNapi -} // namespace OHOS +} // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index e3946a9..96e3e42 100644 --- a/interfaces/kits/napi/ans/src/constant.cpp +++ b/interfaces/kits/napi/ans/src/constant.cpp @@ -35,19 +35,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 +68,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 +89,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 +110,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 +144,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 +162,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 +183,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 +203,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), @@ -215,10 +228,10 @@ napi_value DoNotDisturbTypeInit(napi_env env, napi_value exports) napi_value obj = nullptr; napi_create_object(env, &obj); - SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_NONE, "TYPE_NONE"); - SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_ONCE, "TYPE_ONCE"); - SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_DAILY, "TYPE_DAILY"); - SetNamedPropertyByInteger(env, obj, DoNotDisturbType::TYPE_CLEARLY, "TYPE_CLEARLY"); + 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), @@ -228,6 +241,25 @@ napi_value DoNotDisturbTypeInit(napi_env env, napi_value exports) 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); @@ -238,9 +270,9 @@ napi_value ConstantInit(napi_env env, napi_value exports) DoNotDisturbMode(env, exports); InputEditTypeInit(env, exports); ContentTypeInit(env, exports); + SourceTypeInit(env, exports); DoNotDisturbTypeInit(env, exports); return exports; } - } // namespace NotificationNapi } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index ee5de83..4056542 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -49,12 +49,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 @@ -62,7 +62,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); @@ -71,7 +71,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); @@ -80,7 +80,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); @@ -109,7 +109,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() diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index a476c59..921ad9d 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -107,6 +107,8 @@ public: const sptr &bundleOption, const std::string &groupName) 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; // SystemEvent void OnBundleRemoved(const sptr &bundleOption); @@ -146,9 +148,10 @@ private: void UpdateRecentNotification(sptr ¬ification, bool isDelete, int reason); void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); + bool CheckPermission(const std::string &bundleName); + ErrCode PrepereLongTaskNotificationRequest(const sptr &request, const int &uid); private: - bool CheckPermission(const std::string &bundleName); static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 538f26b..7cc5233 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -379,7 +379,6 @@ 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; @@ -972,6 +971,9 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } if (((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid())) && (record->notification->GetLabel() == label) && (record->notification->GetId() == notificationId)) { @@ -991,6 +993,9 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( const std::string &key, sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } if (record->notification->GetKey() == key) { if (!isCancel && record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; @@ -1273,6 +1278,85 @@ ErrCode AdvancedNotificationService::ShellDump(const std::string &dumpOption, st return result; } +ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const sptr &request) +{ + ANS_LOGD("%{public}s", __FUNCTION__); + + int uid = IPCSkeleton::GetCallingUid(); + if (uid != SYSTEM_SERVICE_UID) { + return ERR_ANS_NOT_SYSTEM_SERVICE; + } + + sptr bundleOption = nullptr; + bundleOption = new NotificationBundleOption(std::string(), uid); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + + ErrCode result = PrepereLongTaskNotificationRequest(request, uid); + if (result != ERR_OK) { + return result; + } + + 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); + record->notification->SetRemoveAllowed(false); + } + + 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::CANCEL_REASON_DELETE; + UpdateRecentNotification(notification, true, reason); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); + } + })); + return result; +} + ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vector &dumpInfo) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -1550,6 +1634,9 @@ ErrCode AdvancedNotificationService::RemoveNotification( sptr notification = nullptr; for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid()) && (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) { @@ -1595,6 +1682,10 @@ 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()) { removeList.push_back(record); @@ -1903,5 +1994,16 @@ bool AdvancedNotificationService::CheckPermission(const std::string &bundleName) // Add permission check in future return true; } + +ErrCode AdvancedNotificationService::PrepereLongTaskNotificationRequest( + const sptr &request, const int &uid) +{ + int pid = IPCSkeleton::GetCallingPid(); + request->SetCreatorUid(uid); + request->SetCreatorPid(pid); + + ErrCode result = CheckPictureSize(request); + return result; +} } // 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 1d6b79c..1b51ab0 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" @@ -1557,5 +1558,74 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10900, EXPECT_EQ(result->GetBeginDate(), beginDate); EXPECT_EQ(result->GetEndDate(), endDate); } + +/** + * @tc.number : ANS_Publish_01500 + * @tc.name : ANSPublish01500 + * @tc.desc : publish a long 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 long 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 -- Gitee From 81971659d849ba9c33df120c10753e685697aec3 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 2 Dec 2021 11:10:04 +0000 Subject: [PATCH 035/131] Fix code Signed-off-by: zhaoyuan17 --- frameworks/ans/core/src/ans_manager_stub.cpp | 6 +++-- interfaces/kits/napi/ans/include/common.h | 10 ++++---- interfaces/kits/napi/ans/src/common.cpp | 24 ++++++++++---------- 3 files changed, 21 insertions(+), 19 deletions(-) diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 7fac8fd..20a8c87 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -189,10 +189,12 @@ const std::map &content, napi_value &result); - static napi_value SetNotificationContentDetailed(const napi_env &env, const enum ContentType &type, + 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, const NotificationBasicContent *basicContent, napi_value &result); @@ -374,13 +374,13 @@ public: 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); diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index da6458c..66e77b0 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -208,7 +208,7 @@ napi_value Common::SetNotification( napi_set_named_property(env, result, "isRemoveAllowed", value); // readonly source?: number - enum SourceType sourceType = SourceType::TYPE_NORMAL; + SourceType sourceType = SourceType::TYPE_NORMAL; if (!SourceTypeCToJS(notification->GetSourceType(), sourceType)) { return NapiGetBoolean(env, false); } @@ -270,7 +270,7 @@ napi_value Common::SetNotificationRequestByNumber( 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); } @@ -620,7 +620,7 @@ 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); } @@ -628,7 +628,7 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl 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); } @@ -682,7 +682,7 @@ napi_value Common::SetNotificationSlot(const napi_env &env, const NotificationSl return NapiGetBoolean(env, true); } -napi_value Common::SetNotificationContentDetailed(const napi_env &env, const enum ContentType &type, +napi_value Common::SetNotificationContentDetailed(const napi_env &env, const ContentType &type, const std::shared_ptr &content, napi_value &result) { ANS_LOGI("enter"); @@ -1212,7 +1212,7 @@ napi_value Common::SetDoNotDisturbDate( const napi_env &env, const NotificationDoNotDisturbDate &date, napi_value &result) { ANS_LOGI("enter"); - enum DoNotDisturbType outType = DoNotDisturbType::TYPE_NONE; + DoNotDisturbType outType = DoNotDisturbType::TYPE_NONE; if (!DoNotDisturbTypeCToJS(date.GetDoNotDisturbType(), outType)) { return NapiGetBoolean(env, false); } @@ -1473,7 +1473,7 @@ napi_value Common::GetNotificationSlotType(const napi_env &env, const napi_value 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; + NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; if (!SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } @@ -3359,7 +3359,7 @@ napi_value Common::GetNotificationSlotByCustom(const napi_env &env, const napi_v 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; + NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { return nullptr; } @@ -3453,7 +3453,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: @@ -3478,7 +3478,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: @@ -3503,7 +3503,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: @@ -3526,7 +3526,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: -- Gitee From 9f5cb6f605fedff0b5d0c619e6eee6180e7f011b Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 2 Dec 2021 15:46:27 +0000 Subject: [PATCH 036/131] Fix bug Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/include/common.h | 2 +- interfaces/kits/napi/ans/src/common.cpp | 59 ++++++++++++----------- 2 files changed, 33 insertions(+), 28 deletions(-) diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index eb17a72..6450f8c 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -288,7 +288,7 @@ public: 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 GetNotificationSlotByCustom(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); diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 66e77b0..3e67eac 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -3180,13 +3180,31 @@ napi_value Common::GetNotificationSlot(const napi_env &env, const napi_value &va { ANS_LOGI("enter"); + napi_value nobj = nullptr; + napi_valuetype valuetype = napi_undefined; + bool hasProperty = false; + + // type: notification.SlotType + int slotType = 0; + NAPI_CALL(env, napi_has_named_property(env, value, "type", &hasProperty)); + NAPI_ASSERT(env, hasProperty, "Property type expected."); + napi_get_named_property(env, value, "type", &nobj); + NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); + NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); + napi_get_value_int32(env, nobj, &slotType); + NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; + if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { + return nullptr; + } + slot.SetType(outType); + if (GetNotificationSlotByString(env, value, slot) == nullptr) { return nullptr; } if (GetNotificationSlotByNumber(env, value, slot) == nullptr) { return nullptr; } - if (GetNotificationSlotByCustom(env, value, slot) == nullptr) { + if (GetNotificationSlotByVibration(env, value, slot) == nullptr) { return nullptr; } if (GetNotificationSlotByBool(env, value, slot) == nullptr) { @@ -3278,17 +3296,6 @@ napi_value Common::GetNotificationSlotByBool(const napi_env &env, const napi_val slot.SetEnableLight(lightEnabled); } - // 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); } @@ -3343,7 +3350,7 @@ napi_value Common::GetNotificationSlotByNumber(const napi_env &env, const napi_v return NapiGetNull(env); } -napi_value Common::GetNotificationSlotByCustom(const napi_env &env, const napi_value &value, NotificationSlot &slot) +napi_value Common::GetNotificationSlotByVibration(const napi_env &env, const napi_value &value, NotificationSlot &slot) { ANS_LOGI("enter"); napi_value nobj = nullptr; @@ -3351,20 +3358,6 @@ napi_value Common::GetNotificationSlotByCustom(const napi_env &env, const napi_v bool hasProperty = false; uint32_t length = 0; - // type: notification.SlotType - int slotType = 0; - NAPI_CALL(env, napi_has_named_property(env, value, "type", &hasProperty)); - NAPI_ASSERT(env, hasProperty, "Property type expected."); - napi_get_named_property(env, value, "type", &nobj); - NAPI_CALL(env, napi_typeof(env, nobj, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_number, "Wrong argument type. Number expected."); - napi_get_value_int32(env, nobj, &slotType); - NotificationConstant::SlotType outType = NotificationConstant::SlotType::OTHER; - if (!Common::SlotTypeJSToC(SlotType(slotType), outType)) { - return nullptr; - } - slot.SetType(outType); - // vibrationValues?: Array NAPI_CALL(env, napi_has_named_property(env, value, "vibrationValues", &hasProperty)); if (hasProperty) { @@ -3388,6 +3381,18 @@ napi_value Common::GetNotificationSlotByCustom(const napi_env &env, const napi_v 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); } -- Gitee From f7e4e962a948e41177626502deb3aa499e8f0c05 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 2 Dec 2021 16:10:38 +0000 Subject: [PATCH 037/131] Fix codex Signed-off-by: zhaoyuan17 --- interfaces/kits/napi/ans/include/common.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 6450f8c..94f053a 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -288,7 +288,8 @@ public: 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 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); -- Gitee From 109d1779b63009b1e06b64ab85a2ff6fd61cfb99 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Fri, 3 Dec 2021 14:36:32 +0000 Subject: [PATCH 038/131] Modify name Signed-off-by: zhaoyuan17 --- .../ans/core/include/ans_notification.h | 12 +-- .../test/moduletest/ans_fw_module_test.cpp | 91 +++++++++++++++++-- .../ans/native/include/notification_helper.h | 12 +-- .../include/advanced_notification_service.h | 3 +- .../ans/src/advanced_notification_service.cpp | 32 +++++-- .../advanced_notification_service_test.cpp | 4 +- 6 files changed, 122 insertions(+), 32 deletions(-) diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index 0f879f0..54d4811 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -619,19 +619,19 @@ public: ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); /** - * Publishes a long task notification. + * Publishes a continuous task notification. * @param request Indicates the NotificationRequest object for setting the notification content. * This parameter must be specified. - * @return Returns publish long task notification result. + * @return Returns publish continuous task notification result. */ ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); /** - * Cancels a published long task notification matching the specified label and notificationId. + * Cancels a published continuous task notification matching the specified label and notificationId. * - * @param label Indicates the label of the long task notification to cancel. - * @param notificationId Indicates the ID of the long task notification to cancel. - * @return Returns cancel long task notification result. + * @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); diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index ef727d9..aeed692 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -88,15 +88,13 @@ public: ~OnSubscribeResultEvent() override {} - OnSubscribeResultEvent() - : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT) + OnSubscribeResultEvent() : SubscriberEvent(SubscriberEventType::ON_SUBSCRIBERESULT) {} }; class OnUnSubscribeResultEvent : public SubscriberEvent { public: - OnUnSubscribeResultEvent() - : SubscriberEvent(SubscriberEventType::ON_UNSUBSCRIBERESULT) + OnUnSubscribeResultEvent() : SubscriberEvent(SubscriberEventType::ON_UNSUBSCRIBERESULT) {} ~OnUnSubscribeResultEvent() override @@ -132,8 +130,7 @@ private: class OnDoNotDisturbDateChangedEvent : public SubscriberEvent { public: - explicit OnDoNotDisturbDateChangedEvent( - const std::shared_ptr &date) + explicit OnDoNotDisturbDateChangedEvent(const std::shared_ptr &date) : SubscriberEvent(SubscriberEventType::ON_DND_CHANGED), date_(date) {} @@ -1352,10 +1349,10 @@ static NotificationDoNotDisturbDate GetDoNotDisturbDateInstance( 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 beginMs = beginDur.count(); auto endDur = beginDur + std::chrono::hours(intervalHours); - auto endMs = endDur.count(); + auto endMs = endDur.count(); return {type, beginMs, endMs}; } @@ -1603,7 +1600,7 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishLongTask_07200, Function | Med 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_ANS_NOTIFICATION_NOT_EXISTS); + 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); @@ -1726,5 +1723,81 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishLongTask_07600, Function | Med subscriber.ClearEvents(); IPCSkeleton::SetCallingUid(1); } + +HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishLongTask_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_PulbishLongTask_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 diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index cbc3d46..0395b63 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -614,19 +614,19 @@ public: static ErrCode DoesSupportDoNotDisturbMode(bool &doesSupport); /** - * Publishes a long task notification. + * Publishes a continuous task notification. * @param request Indicates the NotificationRequest object for setting the notification content. * This parameter must be specified. - * @return Returns publish long task notification result. + * @return Returns publish continuous task notification result. */ static ErrCode PublishContinuousTaskNotification(const NotificationRequest &request); /** - * Cancels a published long task notification matching the specified label and notificationId. + * Cancels a published continuous task notification matching the specified label and notificationId. * - * @param label Indicates the label of the long task notification to cancel. - * @param notificationId Indicates the ID of the long task notification to cancel. - * @return Returns cancel long task notification result. + * @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); }; diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 921ad9d..176224e 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -129,6 +129,7 @@ private: 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(); @@ -149,7 +150,7 @@ private: void AdjustDateForDndTypeOnce(int64_t &beginDate, int64_t &endDate); bool CheckPermission(const std::string &bundleName); - ErrCode PrepereLongTaskNotificationRequest(const sptr &request, const int &uid); + ErrCode PrepereContinuousTaskNotificationRequest(const sptr &request, const int &uid); private: static sptr instance_; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 7cc5233..3deb150 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -781,7 +781,7 @@ ErrCode AdvancedNotificationService::DeleteAll() for (auto key : keys) { sptr notification = nullptr; - result = RemoveFromNotificationList(key, notification); + result = RemoveFromNotificationListForDeleteAll(key, notification); if (result != ERR_OK) { continue; } @@ -993,7 +993,7 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( const std::string &key, sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { - if (!record->notification->IsRemoveAllowed()) { + if (!record->notification->IsRemoveAllowed() && isCancel) { continue; } if (record->notification->GetKey() == key) { @@ -1009,6 +1009,26 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( return ERR_ANS_NOTIFICATION_NOT_EXISTS; } +ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll( + const std::string &key, sptr ¬ification) +{ + for (auto record : notificationList_) { + if (!record->notification->IsRemoveAllowed()) { + continue; + } + if (record->notification->GetKey() == key) { + if (record->request->IsUnremovable()) { + return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + } + notification = record->notification; + notificationList_.remove(record); + return ERR_OK; + } + } + + return ERR_ANS_NOTIFICATION_NOT_EXISTS; +} + ErrCode AdvancedNotificationService::Subscribe( const sptr &subscriber, const sptr &info) { @@ -1293,7 +1313,7 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt return ERR_ANS_INVALID_BUNDLE; } - ErrCode result = PrepereLongTaskNotificationRequest(request, uid); + ErrCode result = PrepereContinuousTaskNotificationRequest(request, uid); if (result != ERR_OK) { return result; } @@ -1634,9 +1654,6 @@ ErrCode AdvancedNotificationService::RemoveNotification( sptr notification = nullptr; for (auto record : notificationList_) { - if (!record->notification->IsRemoveAllowed()) { - continue; - } if ((record->bundleOption->GetBundleName() == bundle->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid()) && (record->notification->GetId() == notificationId) && (record->notification->GetLabel() == label)) { @@ -1694,7 +1711,6 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptrnotification != nullptr) { int reason = NotificationConstant::CANCEL_REASON_DELETE; UpdateRecentNotification(record->notification, true, reason); @@ -1995,7 +2011,7 @@ bool AdvancedNotificationService::CheckPermission(const std::string &bundleName) return true; } -ErrCode AdvancedNotificationService::PrepereLongTaskNotificationRequest( +ErrCode AdvancedNotificationService::PrepereContinuousTaskNotificationRequest( const sptr &request, const int &uid) { int pid = IPCSkeleton::GetCallingPid(); diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index 1b51ab0..f4693c9 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -1562,7 +1562,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_10900, /** * @tc.number : ANS_Publish_01500 * @tc.name : ANSPublish01500 - * @tc.desc : publish a long task notification + * @tc.desc : publish a continuous task notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11000, Function | SmallTest | Level1) { @@ -1578,7 +1578,7 @@ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11000, /** * @tc.number : ANS_Publish_01600 * @tc.name : ANSPublish01600 - * @tc.desc : publish a long task notification + * @tc.desc : publish a continuous task notification */ HWTEST_F(AdvancedNotificationServiceTest, AdvancedNotificationServiceTest_11100, Function | SmallTest | Level1) { -- Gitee From dc26470a85f69eb5b1908a6dc422122b9ee2a97b Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sat, 4 Dec 2021 11:22:58 +0000 Subject: [PATCH 039/131] Added access control test cases Signed-off-by: zhaoyuan17 --- test/BUILD.gn | 1 + test/systemtest/acts/ansDump/BUILD.gn | 56 +++++++++++++ test/systemtest/acts/ansDump/ansDumpTest.cpp | 88 ++++++++++++++++++++ 3 files changed, 145 insertions(+) create mode 100644 test/systemtest/acts/ansDump/BUILD.gn create mode 100644 test/systemtest/acts/ansDump/ansDumpTest.cpp diff --git a/test/BUILD.gn b/test/BUILD.gn index 7f120ed..1cd6c47 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -27,5 +27,6 @@ group("systemtest") { deps = [ "common\acts:actsnotificationtest", "resource\ansSTSlotGroupTest:ansSTSlotGroupTest", + "systemtest\acts\ansDump:ansDumpTest", ] } diff --git a/test/systemtest/acts/ansDump/BUILD.gn b/test/systemtest/acts/ansDump/BUILD.gn new file mode 100644 index 0000000..fd79d5c --- /dev/null +++ b/test/systemtest/acts/ansDump/BUILD.gn @@ -0,0 +1,56 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//base/notification/ans_standard/notification.gni") +import("//build/test.gni") + +module_output_path = "ans_standard/systemtest" +ohos_systemtest("AnsDumpTest") { + module_out_path = module_output_path + + sources = [ "ansDumpTest.cpp" ] + + include_dirs = [ + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//third_party/json/single_include", + "//utils/native/base/include", + "//utils/system/safwk/native/include", + ] + + cflags = [] + + if (target_cpu == "arm") { + cflags += [ "-DBINDER_IPC_32BIT" ] + } + + deps = [ + "${frameworks_path}/ans/core:ans_core", + "${frameworks_path}/wantagent:wantagent_innerkits", + "//third_party/googletest:gtest_main", + "//utils/native/base:utils", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_core", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "samgr_standard:samgr_proxy", + ] +} + +group("ansDumpTest") { + testonly = true + + deps = [ ":AnsDumpTest" ] +} diff --git a/test/systemtest/acts/ansDump/ansDumpTest.cpp b/test/systemtest/acts/ansDump/ansDumpTest.cpp new file mode 100644 index 0000000..a95e500 --- /dev/null +++ b/test/systemtest/acts/ansDump/ansDumpTest.cpp @@ -0,0 +1,88 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#define private public +#define protected public + +#include "ans_notification.h" +#include "iservice_registry.h" +#include "singleton.h" +#include "system_ability_definition.h" + +#undef private +#undef protected + +#include + +using namespace testing::ext; + +namespace OHOS { +namespace Notification { +class AnsDumpTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); + + std::shared_ptr ans_; +}; + +void AnsDumpTest::SetUpTestCase() +{} + +void AnsDumpTest::TearDownTestCase() +{} + +void AnsDumpTest::SetUp() +{ + if (!ans_) { + ans_ = DelayedSingleton::GetInstance(); + } +} + +void AnsDumpTest::TearDown() +{} + +/* + * @tc.number: AnsDumpTest_GetServiceObject_0100 + * @tc.name: Get Service Object + * @tc.desc: + */ +HWTEST_F(AnsDumpTest, AnsDumpTest_GetServiceObject_0100, Function | MediumTest | Level0) +{ + sptr systemAbilityManager = + SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + EXPECT_NE(systemAbilityManager, nullptr); + + sptr remoteObject = + systemAbilityManager->GetSystemAbility(ADVANCED_NOTIFICATION_SERVICE_ABILITY_ID); + EXPECT_NE(remoteObject, nullptr); +} + +/* + * @tc.number: AnsDumpTest_ShellDump_0100 + * @tc.name: Shell Dump + * @tc.desc: + */ +HWTEST_F(AnsDumpTest, AnsDumpTest_ShellDump_0100, Function | MediumTest | Level0) +{ + std::vector infos; + if (ans_) { + auto ret = ans_->ShellDump("active", infos); + EXPECT_EQ(ret, 0); + } +} +} // namespace Notification +} // namespace OHOS \ No newline at end of file -- Gitee From c253777821d0bfaf91ad1f44830bca95aad8b20d Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sat, 4 Dec 2021 12:12:34 +0000 Subject: [PATCH 040/131] Fix code Signed-off-by: zhaoyuan17 --- test/systemtest/acts/ansDump/ansDumpTest.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/systemtest/acts/ansDump/ansDumpTest.cpp b/test/systemtest/acts/ansDump/ansDumpTest.cpp index a95e500..de99991 100644 --- a/test/systemtest/acts/ansDump/ansDumpTest.cpp +++ b/test/systemtest/acts/ansDump/ansDumpTest.cpp @@ -58,7 +58,7 @@ void AnsDumpTest::TearDown() /* * @tc.number: AnsDumpTest_GetServiceObject_0100 * @tc.name: Get Service Object - * @tc.desc: + * @tc.desc: */ HWTEST_F(AnsDumpTest, AnsDumpTest_GetServiceObject_0100, Function | MediumTest | Level0) { @@ -74,7 +74,7 @@ HWTEST_F(AnsDumpTest, AnsDumpTest_GetServiceObject_0100, Function | MediumTest | /* * @tc.number: AnsDumpTest_ShellDump_0100 * @tc.name: Shell Dump - * @tc.desc: + * @tc.desc: */ HWTEST_F(AnsDumpTest, AnsDumpTest_ShellDump_0100, Function | MediumTest | Level0) { -- Gitee From 4dcb1ba91fd7b6f12b8868820f0731f757c6d3df Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 6 Dec 2021 19:50:21 +0000 Subject: [PATCH 041/131] Update d.ts Signed-off-by: zhaoyuan17 --- interfaces/kits/js/@ohos.notification.d.ts | 83 +++++++++++++++++++ .../notificationActionButton.d.ts | 6 ++ .../js/notification/notificationRequest.d.ts | 14 ++++ .../notification/notificationSubscriber.d.ts | 1 + .../notification/notificationUserInput.d.ts | 30 +++++++ 5 files changed, 134 insertions(+) create mode 100644 interfaces/kits/js/notification/notificationUserInput.d.ts diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index b1eb7f2..eb44ec9 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -495,6 +495,44 @@ declare namespace notification { function getActiveNotifications(callback: AsyncCallback>): void; function getActiveNotifications(): Promise>; + /** + * Cancel the notification of a specified group for this application. + */ + function cancelGroup(groupName: string, callback: AsyncCallback): void; + function cancelGroup(groupName: string): Promise; + + /** + * Delete the notification of a specified group for this application. + * + * @systemapi Hide this for inner system use. + */ + function removeGroupByBundle(bundle: BundleOption, groupName: string, callback: AsyncCallback): void; + function removeGroupByBundle(bundle: BundleOption, groupName: string): Promise; + + /** + * Set the Do Not Disturb date. + * + * @systemapi Hide this for inner system use. + */ + function setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback): void; + function setDoNotDisturbDate(date: DoNotDisturbDate): Promise; + + /** + * Obtains the Do Not Disturb date. + * + * @systemapi Hide this for inner system use. + */ + function getDoNotDisturbDate(callback: AsyncCallback): void; + function getDoNotDisturbDate(): Promise; + + /** + * Obtains whether to support the Do Not Disturb mode. + * + * @systemapi Hide this for inner system use. + */ + function supportDoNotDisturbMode(callback: AsyncCallback): void; + function supportDoNotDisturbMode(): Promise; + /** * Describes a BundleOption. */ @@ -541,6 +579,51 @@ declare namespace notification { */ ALLOW_ALARMS } + + /** + * The type of the Do Not Disturb. + * + * @systemapi Hide this for inner system use. + */ + export enum DoNotDisturbType { + TYPE_NONE = 0, // 非通知勿扰类型 + TYPE_ONCE = 1, // 以设置时间段(只看小时和分钟)一次执行勿扰 + TYPE_DAILY = 2, // 以设置时间段(只看小时和分钟)每天执行勿扰 + TYPE_CLEARLY = 3, // 以设置时间段(明确年月日时分)执行勿扰 + } + + /** + * Describes a DoNotDisturbDate instance. + * + * @systemapi Hide this for inner system use. + */ + export interface DoNotDisturbDate { + /** + * the type of the Do Not Disturb. + */ + type: DoNotDisturbType; + + /** + * the start time of the Do Not Disturb. + */ + begin: Date; + + /** + * the end time of the Do Not Disturb. + */ + end: Date; + } + + /** + * Notification source type + * + * @systemapi Hide this for inner system use. + */ + export enum SourceType { + TYPE_NORMAL = 0x00000000, // 普通通知 + TYPE_CONTINUOUS = 0x00000001, // 长时任务通知 + TYPE_TIMER = 0x00000002, // 定时通知 + } } export default notification; diff --git a/interfaces/kits/js/notification/notificationActionButton.d.ts b/interfaces/kits/js/notification/notificationActionButton.d.ts index 39cc3db..bf2549c 100644 --- a/interfaces/kits/js/notification/notificationActionButton.d.ts +++ b/interfaces/kits/js/notification/notificationActionButton.d.ts @@ -13,6 +13,7 @@ * limitations under the License. */ +import { NotificationUserInput } from './notificationUserInput'; import { WantAgent } from '../@ohos.wantAgent'; /** @@ -38,4 +39,9 @@ export interface NotificationActionButton { * Extra information of the button. */ extras?: {[key: string]: any}; + + /** + * User input + */ + userInput?: NotificationUserInput; } diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index b7e6575..1afddfb 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -165,4 +165,18 @@ export interface NotificationRequest { * Obtains the unique hash code of a notification in the current application. */ readonly hashCode?: string; + + /** + * Whether the notification can be remove. + * + * @systemapi Hide this for inner system use. + */ + readonly isRemoveAllowed?: boolean; + + /** + * Notification source. enum SourceType + * + * @systemapi Hide this for inner system use. + */ + readonly source?: number; } diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts index a659a9d..2b3f57e 100644 --- a/interfaces/kits/js/notification/notificationSubscriber.d.ts +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -36,6 +36,7 @@ export interface NotificationSubscriber { onDisconnect?:() => void; onDestroy?:() => void; onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void; + onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void; } /** diff --git a/interfaces/kits/js/notification/notificationUserInput.d.ts b/interfaces/kits/js/notification/notificationUserInput.d.ts new file mode 100644 index 0000000..1b44e87 --- /dev/null +++ b/interfaces/kits/js/notification/notificationUserInput.d.ts @@ -0,0 +1,30 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"), + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http?://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Describes a NotificationUserInput instance. + * + * @name NotificationUserInput + * @since 7 + * @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; +} -- Gitee From 9403c24f8f320b9ad2547cbe3e864435bf985f70 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 6 Dec 2021 20:11:57 +0000 Subject: [PATCH 042/131] Update d.ts Signed-off-by: zhaoyuan17 --- interfaces/kits/js/notification/notificationRequest.d.ts | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index 1afddfb..ce18332 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -139,6 +139,11 @@ export interface NotificationRequest { */ largeIcon?: image.PixelMap; + /** + * The group information for this notification. + */ + groupName?: string; + /** * Read-only name of the package for which a notification is created. */ -- Gitee From e8049fea1c0074672d683b479213161b203f274f Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Tue, 7 Dec 2021 10:56:46 +0000 Subject: [PATCH 043/131] Update d.ts Signed-off-by: zhaoyuan17 --- interfaces/kits/js/@ohos.notification.d.ts | 44 ++++++++++++++++++---- 1 file changed, 37 insertions(+), 7 deletions(-) diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index eb44ec9..aed5952 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -505,6 +505,7 @@ declare namespace notification { * Delete the notification of a specified group for this application. * * @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; @@ -513,6 +514,7 @@ declare namespace notification { * Set the Do Not Disturb date. * * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function setDoNotDisturbDate(date: DoNotDisturbDate, callback: AsyncCallback): void; function setDoNotDisturbDate(date: DoNotDisturbDate): Promise; @@ -521,6 +523,7 @@ declare namespace notification { * Obtains the Do Not Disturb date. * * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function getDoNotDisturbDate(callback: AsyncCallback): void; function getDoNotDisturbDate(): Promise; @@ -529,6 +532,7 @@ declare namespace notification { * Obtains whether to support the Do Not Disturb mode. * * @systemapi Hide this for inner system use. + * @permission ohos.permission.NOTIFICATION_CONTROLLER */ function supportDoNotDisturbMode(callback: AsyncCallback): void; function supportDoNotDisturbMode(): Promise; @@ -586,10 +590,25 @@ declare namespace notification { * @systemapi Hide this for inner system use. */ export enum DoNotDisturbType { - TYPE_NONE = 0, // 非通知勿扰类型 - TYPE_ONCE = 1, // 以设置时间段(只看小时和分钟)一次执行勿扰 - TYPE_DAILY = 2, // 以设置时间段(只看小时和分钟)每天执行勿扰 - TYPE_CLEARLY = 3, // 以设置时间段(明确年月日时分)执行勿扰 + /** + * 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, } /** @@ -620,9 +639,20 @@ declare namespace notification { * @systemapi Hide this for inner system use. */ export enum SourceType { - TYPE_NORMAL = 0x00000000, // 普通通知 - TYPE_CONTINUOUS = 0x00000001, // 长时任务通知 - TYPE_TIMER = 0x00000002, // 定时通知 + /** + * General notification + */ + TYPE_NORMAL = 0x00000000, + + /** + * Continuous notification + */ + TYPE_CONTINUOUS = 0x00000001, + + /** + * Scheduled notification + */ + TYPE_TIMER = 0x00000002, } } -- Gitee From ff03391f35321aa940b4a93e210dfcc441850716 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 8 Dec 2021 10:43:02 +0000 Subject: [PATCH 044/131] Application clone compilation error modification Signed-off-by: zhaoyuan17 --- .../ans/test/moduletest/mock/include/mock_bundle_manager.h | 2 +- frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp | 3 ++- services/test/moduletest/mock/include/mock_bundle_manager.h | 2 +- services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp | 2 +- 4 files changed, 5 insertions(+), 4 deletions(-) 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 fd4ac0f..cc102a7 100644 --- a/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h +++ b/frameworks/ans/test/moduletest/mock/include/mock_bundle_manager.h @@ -425,7 +425,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; } 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 cd58a48..eef4bd3 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -47,6 +47,7 @@ bool BundleMgrProxy::GetApplicationInfos( bool BundleMgrProxy::GetBundleInfo(const std::string &bundleName, const BundleFlag flag, BundleInfo &bundleInfo) { + bundleInfo.uid = 1; return true; } @@ -183,7 +184,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; } diff --git a/services/test/moduletest/mock/include/mock_bundle_manager.h b/services/test/moduletest/mock/include/mock_bundle_manager.h index 960b2aa..6a550d6 100644 --- a/services/test/moduletest/mock/include/mock_bundle_manager.h +++ b/services/test/moduletest/mock/include/mock_bundle_manager.h @@ -331,7 +331,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; } diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 5738fc8..efccb1f 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -180,7 +180,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; } -- Gitee From b5dbb21e5c8bcff8645b774c1f1b8a96855c1842 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 8 Dec 2021 14:21:14 +0000 Subject: [PATCH 045/131] Fix code Signed-off-by: zhaoyuan17 --- services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index efccb1f..232efcf 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -274,6 +274,5 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da { return true; } - } // namespace AppExecFwk } // namespace OHOS -- Gitee From 48d2dececbadfaf09dfd2c84685c66936e06858c Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Wed, 8 Dec 2021 15:31:03 +0000 Subject: [PATCH 046/131] Fix codex Signed-off-by: zhaoyuan17 --- frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp | 2 -- 1 file changed, 2 deletions(-) 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 eef4bd3..5f16742 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) { } @@ -278,6 +277,5 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da { return true; } - } // namespace AppExecFwk } // namespace OHOS -- Gitee From 1b36dec2c5bd995920f6d2310db67bc3387b072d Mon Sep 17 00:00:00 2001 From: liuyanzhi Date: Wed, 8 Dec 2021 20:36:10 +0800 Subject: [PATCH 047/131] start alarm clearing Signed-off-by: liuyanzhi Change-Id: Ia40ae490c43b9688a795baf558f9015b2d4a189f --- .../core/common/include/ans_const_define.h | 1 - .../ans/core/common/include/ans_log_wrapper.h | 1 - .../include/ans_manager_death_recipient.h | 1 - .../ans/core/include/ans_notification.h | 2 +- .../ans/core/include/ans_subscriber_proxy.h | 1 - .../ans/core/include/ans_subscriber_stub.h | 1 - frameworks/ans/core/src/ans_manager_proxy.cpp | 3 -- frameworks/ans/core/src/ans_manager_stub.cpp | 37 ------------------- frameworks/ans/core/src/ans_notification.cpp | 1 - .../ans/core/src/ans_subscriber_proxy.cpp | 1 - .../ans/core/src/ans_subscriber_stub.cpp | 2 - frameworks/ans/native/src/notification.cpp | 4 +- .../native/src/notification_action_button.cpp | 6 +-- .../native/src/notification_bundle_option.cpp | 3 +- .../ans/native/src/notification_constant.cpp | 1 - .../ans/native/src/notification_content.cpp | 22 +++++++---- .../notification_conversational_content.cpp | 2 +- .../notification_conversational_message.cpp | 2 +- .../src/notification_long_text_content.cpp | 5 +-- .../native/src/notification_media_content.cpp | 5 +-- .../src/notification_multiline_content.cpp | 4 +- .../src/notification_normal_content.cpp | 2 +- .../src/notification_picture_content.cpp | 2 +- .../ans/native/src/notification_request.cpp | 14 +++---- .../ans/native/src/notification_slot.cpp | 1 - .../native/src/notification_slot_group.cpp | 2 +- .../src/notification_subscribe_info.cpp | 2 - .../native/src/notification_subscriber.cpp | 8 ++-- .../native/src/notification_user_input.cpp | 3 +- .../ans_innerkits_module_publish_test.cpp | 3 +- .../ans_innerkits_module_setting_test.cpp | 13 +++---- .../ans_innerkits_module_slot_test.cpp | 1 - .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 2 - .../moduletest/mock/mock_event_handler.cpp | 1 - .../moduletest/mock/mock_message_parcel.cpp | 2 +- .../moduletest/mock/mock_single_kv_store.cpp | 1 - frameworks/wantagent/src/pending_want.cpp | 1 - .../wantagent/src/want_agent_log_wrapper.cpp | 1 - .../ans/native/include/message_user.h | 10 ++--- .../ans/native/include/notification.h | 1 - .../include/notification_bundle_option.h | 4 +- .../native/include/notification_constant.h | 4 +- .../ans/native/include/notification_request.h | 32 ++++++++-------- .../native/include/notification_slot_group.h | 10 ++--- .../ans/native/include/notification_sorting.h | 1 - .../native/include/notification_sorting_map.h | 2 - .../include/notification_subscribe_info.h | 1 - .../native/include/notification_subscriber.h | 3 +- .../wantagent/include/completed_callback.h | 1 - .../wantagent/include/completed_dispatcher.h | 18 ++++----- .../wantagent/include/pending_want.h | 8 ++-- .../wantagent/include/trigger_info.h | 12 +++--- .../innerkits/wantagent/include/want_agent.h | 19 +++++----- .../wantagent/include/want_agent_constant.h | 2 +- .../wantagent/include/want_agent_helper.h | 8 ++-- .../wantagent/include/want_agent_info.h | 14 +++---- .../include/want_agent_log_wrapper.h | 2 +- interfaces/kits/napi/ans/include/cancel.h | 1 - interfaces/kits/napi/ans/include/common.h | 1 - interfaces/kits/napi/ans/include/constant.h | 1 - .../kits/napi/ans/include/display_badge.h | 1 - .../kits/napi/ans/include/disturb_mode.h | 1 - .../napi/ans/include/enable_notification.h | 1 - interfaces/kits/napi/ans/include/get_active.h | 1 - interfaces/kits/napi/ans/include/init.h | 1 - interfaces/kits/napi/ans/include/publish.h | 2 - interfaces/kits/napi/ans/include/remove.h | 1 - interfaces/kits/napi/ans/include/slot.h | 1 - interfaces/kits/napi/ans/include/subscribe.h | 2 - .../kits/napi/ans/include/unsubscribe.h | 1 - interfaces/kits/napi/ans/src/cancel.cpp | 1 - .../kits/napi/ans/src/display_badge.cpp | 1 - interfaces/kits/napi/ans/src/disturb_mode.cpp | 1 - .../kits/napi/ans/src/enable_notification.cpp | 1 - interfaces/kits/napi/ans/src/init.cpp | 1 - interfaces/kits/napi/ans/src/slot.cpp | 1 - interfaces/kits/napi/ans/src/subscribe.cpp | 1 - interfaces/kits/napi/ans/src/unsubscribe.cpp | 1 - .../kits/napi/wantagent/napi_want_agent.cpp | 18 ++++----- .../kits/napi/wantagent/native_module.cpp | 4 +- .../include/advanced_notification_service.h | 2 - .../advanced_notification_service_ability.h | 2 - services/ans/include/bundle_manager_helper.h | 2 - .../distributed_kvstore_death_recipient.h | 2 - services/ans/include/disturb_filter.h | 6 +-- services/ans/include/interface_system_event.h | 2 - services/ans/include/notification_filter.h | 6 +-- .../notification_preferences_database.h | 2 - services/ans/include/notification_record.h | 2 - .../ans/include/notification_slot_filter.h | 6 +-- .../include/notification_subscriber_manager.h | 1 - services/ans/include/permission_filter.h | 6 +-- services/ans/include/preferences_constant.h | 2 - services/ans/include/remote_death_recipient.h | 7 +--- services/ans/include/system_event_observer.h | 2 - .../ans/include/system_event_subscriber.h | 2 - .../ans/src/advanced_notification_service.cpp | 1 - .../advanced_notification_service_ability.cpp | 2 - services/ans/src/bundle_manager_helper.cpp | 2 - services/ans/src/notification_preferences.cpp | 6 --- .../src/notification_preferences_database.cpp | 4 -- .../ans/src/notification_preferences_info.cpp | 2 - services/ans/src/notification_slot_filter.cpp | 2 - .../src/notification_subscriber_manager.cpp | 1 - services/ans/src/permission_filter.cpp | 2 - services/ans/src/system_event_observer.cpp | 2 - ...nced_notification_service_ability_test.cpp | 10 ++--- .../unittest/bundle_manager_helper_test.cpp | 9 ++--- .../mock/mock_bundle_manager_helper.cpp | 3 -- .../test/unittest/mock/mock_event_handler.cpp | 2 - ...notification_preferences_database_test.cpp | 12 ++---- .../notification_preferences_test.cpp | 8 ++-- .../notification_slot_filter_test.cpp | 9 ++--- .../notification_subscriber_manager_test.cpp | 1 - .../test/unittest/permission_filter_test.cpp | 5 +-- services/test/moduletest/ans_module_test.cpp | 9 ++--- .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 1 - .../moduletest/mock/mock_event_handler.cpp | 1 - .../include/ans_slotgroup_test.h | 2 - .../dump/include/notification_shell_command.h | 4 +- tools/dump/src/main.cpp | 1 - 121 files changed, 169 insertions(+), 345 deletions(-) diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 8e1cb00..8568a2b 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -22,7 +22,6 @@ namespace OHOS { namespace Notification { - // Max active notification number constexpr uint32_t MAX_ACTIVE_NUM = 1000; constexpr uint32_t MAX_ACTIVE_NUM_PERAPP = 100; diff --git a/frameworks/ans/core/common/include/ans_log_wrapper.h b/frameworks/ans/core/common/include/ans_log_wrapper.h index 3f03294..c9543f7 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 diff --git a/frameworks/ans/core/include/ans_manager_death_recipient.h b/frameworks/ans/core/include/ans_manager_death_recipient.h index a726115..671a4e3 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_notification.h b/frameworks/ans/core/include/ans_notification.h index 54d4811..f95a82d 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -427,7 +427,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. diff --git a/frameworks/ans/core/include/ans_subscriber_proxy.h b/frameworks/ans/core/include/ans_subscriber_proxy.h index ea286a7..8739caf 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; diff --git a/frameworks/ans/core/include/ans_subscriber_stub.h b/frameworks/ans/core/include/ans_subscriber_stub.h index 403731b..26928cd 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(); diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 7729d7a..f3889d7 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace Notification { - AnsManagerProxy::AnsManagerProxy(const sptr &impl) : IRemoteProxy(impl) {} @@ -1442,7 +1441,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; @@ -2009,6 +2007,5 @@ bool AnsManagerProxy::ReadParcelableVector(std::vector> &parcelableInfos return true; } - } // 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 20a8c87..ea74077 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -23,7 +23,6 @@ namespace OHOS { namespace Notification { - const std::map> AnsManagerStub::interfaces_ = { {AnsManagerStub::PUBLISH_NOTIFICATION, @@ -249,7 +248,6 @@ ErrCode AnsManagerStub::HandlePublish(MessageParcel &data, MessageParcel &reply) } ErrCode result = Publish(label, notification); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandlePublish] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -272,7 +270,6 @@ ErrCode AnsManagerStub::HandlePublishToDevice(MessageParcel &data, MessageParcel } ErrCode result = PublishToDevice(notification, deviceId); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandlePublishToDevice] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -295,7 +292,6 @@ ErrCode AnsManagerStub::HandleCancel(MessageParcel &data, MessageParcel &reply) } ErrCode result = Cancel(notificationId, label); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleCancel] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -306,7 +302,6 @@ ErrCode AnsManagerStub::HandleCancel(MessageParcel &data, MessageParcel &reply) ErrCode AnsManagerStub::HandleCancelAll(MessageParcel &data, MessageParcel &reply) { ErrCode result = CancelAll(); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleCancelAll] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -317,9 +312,7 @@ ErrCode AnsManagerStub::HandleCancelAll(MessageParcel &data, MessageParcel &repl ErrCode AnsManagerStub::HandleAddSlotByType(MessageParcel &data, MessageParcel &reply) { NotificationConstant::SlotType slotType = static_cast(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; @@ -349,7 +342,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; @@ -360,7 +352,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; @@ -377,7 +368,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; @@ -389,7 +379,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; @@ -404,7 +393,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; @@ -427,7 +415,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; @@ -444,7 +431,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; @@ -484,7 +470,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; @@ -496,7 +481,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; @@ -508,7 +492,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; @@ -525,7 +508,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; @@ -543,7 +525,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; @@ -571,7 +552,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; @@ -595,7 +575,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; @@ -651,7 +630,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; @@ -673,7 +651,6 @@ ErrCode AnsManagerStub::HandleSetDoNotDisturbDate(MessageParcel &data, MessagePa } ErrCode result = SetDoNotDisturbDate(date); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleSetDoNotDisturbDate] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -687,7 +664,6 @@ ErrCode AnsManagerStub::HandleGetDoNotDisturbDate(MessageParcel &data, MessagePa sptr date = nullptr; ErrCode result = GetDoNotDisturbDate(date); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleSetDoNotDisturbDate] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -708,7 +684,6 @@ ErrCode AnsManagerStub::HandleDoesSupportDoNotDisturbMode(MessageParcel &data, M 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; @@ -731,7 +706,6 @@ ErrCode AnsManagerStub::HandlePublishContinuousTaskNotification(MessageParcel &d } ErrCode result = PublishContinuousTaskNotification(request); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandlePublishContinuousTaskNotification] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -754,7 +728,6 @@ ErrCode AnsManagerStub::HandleCancelContinuousTaskNotification(MessageParcel &da } 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; @@ -766,7 +739,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; @@ -1058,7 +1030,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; @@ -1075,7 +1046,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; @@ -1154,7 +1124,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; @@ -1171,7 +1140,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; @@ -1188,7 +1156,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; @@ -1211,7 +1178,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; @@ -1233,7 +1199,6 @@ ErrCode AnsManagerStub::HandleCancelGroup(MessageParcel &data, MessageParcel &re } ErrCode result = CancelGroup(groupName); - if (!reply.WriteInt32(result)) { ANS_LOGW("[HandleCancelGroup] fail: write result failed, ErrCode=%{public}d", result); return ERR_ANS_PARCELABLE_FAILED; @@ -1256,7 +1221,6 @@ ErrCode AnsManagerStub::HandleRemoveGroupByBundle(MessageParcel &data, MessagePa } 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; @@ -1274,7 +1238,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; diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 7171c38..2e8b480 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -14,7 +14,6 @@ */ #include "ans_notification.h" -#include #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" diff --git a/frameworks/ans/core/src/ans_subscriber_proxy.cpp b/frameworks/ans/core/src/ans_subscriber_proxy.cpp index b1abfaf..1952b3f 100644 --- a/frameworks/ans/core/src/ans_subscriber_proxy.cpp +++ b/frameworks/ans/core/src/ans_subscriber_proxy.cpp @@ -274,6 +274,5 @@ void AnsSubscriberProxy::OnDoNotDisturbDateChange(const sptr #include "ans_subscriber_stub.h" @@ -216,6 +215,5 @@ void AnsSubscriberStub::OnUpdated(const sptr ¬ificati void AnsSubscriberStub::OnDoNotDisturbDateChange(const sptr &date) {} - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 100e122..77b1f58 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -15,13 +15,12 @@ #include "notification.h" -#include #include "ans_log_wrapper.h" namespace OHOS { namespace Notification { -Notification::Notification(){}; +Notification::Notification() {}; Notification::Notification(const sptr &request) { @@ -445,6 +444,5 @@ std::string Notification::Dump() const } return dump; } - } // 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 4c11474..94cd2a7 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -15,7 +15,6 @@ #include "notification_action_button.h" -#include #include "ans_log_wrapper.h" namespace OHOS { @@ -34,7 +33,6 @@ std::shared_ptr NotificationActionButton::Create(const auto realExtras = extras; if (!realExtras) { realExtras = std::make_shared(); - if (!realExtras) { ANS_LOGE("create PacMap object failed"); return {}; @@ -289,7 +287,7 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const NotificationActionButton *NotificationActionButton::Unmarshalling(Parcel &parcel) { auto pButton = new NotificationActionButton(); - if ((nullptr != pButton) && !pButton->ReadFromParcel(parcel)) { + if ((pButton != nullptr) && !pButton->ReadFromParcel(parcel)) { delete pButton; pButton = nullptr; } @@ -345,7 +343,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_bundle_option.cpp b/frameworks/ans/native/src/notification_bundle_option.cpp index b5adae9..4269aca 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() diff --git a/frameworks/ans/native/src/notification_constant.cpp b/frameworks/ans/native/src/notification_constant.cpp index 43f23d6..5637d58 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 1accb1d..5f302bb 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -136,7 +136,7 @@ bool NotificationContent::Marshalling(Parcel &parcel) const NotificationContent *NotificationContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; } @@ -162,7 +162,8 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(normalContent); - } break; + break; + } case NotificationContent::Type::CONVERSATION: { std::shared_ptr conversationalContent( parcel.ReadParcelable()); @@ -171,7 +172,8 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(conversationalContent); - } break; + break; + } case NotificationContent::Type::LONG_TEXT: { std::shared_ptr longTextContent( parcel.ReadParcelable()); @@ -180,7 +182,8 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(longTextContent); - } break; + break; + } case NotificationContent::Type::MEDIA: { std::shared_ptr mediaContent(parcel.ReadParcelable()); if (!mediaContent) { @@ -188,7 +191,8 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(mediaContent); - } break; + break; + } case NotificationContent::Type::MULTILINE: { std::shared_ptr multiLineContent( parcel.ReadParcelable()); @@ -197,7 +201,8 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(multiLineContent); - } break; + break; + } case NotificationContent::Type::PICTURE: { std::shared_ptr pictureContent( parcel.ReadParcelable()); @@ -206,10 +211,11 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) return false; } content_ = std::dynamic_pointer_cast(pictureContent); - } break; + break; + } default: { return false; - } break; + } } return true; diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 2b1925d..102a984 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -133,7 +133,7 @@ bool NotificationConversationalContent::Marshalling(Parcel &parcel) const NotificationConversationalContent *NotificationConversationalContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationConversationalContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 9274ef8..139826a 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -102,7 +102,7 @@ bool NotificationConversationalMessage::Marshalling(Parcel &parcel) const NotificationConversationalMessage *NotificationConversationalMessage::Unmarshalling(Parcel &parcel) { auto pMessage = new NotificationConversationalMessage(); - if ((nullptr != pMessage) && !pMessage->ReadFromParcel(parcel)) { + if ((pMessage != nullptr) && !pMessage->ReadFromParcel(parcel)) { delete pMessage; pMessage = nullptr; } diff --git a/frameworks/ans/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp index c806df2..1ce547b 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -13,9 +13,8 @@ * limitations under the License. */ -#include -#include "notification_long_text_content.h" #include "ans_log_wrapper.h" +#include "notification_long_text_content.h" namespace OHOS { namespace Notification { @@ -97,7 +96,7 @@ bool NotificationLongTextContent::Marshalling(Parcel &parcel) const NotificationLongTextContent *NotificationLongTextContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationLongTextContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 d66b8bc..252240b 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -13,9 +13,8 @@ * limitations under the License. */ -#include -#include "notification_media_content.h" #include "ans_log_wrapper.h" +#include "notification_media_content.h" namespace OHOS { namespace Notification { @@ -68,7 +67,7 @@ bool NotificationMediaContent::Marshalling(Parcel &parcel) const NotificationMediaContent *NotificationMediaContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationMediaContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 abd88be..d20acf4 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -14,8 +14,8 @@ */ #include -#include "notification_multiline_content.h" #include "ans_log_wrapper.h" +#include "notification_multiline_content.h" namespace OHOS { namespace Notification { @@ -95,7 +95,7 @@ bool NotificationMultiLineContent::Marshalling(Parcel &parcel) const NotificationMultiLineContent *NotificationMultiLineContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationMultiLineContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 e9e2537..481c1aa 100644 --- a/frameworks/ans/native/src/notification_normal_content.cpp +++ b/frameworks/ans/native/src/notification_normal_content.cpp @@ -30,7 +30,7 @@ bool NotificationNormalContent::Marshalling(Parcel &parcel) const NotificationNormalContent *NotificationNormalContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationNormalContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 9138938..b2aa8af 100644 --- a/frameworks/ans/native/src/notification_picture_content.cpp +++ b/frameworks/ans/native/src/notification_picture_content.cpp @@ -90,7 +90,7 @@ bool NotificationPictureContent::Marshalling(Parcel &parcel) const NotificationPictureContent *NotificationPictureContent::Unmarshalling(Parcel &parcel) { auto pContent = new NotificationPictureContent(); - if ((nullptr != pContent) && !pContent->ReadFromParcel(parcel)) { + 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 1ea18d3..a3898fc 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -13,10 +13,8 @@ * limitations under the License. */ -#include -#include -#include "notification_request.h" #include "ans_log_wrapper.h" +#include "notification_request.h" namespace OHOS { namespace Notification { @@ -271,7 +269,7 @@ int64_t NotificationRequest::GetDeliveryTime() const bool NotificationRequest::IsShowDeliveryTime() const { - return (0 != deliveryTime_) && showDeliveryTime_; + return (deliveryTime_ != 0) && showDeliveryTime_; } void NotificationRequest::SetShowDeliveryTime(bool showDeliveryTime) @@ -653,7 +651,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 ""; } @@ -1090,7 +1088,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const NotificationRequest *NotificationRequest::Unmarshalling(Parcel &parcel) { auto objptr = new NotificationRequest(); - if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -1254,7 +1252,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 +1263,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; } diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index a54224d..00f7a5b 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace Notification { - const int MAX_TEXT_LENGTH = 1000; NotificationSlot::NotificationSlot(NotificationConstant::SlotType type) : sound_("") diff --git a/frameworks/ans/native/src/notification_slot_group.cpp b/frameworks/ans/native/src/notification_slot_group.cpp index 5f06ffc..89720f8 100644 --- a/frameworks/ans/native/src/notification_slot_group.cpp +++ b/frameworks/ans/native/src/notification_slot_group.cpp @@ -137,7 +137,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; } diff --git a/frameworks/ans/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp index 5424042..7f42398 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() {} @@ -77,6 +76,5 @@ std::string NotificationSubscribeInfo::Dump() { return "Dump"; } - } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index 62e2c09..d1be623 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -20,7 +20,6 @@ namespace OHOS { namespace Notification { - NotificationSubscriber::NotificationSubscriber() { impl_ = new SubscriberImpl(*this); @@ -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_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index 0115c3b..e8ed66a 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -15,7 +15,6 @@ #include "notification_user_input.h" -#include #include "ans_log_wrapper.h" namespace OHOS { @@ -281,7 +280,7 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const NotificationUserInput *NotificationUserInput::Unmarshalling(Parcel &parcel) { auto pUserInput = new NotificationUserInput(); - if ((nullptr != pUserInput) && !pUserInput->ReadFromParcel(parcel)) { + if ((pUserInput != nullptr) && !pUserInput->ReadFromParcel(parcel)) { delete pUserInput; pUserInput = nullptr; } 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 aae3d31..65a4ab2 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -32,7 +32,6 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); bool OnConsumedReceived = false; @@ -67,7 +66,7 @@ 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: 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 98a38c0..4a16ba6 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,7 +130,7 @@ 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()); } 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 caef96a..31675f2 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_slot_test.cpp @@ -29,7 +29,6 @@ using namespace testing::ext; namespace OHOS { namespace Notification { - static sptr systemAbilityManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); const int32_t CALLING_UID = 9998; 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 cd58a48..6bcdb3b 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -24,7 +24,6 @@ namespace OHOS { namespace AppExecFwk { - BundleMgrProxy::BundleMgrProxy(const sptr &impl) : IRemoteProxy(impl) { } @@ -277,6 +276,5 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da { return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp index 12a7f65..bbbeb49 100644 --- a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp @@ -15,7 +15,6 @@ #include "event_handler.h" #include "event_handler_utils.h" -#include namespace OHOS { namespace AppExecFwk { diff --git a/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp b/frameworks/ans/test/moduletest/mock/mock_message_parcel.cpp index 26b6304..49c18fb 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 bc79b19..e246e8d 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/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; diff --git a/frameworks/wantagent/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp index 926dbfc..56e1e4c 100644 --- a/frameworks/wantagent/src/pending_want.cpp +++ b/frameworks/wantagent/src/pending_want.cpp @@ -408,5 +408,4 @@ PendingWant *PendingWant::Unmarshalling(Parcel &parcel) return pendingWant; } - } // namespace OHOS::Notification::WantAgent diff --git a/frameworks/wantagent/src/want_agent_log_wrapper.cpp b/frameworks/wantagent/src/want_agent_log_wrapper.cpp index 059ffb2..e379cef 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/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 0e7717d..7c8dbda 100644 --- a/interfaces/innerkits/ans/native/include/message_user.h +++ b/interfaces/innerkits/ans/native/include/message_user.h @@ -150,12 +150,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 1b125e4..7503e15 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -25,7 +25,6 @@ namespace OHOS { namespace Notification { - class Notification final : public Parcelable { public: /** diff --git a/interfaces/innerkits/ans/native/include/notification_bundle_option.h b/interfaces/innerkits/ans/native/include/notification_bundle_option.h index 7c2fa91..4ea4fb0 100644 --- a/interfaces/innerkits/ans/native/include/notification_bundle_option.h +++ b/interfaces/innerkits/ans/native/include/notification_bundle_option.h @@ -91,8 +91,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 fb8f4aa..1f710ef 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -23,8 +23,8 @@ namespace Notification { class NotificationConstant { public: 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 diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index ad1b078..34d542d 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -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. @@ -874,6 +858,22 @@ public: */ static NotificationRequest *Unmarshalling(Parcel &parcel); +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. diff --git a/interfaces/innerkits/ans/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h index 7231289..bcba439 100644 --- a/interfaces/innerkits/ans/native/include/notification_slot_group.h +++ b/interfaces/innerkits/ans/native/include/notification_slot_group.h @@ -140,11 +140,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 1efa272..da7810b 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting.h @@ -26,7 +26,6 @@ namespace OHOS { namespace Notification { - class NotificationSorting final : public Parcelable { public: /** diff --git a/interfaces/innerkits/ans/native/include/notification_sorting_map.h b/interfaces/innerkits/ans/native/include/notification_sorting_map.h index 54fb3f3..0fe5e4b 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting_map.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting_map.h @@ -25,7 +25,6 @@ namespace OHOS { namespace Notification { - class NotificationSortingMap final : public Parcelable { public: /** @@ -96,7 +95,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 1eb370e..bb5ede5 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h +++ b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h @@ -24,7 +24,6 @@ namespace OHOS { namespace Notification { - class NotificationSubscribeInfo final : public Parcelable { public: /** diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 54ce4f3..688959d 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -26,7 +26,6 @@ namespace OHOS { namespace Notification { - class NotificationSubscriber { public: /** @@ -120,7 +119,7 @@ private: public: SubscriberImpl(NotificationSubscriber &subscriber); - ~SubscriberImpl(){}; + ~SubscriberImpl() {}; void OnConnected() override; diff --git a/interfaces/innerkits/wantagent/include/completed_callback.h b/interfaces/innerkits/wantagent/include/completed_callback.h index 5740a89..5b83a2d 100644 --- a/interfaces/innerkits/wantagent/include/completed_callback.h +++ b/interfaces/innerkits/wantagent/include/completed_callback.h @@ -23,7 +23,6 @@ namespace OHOS::Notification::WantAgent { class CompletedCallback { - /** * Called when a Send operation as completed. * diff --git a/interfaces/innerkits/wantagent/include/completed_dispatcher.h b/interfaces/innerkits/wantagent/include/completed_dispatcher.h index bd17fbe..3b987c8 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 7ab84bd..1db00b7 100644 --- a/interfaces/innerkits/wantagent/include/pending_want.h +++ b/interfaces/innerkits/wantagent/include/pending_want.h @@ -32,7 +32,7 @@ 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; @@ -255,9 +255,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,6 +262,9 @@ 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, diff --git a/interfaces/innerkits/wantagent/include/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h index ce60016..ba4cdba 100644 --- a/interfaces/innerkits/wantagent/include/trigger_info.h +++ b/interfaces/innerkits/wantagent/include/trigger_info.h @@ -100,12 +100,6 @@ 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; - /** * Default constructor used to create a {@code Builder} instance. * @@ -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 06d6cd3..f9a1908 100644 --- a/interfaces/innerkits/wantagent/include/want_agent.h +++ b/interfaces/innerkits/wantagent/include/want_agent.h @@ -25,16 +25,8 @@ namespace OHOS::Notification::WantAgent { class WantAgent final : public std::enable_shared_from_this, public Parcelable { -private: - std::shared_ptr pendingWant_; - - /** - * Constructor. - * - * @param obj The proxy object. - */ public: - WantAgent(){}; + WantAgent() {}; virtual ~WantAgent() = default; explicit WantAgent(const std::shared_ptr &pendingWant); @@ -67,6 +59,15 @@ public: * @return Returns true if the unmarshalling is successful; returns false otherwise. */ static WantAgent *Unmarshalling(Parcel &parcel); + +private: + std::shared_ptr pendingWant_; + + /** + * Constructor. + * + * @param obj The proxy object. + */ }; } // 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 461b023..4f611ff 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 cf775dd..7f3027f 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_helper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_helper.h @@ -42,10 +42,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. @@ -166,6 +162,10 @@ public: */ static void UnregisterCancelListener( const std::shared_ptr &cancelListener, const std::shared_ptr &agent); + +private: + WantAgentHelper(); + virtual ~WantAgentHelper() = default; private: static void Send(const std::shared_ptr &context, diff --git a/interfaces/innerkits/wantagent/include/want_agent_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h index 15c411d..c363784 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_info.h +++ b/interfaces/innerkits/wantagent/include/want_agent_info.h @@ -32,13 +32,6 @@ 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_; - /** * Default constructor used to create an empty WantAgentInfo instance. * @@ -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 263310d..8c9c141 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/napi/ans/include/cancel.h b/interfaces/kits/napi/ans/include/cancel.h index 219005d..4cdc87e 100644 --- a/interfaces/kits/napi/ans/include/cancel.h +++ b/interfaces/kits/napi/ans/include/cancel.h @@ -25,7 +25,6 @@ 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 94f053a..0f2075e 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -406,7 +406,6 @@ private: 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 96cb86f..5eb46c1 100644 --- a/interfaces/kits/napi/ans/include/constant.h +++ b/interfaces/kits/napi/ans/include/constant.h @@ -32,7 +32,6 @@ 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 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 9455431..992a41d 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/disturb_mode.h b/interfaces/kits/napi/ans/include/disturb_mode.h index 5b86d6e..3a2d668 100644 --- a/interfaces/kits/napi/ans/include/disturb_mode.h +++ b/interfaces/kits/napi/ans/include/disturb_mode.h @@ -24,7 +24,6 @@ using namespace OHOS::Notification; 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 e7ae306..d960945 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 867eef8..3786530 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 fabae8a..d8306a6 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 a288687..2f64e25 100644 --- a/interfaces/kits/napi/ans/include/publish.h +++ b/interfaces/kits/napi/ans/include/publish.h @@ -21,9 +21,7 @@ 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/interfaces/kits/napi/ans/include/remove.h b/interfaces/kits/napi/ans/include/remove.h index fddba90..56bc61c 100644 --- a/interfaces/kits/napi/ans/include/remove.h +++ b/interfaces/kits/napi/ans/include/remove.h @@ -26,7 +26,6 @@ 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 e4e0374..d7aaca4 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 08c0df5..b18e1de 100644 --- a/interfaces/kits/napi/ans/include/subscribe.h +++ b/interfaces/kits/napi/ans/include/subscribe.h @@ -80,7 +80,6 @@ private: CallbackInfo dieCallbackInfo_; CallbackInfo disturbModeCallbackInfo_; CallbackInfo disturbDateCallbackInfo_; - }; struct SubscriberInstancesInfo { @@ -96,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 595de74..2751b46 100644 --- a/interfaces/kits/napi/ans/include/unsubscribe.h +++ b/interfaces/kits/napi/ans/include/unsubscribe.h @@ -21,7 +21,6 @@ namespace OHOS { namespace NotificationNapi { using namespace OHOS::Notification; - napi_value Unsubscribe(napi_env env, napi_callback_info info); } // namespace NotificationNapi diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 0ba7a44..1632d1f 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -289,6 +289,5 @@ napi_value CancelGroup(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/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 889fd78..214b87b 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -260,6 +260,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/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index 2c261eb..d9b056f 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -316,6 +316,5 @@ napi_value SupportDoNotDisturbMode(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/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index b350df6..f0d943a 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -257,6 +257,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/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 358865a..2a27497 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -96,6 +96,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/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index faa723f..15d0156 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -978,6 +978,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 4056542..d35db62 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -1083,6 +1083,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 a8b188e..bd500e3 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -130,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/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index 727f54f..1d7fa5f 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 @@ -330,7 +330,7 @@ napi_value NAPI_GetBundleName(napi_env env, napi_callback_info info) 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, @@ -454,7 +454,7 @@ napi_value NAPI_GetUid(napi_env env, napi_callback_info info) 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, @@ -576,7 +576,7 @@ napi_value NAPI_GetWant(napi_env env, napi_callback_info info) 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, @@ -716,7 +716,7 @@ napi_value NAPI_Cancel(napi_env env, napi_callback_info info) 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, @@ -862,7 +862,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, @@ -1002,7 +1002,7 @@ napi_value NAPI_Equal(napi_env env, napi_callback_info info) 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, @@ -1254,7 +1254,7 @@ napi_value NAPI_GetWantAgent(napi_env env, napi_callback_info info) callBackMode = true; } - AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantAgentCallbackInfo{ + AsyncGetWantAgentCallbackInfo *asyncCallbackInfo = new (std::nothrow) AsyncGetWantAgentCallbackInfo { .env = env, .asyncWork = nullptr, .deferred = nullptr, diff --git a/interfaces/kits/napi/wantagent/native_module.cpp b/interfaces/kits/napi/wantagent/native_module.cpp index 0177c32..f4474a3 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/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 176224e..95214c0 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -36,7 +36,6 @@ namespace OHOS { namespace Notification { - class AdvancedNotificationService final : public AnsManagerStub { public: ~AdvancedNotificationService() override; @@ -165,7 +164,6 @@ private: std::shared_ptr systemEventObserver_ = nullptr; DistributedKv::DistributedKvDataManager dataManager_; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/advanced_notification_service_ability.h b/services/ans/include/advanced_notification_service_ability.h index 10f8ac3..ec5c866 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 bb8dc81..ab4fb0c 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -29,7 +29,6 @@ namespace OHOS { namespace Notification { - class BundleManagerHelper : public DelayedSingleton { public: std::string GetBundleNameByUid(int uid); @@ -49,7 +48,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 d596048..a023318 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/disturb_filter.h b/services/ans/include/disturb_filter.h index 3a28a32..84c4846 100644 --- a/services/ans/include/disturb_filter.h +++ b/services/ans/include/disturb_filter.h @@ -20,11 +20,10 @@ namespace OHOS { namespace Notification { - class DisturbFilter : public INotificationFilter { public: - DisturbFilter(){}; - ~DisturbFilter(){}; + DisturbFilter() {}; + ~DisturbFilter() {}; void OnStart() override; void OnStop() override; @@ -34,7 +33,6 @@ public: private: void GetTimeInterval(int64_t &beginDate, int64_t &endDate); }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/interface_system_event.h b/services/ans/include/interface_system_event.h index b4aba38..bc3b8f4 100644 --- a/services/ans/include/interface_system_event.h +++ b/services/ans/include/interface_system_event.h @@ -23,11 +23,9 @@ namespace OHOS { namespace Notification { - struct ISystemEvent { std::function &)> onBundleRemoved; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_filter.h b/services/ans/include/notification_filter.h index 30dc7b9..4c22910 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_database.h b/services/ans/include/notification_preferences_database.h index d037fe4..0787c62 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -24,7 +24,6 @@ namespace OHOS { namespace Notification { - class NotificationPreferencesDatabase final { public: NotificationPreferencesDatabase(); @@ -142,7 +141,6 @@ private: 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 diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index f41e65f..12b5413 100644 --- a/services/ans/include/notification_record.h +++ b/services/ans/include/notification_record.h @@ -25,14 +25,12 @@ namespace OHOS { namespace Notification { - struct NotificationRecord { sptr bundleOption; sptr request; sptr notification; sptr slot; }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/notification_slot_filter.h b/services/ans/include/notification_slot_filter.h index 45092a2..3b8978c 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 ea96bfa..477acb7 100644 --- a/services/ans/include/notification_subscriber_manager.h +++ b/services/ans/include/notification_subscriber_manager.h @@ -79,7 +79,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 850069c..f061027 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 f4ced93..64419b6 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -18,7 +18,6 @@ namespace OHOS { namespace Notification { - 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"; @@ -74,7 +73,6 @@ enum class BundleType { BUNDLE_PRIVATE_ALLOWED_TYPE, BUNDLE_ENABLE_NOTIFICATION_TYPE, }; - } // namespace Notification } // namespace OHOS diff --git a/services/ans/include/remote_death_recipient.h b/services/ans/include/remote_death_recipient.h index 400dfd5..ea52d41 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 7fc8cd4..8e4be39 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -26,7 +26,6 @@ namespace OHOS { namespace Notification { - class SystemEventObserver { public: SystemEventObserver(const ISystemEvent& callbacks); @@ -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 41b58c4..593f92b 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 3deb150..1af9f66 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -34,7 +34,6 @@ namespace OHOS { namespace Notification { - namespace { static const std::string ACTIVE_NOTIFICATION_OPTION = "active"; static const std::string RECENT_NOTIFICATION_OPTION = "recent"; diff --git a/services/ans/src/advanced_notification_service_ability.cpp b/services/ans/src/advanced_notification_service_ability.cpp index f361f3d..56f052f 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 a02c7f2..c548526 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - BundleManagerHelper::BundleManagerHelper() { deathRecipient_ = @@ -118,6 +117,5 @@ int BundleManagerHelper::GetDefaultUidByBundleName(const std::string& bundle) return uid; } - } // 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 dcf3080..04c2ce8 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - NotificationPreferences::NotificationPreferences() { preferncesDB_ = std::make_unique(); @@ -39,7 +38,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; @@ -119,7 +117,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; } @@ -237,7 +234,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; @@ -484,7 +480,6 @@ ErrCode NotificationPreferences::SetNotificationsEnabledForBundle( NotificationPreferencesInfo preferencesInfo = preferencesInfo_; ErrCode result = SetBundleProperty(preferencesInfo, bundleOption, BundleType::BUNDLE_ENABLE_NOTIFICATION_TYPE, enabled); - if (result == ERR_OK) { preferencesInfo_ = preferencesInfo; } @@ -778,6 +773,5 @@ void NotificationPreferences::OnDistributedKvStoreDeathRecipient() } } } - } // 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 a839e14..54c5a1e 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -14,16 +14,12 @@ */ #include "notification_preferences_database.h" -#include -#include -#include #include "ans_log_wrapper.h" #include "uri.h" namespace OHOS { namespace Notification { - const std::map &, std::string &)>> NotificationPreferencesDatabase::slotMap_ = { diff --git a/services/ans/src/notification_preferences_info.cpp b/services/ans/src/notification_preferences_info.cpp index 539035f..f58a968 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() @@ -291,6 +290,5 @@ void NotificationPreferencesInfo::ClearBundleInfo() { infos_.clear(); } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_slot_filter.cpp b/services/ans/src/notification_slot_filter.cpp index d59d1d1..9b4c59e 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 subscriber {nullptr}; std::set bundleList_ {}; diff --git a/services/ans/src/permission_filter.cpp b/services/ans/src/permission_filter.cpp index d66946c..9c4a868 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/system_event_observer.cpp b/services/ans/src/system_event_observer.cpp index 959e85f..c87a777 100644 --- a/services/ans/src/system_event_observer.cpp +++ b/services/ans/src/system_event_observer.cpp @@ -21,7 +21,6 @@ namespace OHOS { namespace Notification { - SystemEventObserver::SystemEventObserver(const ISystemEvent &callbacks) : callbacks_(callbacks) { EventFwk::MatchingSkills matchingSkills; @@ -53,6 +52,5 @@ void SystemEventObserver::OnReceiveEvent(const EventFwk::CommonEventData &data) } } } - } // namespace Notification } // namespace OHOS \ No newline at end of file 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 e447dec..fce488e 100644 --- a/services/ans/test/unittest/advanced_notification_service_ability_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_ability_test.cpp @@ -22,13 +22,12 @@ 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() {}; }; /** @@ -43,6 +42,5 @@ HWTEST_F( bool runOnCreate = true; AdvancedNotificationServiceAbility(systemAbilityId, runOnCreate); } - } // namespace Notification } // namespace OHOS diff --git a/services/ans/test/unittest/bundle_manager_helper_test.cpp b/services/ans/test/unittest/bundle_manager_helper_test.cpp index dc710da..4cde76e 100644 --- a/services/ans/test/unittest/bundle_manager_helper_test.cpp +++ b/services/ans/test/unittest/bundle_manager_helper_test.cpp @@ -25,13 +25,12 @@ 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() {}; }; /** 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 efde936..0d45485 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() {} @@ -46,12 +45,10 @@ bool BundleManagerHelper::IsSystemApp(int uid) { return (uid == SYSTEM_APP_UID); } - void BundleManagerHelper::Connect() {} void BundleManagerHelper::Disconnect() {} - } // 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 12a7f65..bdadec5 100644 --- a/services/ans/test/unittest/mock/mock_event_handler.cpp +++ b/services/ans/test/unittest/mock/mock_event_handler.cpp @@ -15,11 +15,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/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index 6cb5f77..b294f18 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -21,13 +21,12 @@ 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"; std::unique_ptr preferncesDB_ = @@ -173,7 +172,6 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutImportance_00200, Function | Sm */ HWTEST_F(NotificationPreferencesDatabaseTest, PutTotalBadgeNums_00100, Function | SmallTest | Level1) { - EXPECT_TRUE(preferncesDB_->PutTotalBadgeNums(bundleName_, 0)); } @@ -456,7 +454,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)); } @@ -494,6 +491,5 @@ HWTEST_F(NotificationPreferencesDatabaseTest, CheckBundle_00100, Function | Smal { EXPECT_EQ(true, preferncesDB_->CheckBundle(bundleName_)); } - } // 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 6c53534..f1ec114 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); diff --git a/services/ans/test/unittest/notification_slot_filter_test.cpp b/services/ans/test/unittest/notification_slot_filter_test.cpp index 15e72a0..7cc73fa 100644 --- a/services/ans/test/unittest/notification_slot_filter_test.cpp +++ b/services/ans/test/unittest/notification_slot_filter_test.cpp @@ -21,13 +21,12 @@ 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() {}; }; /** diff --git a/services/ans/test/unittest/notification_subscriber_manager_test.cpp b/services/ans/test/unittest/notification_subscriber_manager_test.cpp index 6ce1eee..eb8d6f7 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(); diff --git a/services/ans/test/unittest/permission_filter_test.cpp b/services/ans/test/unittest/permission_filter_test.cpp index 3aa2fa8..f1010e0 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(); }; diff --git a/services/test/moduletest/ans_module_test.cpp b/services/test/moduletest/ans_module_test.cpp index a967f8b..50b0708 100644 --- a/services/test/moduletest/ans_module_test.cpp +++ b/services/test/moduletest/ans_module_test.cpp @@ -1079,10 +1079,10 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0051, Function | SmallTest | Level1) slots.push_back(slot); g_advancedNotificationService->AddSlots(slots); - std::vector> slotsRef{}; + std::vector> slotsRef {}; g_advancedNotificationService->GetSlots(slotsRef); EXPECT_EQ(1, static_cast(slotsRef.size())); - std::vector slotsId{}; + std::vector slotsId {}; for (const auto &i : slotsRef) { slotsId.push_back(i->GetId()); } @@ -1104,9 +1104,9 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0052, Function | SmallTest | Level1) slots.push_back(slot); g_advancedNotificationService->AddSlots(slots); - std::vector> slotsRef{}; + std::vector> slotsRef {}; g_advancedNotificationService->GetSlots(slotsRef); - std::vector slotsId{}; + std::vector slotsId {}; for (const auto &i : slotsRef) { slotsId.push_back(i->GetId()); } @@ -1620,7 +1620,6 @@ HWTEST_F(AnsModuleTest, AnsModuleTest_0103, Function | SmallTest | Level1) */ HWTEST_F(AnsModuleTest, AnsModuleTest_0105, Function | SmallTest | Level1) { - std::vector> slots; sptr socialSlot = new NotificationSlot(NotificationConstant::SlotType::SOCIAL_COMMUNICATION); sptr reminderSlot = new NotificationSlot(NotificationConstant::SlotType::SERVICE_REMINDER); diff --git a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 5738fc8..7839b90 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -274,6 +274,5 @@ bool BundleMgrProxy::SendTransactCmd(IBundleMgr::Message code, MessageParcel &da { return true; } - } // namespace AppExecFwk } // namespace OHOS diff --git a/services/test/moduletest/mock/mock_event_handler.cpp b/services/test/moduletest/mock/mock_event_handler.cpp index 12a7f65..bbbeb49 100644 --- a/services/test/moduletest/mock/mock_event_handler.cpp +++ b/services/test/moduletest/mock/mock_event_handler.cpp @@ -15,7 +15,6 @@ #include "event_handler.h" #include "event_handler_utils.h" -#include namespace OHOS { namespace AppExecFwk { diff --git a/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h index cdab5c1..4e20ffb 100644 --- a/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h +++ b/test/resource/ansSTSlotGroupTest/include/ans_slotgroup_test.h @@ -26,7 +26,6 @@ namespace OHOS { namespace AppExecFwk { - class AnsSlotGroupSystemTest : public Ability { protected: virtual void OnStart(const Want &want) override; @@ -45,7 +44,6 @@ private: std::string targetBundle; std::string targetAbility; }; - } // namespace AppExecFwk } // namespace OHOS #endif \ No newline at end of file diff --git a/tools/dump/include/notification_shell_command.h b/tools/dump/include/notification_shell_command.h index b881ffa..ae1b2f8 100644 --- a/tools/dump/include/notification_shell_command.h +++ b/tools/dump/include/notification_shell_command.h @@ -23,11 +23,10 @@ namespace OHOS { namespace Notification { - class NotificationShellCommand : public OHOS::AAFwk::ShellCommand { public: NotificationShellCommand(int argc, char *argv[]); - ~NotificationShellCommand() override{}; + ~NotificationShellCommand() override {}; private: ErrCode CreateCommandMap() override; @@ -39,7 +38,6 @@ private: private: std::shared_ptr ans_; }; - } // namespace Notification } // namespace OHOS #endif // BASE_NOTIFICATION_ANS_STANDARD_TOOLS_DUMP_INCLUDE_NOTIFICATION_SHELL_COMMAND_H \ No newline at end of file diff --git a/tools/dump/src/main.cpp b/tools/dump/src/main.cpp index 3a650b7..b9557ac 100644 --- a/tools/dump/src/main.cpp +++ b/tools/dump/src/main.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ -#include #include "notification_shell_command.h" -- Gitee From e19c7353fe0787106065ae03acefca972301d48b Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 13 Dec 2021 17:10:20 +0000 Subject: [PATCH 048/131] Add ClearActionButtons() in NotificationRequest Signed-off-by: zhaoyuan17 --- frameworks/ans/native/src/notification_request.cpp | 5 +++++ .../innerkits/ans/native/include/notification_request.h | 5 +++++ 2 files changed, 10 insertions(+) diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 1ea18d3..c929327 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -299,6 +299,11 @@ const std::vector> NotificationRequest return actionButtons_; } +void NotificationRequest::ClearActionButtons() +{ + actionButtons_.clear(); +} + bool NotificationRequest::IsPermitSystemGeneratedContextualActionButtons() const { return permitted_; diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index ad1b078..611c0d0 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -339,6 +339,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. -- Gitee From d75511353d1526ee3efbca83845a2992ff37ac66 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Thu, 16 Dec 2021 17:03:56 +0000 Subject: [PATCH 049/131] Modify delete reason for Continuous Task Signed-off-by: zhaoyuan17 --- .../ans/core/include/ans_manager_interface.h | 4 +- frameworks/ans/core/src/ans_manager_proxy.cpp | 4 +- frameworks/ans/core/src/ans_manager_stub.cpp | 4 +- .../test/moduletest/ans_fw_module_test.cpp | 16 ++++---- services/ans/include/disturb_filter.h | 39 ------------------- .../ans/src/advanced_notification_service.cpp | 2 +- 6 files changed, 15 insertions(+), 54 deletions(-) delete mode 100644 services/ans/include/disturb_filter.h diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index fae8fdf..8513f4f 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -170,8 +170,8 @@ protected: CANCEL_GROUP, REMOVE_GROUP_BY_BUNDLE, SHELL_DUMP, - PUBLISH_LONG_TASK_NOTIFICATION, - CANCEL_LONG_TASK_NOTIFICATION, + PUBLISH_CONTINUOUS_TASK_NOTIFICATION, + CANCEL_CONTINUOUS_TASK_NOTIFICATION, }; }; } // namespace Notification diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index f3889d7..cdde8d2 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1894,7 +1894,7 @@ ErrCode AnsManagerProxy::PublishContinuousTaskNotification(const sptr &record) override; - -private: - void GetTimeInterval(int64_t &beginDate, int64_t &endDate); -}; -} // namespace Notification -} // namespace OHOS - -#endif // BASE_NOTIFICATION_ANS_STANDARD_SERVICES_ANS_INCLUDE_DISTURB_FILTER_H \ No newline at end of file diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 1af9f66..c0995fc 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1367,7 +1367,7 @@ ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std: } } if (notification != nullptr) { - int reason = NotificationConstant::CANCEL_REASON_DELETE; + int reason = NotificationConstant::APP_CANCEL_REASON_DELETE; UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); -- Gitee From cb581fc8d9035ff0d95c2d98a38bcdc246966a80 Mon Sep 17 00:00:00 2001 From: zhongjianfei Date: Sat, 18 Dec 2021 10:42:42 +0800 Subject: [PATCH 050/131] zhongjianfei@huawei.com Signed-off-by: zhongjianfei Change-Id: I7f2aa297e80e8d40836e7cdcf40310ef39b400ce --- interfaces/kits/napi/ans/BUILD.gn | 2 -- 1 file changed, 2 deletions(-) diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 66da342..2d7176e 100755 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -61,8 +61,6 @@ 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", -- Gitee From 0b0cff6528de8f3f9f25ad9514f9bd611c1f067a Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sat, 18 Dec 2021 11:24:51 +0000 Subject: [PATCH 051/131] Conversational Notification and code format Signed-off-by: zhaoyuan17 --- .../ans/core/include/ans_manager_interface.h | 2 +- .../ans/core/include/ans_notification.h | 6 - frameworks/ans/core/src/ans_notification.cpp | 2 - frameworks/ans/native/BUILD.gn | 0 frameworks/ans/native/src/message_user.cpp | 16 +- frameworks/ans/native/src/notification.cpp | 2 +- .../native/src/notification_action_button.cpp | 52 +++- .../native/src/notification_bundle_option.cpp | 5 +- .../ans/native/src/notification_content.cpp | 88 ++---- .../notification_conversational_content.cpp | 21 +- .../notification_conversational_message.cpp | 12 +- .../src/notification_do_not_disturb_date.cpp | 9 +- .../src/notification_long_text_content.cpp | 10 +- .../native/src/notification_media_content.cpp | 10 +- .../src/notification_multiline_content.cpp | 9 +- .../src/notification_normal_content.cpp | 4 +- .../src/notification_picture_content.cpp | 9 +- .../ans/native/src/notification_request.cpp | 84 +++--- .../ans/native/src/notification_slot.cpp | 31 +- .../native/src/notification_slot_group.cpp | 14 +- .../ans/native/src/notification_sorting.cpp | 24 +- .../native/src/notification_sorting_map.cpp | 22 +- .../src/notification_subscribe_info.cpp | 11 +- .../native/src/notification_user_input.cpp | 59 ++-- frameworks/ans/test/moduletest/BUILD.gn | 0 .../ans_innerkits_module_publish_test.cpp | 14 +- .../mock/include/mock_ipc_skeleton.h | 0 .../wantagent/src/want_agent_helper.cpp | 10 +- .../ans/native/include/notification.h | 3 - .../include/notification_action_button.h | 24 +- .../include/notification_bundle_option.h | 1 - .../native/include/notification_constant.h | 2 +- .../ans/native/include/notification_content.h | 10 +- .../notification_conversational_content.h | 3 - .../notification_conversational_message.h | 2 - .../ans/native/include/notification_helper.h | 2 +- .../include/notification_long_text_content.h | 2 - .../include/notification_media_content.h | 3 - .../include/notification_multiline_content.h | 2 - .../include/notification_normal_content.h | 1 - .../include/notification_picture_content.h | 4 +- .../ans/native/include/notification_request.h | 13 +- .../ans/native/include/notification_slot.h | 2 - .../native/include/notification_slot_group.h | 2 - .../ans/native/include/notification_sorting.h | 3 - .../native/include/notification_sorting_map.h | 4 - .../include/notification_subscribe_info.h | 4 - .../native/include/notification_subscriber.h | 2 - .../native/include/notification_user_input.h | 45 ++- interfaces/kits/napi/ans/BUILD.gn | 0 interfaces/kits/napi/ans/include/common.h | 19 +- interfaces/kits/napi/ans/include/constant.h | 5 +- interfaces/kits/napi/ans/include/publish.h | 1 - interfaces/kits/napi/ans/src/cancel.cpp | 22 +- interfaces/kits/napi/ans/src/common.cpp | 82 ++--- interfaces/kits/napi/ans/src/constant.cpp | 1 - .../kits/napi/ans/src/display_badge.cpp | 104 +++---- interfaces/kits/napi/ans/src/disturb_mode.cpp | 8 +- .../kits/napi/ans/src/enable_notification.cpp | 133 +++++---- interfaces/kits/napi/ans/src/publish.cpp | 11 +- interfaces/kits/napi/ans/src/remove.cpp | 103 +++---- interfaces/kits/napi/ans/src/slot.cpp | 282 +++++++++--------- interfaces/kits/napi/ans/src/subscribe.cpp | 18 +- interfaces/kits/napi/ans/src/unsubscribe.cpp | 10 +- sa_profile/3203.xml | 0 services/ans/test/unittest/mock/blob.cpp | 0 .../unittest/mock/include/mock_ipc_skeleton.h | 0 services/test/moduletest/mock/blob.cpp | 0 .../acts/actsnotificationfuzztest/BUILD.gn | 0 .../ansSlotGroupHap/AnsSTSlotGroupTest.hap | Bin 70 files changed, 726 insertions(+), 733 deletions(-) mode change 100755 => 100644 frameworks/ans/native/BUILD.gn mode change 100755 => 100644 frameworks/ans/test/moduletest/BUILD.gn mode change 100755 => 100644 frameworks/ans/test/moduletest/mock/include/mock_ipc_skeleton.h mode change 100755 => 100644 interfaces/kits/napi/ans/BUILD.gn mode change 100755 => 100644 sa_profile/3203.xml mode change 100755 => 100644 services/ans/test/unittest/mock/blob.cpp mode change 100755 => 100644 services/ans/test/unittest/mock/include/mock_ipc_skeleton.h mode change 100755 => 100644 services/test/moduletest/mock/blob.cpp mode change 100755 => 100644 test/common/acts/actsnotificationfuzztest/BUILD.gn mode change 100755 => 100644 test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index 8513f4f..be9a8b1 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -27,7 +27,6 @@ #include "notification_request.h" #include "notification_slot.h" #include "notification_slot_group.h" -#include "notification_sorting.h" #include "notification_subscribe_info.h" namespace OHOS { @@ -106,6 +105,7 @@ public: 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; diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index f95a82d..e030626 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -20,12 +20,6 @@ #include "ans_manager_death_recipient.h" #include "ans_manager_interface.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" -#include "notification_sorting_map.h" #include "notification_subscriber.h" namespace OHOS { diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 2e8b480..f6d751e 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -18,8 +18,6 @@ #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "iservice_registry.h" -#include "notification_request.h" -#include "notification_sorting.h" #include "system_ability_definition.h" namespace OHOS { diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn old mode 100755 new mode 100644 diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index 4e1632a..82a6425 100644 --- a/frameworks/ans/native/src/message_user.cpp +++ b/frameworks/ans/native/src/message_user.cpp @@ -88,12 +88,14 @@ 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::Marshalling(Parcel &parcel) const @@ -181,7 +183,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 77b1f58..40636e8 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -309,7 +309,7 @@ void Notification::ReadFromParcelString(Parcel &parcel) { // Read key_ key_ = parcel.ReadString(); - + // Read sound_ if (enableSound_) { sound_ = std::make_shared(parcel.ReadString()); diff --git a/frameworks/ans/native/src/notification_action_button.cpp b/frameworks/ans/native/src/notification_action_button.cpp index 94cd2a7..b129a54 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -21,7 +21,7 @@ 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) { @@ -32,9 +32,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 {}; } } @@ -86,7 +86,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), @@ -115,12 +115,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_; } @@ -192,10 +194,34 @@ 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::Marshalling(Parcel &parcel) const @@ -286,7 +312,7 @@ bool NotificationActionButton::Marshalling(Parcel &parcel) const NotificationActionButton *NotificationActionButton::Unmarshalling(Parcel &parcel) { - auto pButton = new NotificationActionButton(); + auto pButton = new (std::nothrow) NotificationActionButton(); if ((pButton != nullptr) && !pButton->ReadFromParcel(parcel)) { delete pButton; pButton = nullptr; @@ -330,7 +356,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; diff --git a/frameworks/ans/native/src/notification_bundle_option.cpp b/frameworks/ans/native/src/notification_bundle_option.cpp index 4269aca..402d186 100644 --- a/frameworks/ans/native/src/notification_bundle_option.cpp +++ b/frameworks/ans/native/src/notification_bundle_option.cpp @@ -47,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 diff --git a/frameworks/ans/native/src/notification_content.cpp b/frameworks/ans/native/src/notification_content.cpp index 5f302bb..f76e41e 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -106,8 +106,10 @@ 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::Marshalling(Parcel &parcel) const @@ -135,7 +137,7 @@ bool NotificationContent::Marshalling(Parcel &parcel) const NotificationContent *NotificationContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationContent(); + auto pContent = new (std::nothrow) NotificationContent(); if ((pContent != nullptr) && !pContent->ReadFromParcel(parcel)) { delete pContent; pContent = nullptr; @@ -154,68 +156,38 @@ 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); + case NotificationContent::Type::BASIC_TEXT: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); 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); + case NotificationContent::Type::CONVERSATION: + content_ = + std::static_pointer_cast(std::shared_ptr( + parcel.ReadParcelable())); 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); + case NotificationContent::Type::LONG_TEXT: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); 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); + case NotificationContent::Type::MEDIA: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); 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); + case NotificationContent::Type::MULTILINE: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); 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); + case NotificationContent::Type::PICTURE: + content_ = std::static_pointer_cast( + std::shared_ptr(parcel.ReadParcelable())); break; - } - default: { + default: + ANS_LOGE("Invalid contentType"); return false; - } + } + if (!content_) { + ANS_LOGE("Failed to read content"); + return false; } return true; diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 102a984..1378513 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -76,10 +76,21 @@ 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::Marshalling(Parcel &parcel) const @@ -132,7 +143,7 @@ bool NotificationConversationalContent::Marshalling(Parcel &parcel) const NotificationConversationalContent *NotificationConversationalContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationConversationalContent(); + 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 139826a..1f385c0 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -56,9 +56,13 @@ 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::Marshalling(Parcel &parcel) const @@ -101,7 +105,7 @@ bool NotificationConversationalMessage::Marshalling(Parcel &parcel) const NotificationConversationalMessage *NotificationConversationalMessage::Unmarshalling(Parcel &parcel) { - auto pMessage = new NotificationConversationalMessage(); + auto pMessage = new (std::nothrow) NotificationConversationalMessage(); if ((pMessage != nullptr) && !pMessage->ReadFromParcel(parcel)) { delete pMessage; pMessage = nullptr; diff --git a/frameworks/ans/native/src/notification_do_not_disturb_date.cpp b/frameworks/ans/native/src/notification_do_not_disturb_date.cpp index 4492263..188018f 100644 --- a/frameworks/ans/native/src/notification_do_not_disturb_date.cpp +++ b/frameworks/ans/native/src/notification_do_not_disturb_date.cpp @@ -55,10 +55,11 @@ int64_t NotificationDoNotDisturbDate::GetEndDate() const std::string NotificationDoNotDisturbDate::Dump() { - return "NotificationDoNotDisturbDate[ "\ - "doNotDisturbType = " + std::to_string(static_cast(doNotDisturbType_)) + - ", beginDate = " + std::to_string(beginDate_) + - ", endDate = " + std::to_string(endDate_) + " ]"; + 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 diff --git a/frameworks/ans/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp index 1ce547b..fb30530 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -63,9 +63,11 @@ 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::Marshalling(Parcel &parcel) const @@ -95,7 +97,7 @@ bool NotificationLongTextContent::Marshalling(Parcel &parcel) const NotificationLongTextContent *NotificationLongTextContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationLongTextContent(); + 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 252240b..e1c303d 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -42,11 +42,13 @@ 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::Marshalling(Parcel &parcel) const @@ -66,7 +68,7 @@ bool NotificationMediaContent::Marshalling(Parcel &parcel) const NotificationMediaContent *NotificationMediaContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationMediaContent(); + 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 d20acf4..320c23b 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -63,8 +63,11 @@ 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::Marshalling(Parcel &parcel) const @@ -94,7 +97,7 @@ bool NotificationMultiLineContent::Marshalling(Parcel &parcel) const NotificationMultiLineContent *NotificationMultiLineContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationMultiLineContent(); + 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 481c1aa..d6743d1 100644 --- a/frameworks/ans/native/src/notification_normal_content.cpp +++ b/frameworks/ans/native/src/notification_normal_content.cpp @@ -19,7 +19,7 @@ namespace OHOS { namespace Notification { std::string NotificationNormalContent::Dump() { - return "NotificationNormalContent[ " + NotificationBasicContent::Dump() + " ]"; + return "NotificationNormalContent{ " + NotificationBasicContent::Dump() + " }"; } bool NotificationNormalContent::Marshalling(Parcel &parcel) const @@ -29,7 +29,7 @@ bool NotificationNormalContent::Marshalling(Parcel &parcel) const NotificationNormalContent *NotificationNormalContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationNormalContent(); + 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 b2aa8af..d7e65d4 100644 --- a/frameworks/ans/native/src/notification_picture_content.cpp +++ b/frameworks/ans/native/src/notification_picture_content.cpp @@ -50,8 +50,11 @@ 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::Marshalling(Parcel &parcel) const @@ -89,7 +92,7 @@ bool NotificationPictureContent::Marshalling(Parcel &parcel) const NotificationPictureContent *NotificationPictureContent::Unmarshalling(Parcel &parcel) { - auto pContent = new NotificationPictureContent(); + 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 c7a41c8..bbf4e13 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -716,46 +716,48 @@ std::string NotificationRequest::GetLabel() const 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_ + ", 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") + - ", 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") + + ", 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_ ? notificationContent_->Dump() : "null") + + ", publicNotification = " + (publicNotification_ ? "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") + + " }"; } bool NotificationRequest::Marshalling(Parcel &parcel) const @@ -1092,7 +1094,7 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const NotificationRequest *NotificationRequest::Unmarshalling(Parcel &parcel) { - auto objptr = new NotificationRequest(); + auto objptr = new (std::nothrow) NotificationRequest(); if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; diff --git a/frameworks/ans/native/src/notification_slot.cpp b/frameworks/ans/native/src/notification_slot.cpp index 00f7a5b..04f4c9c 100644 --- a/frameworks/ans/native/src/notification_slot.cpp +++ b/frameworks/ans/native/src/notification_slot.cpp @@ -202,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 @@ -334,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 89720f8..c870357 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 @@ -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 fc390cf..4e0c410 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -53,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 @@ -143,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 8e32c8b..2bd73d2 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 7f42398..0f70d04 100644 --- a/frameworks/ans/native/src/notification_subscribe_info.cpp +++ b/frameworks/ans/native/src/notification_subscribe_info.cpp @@ -57,7 +57,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; @@ -74,7 +74,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_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index e8ed66a..eb0387f 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -32,10 +32,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 {}; } @@ -68,7 +68,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()) { @@ -88,13 +88,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 {}; @@ -104,18 +104,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) {} @@ -124,14 +124,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) @@ -215,11 +217,14 @@ 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::Marshalling(Parcel &parcel) const @@ -244,15 +249,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; } } @@ -279,7 +284,7 @@ bool NotificationUserInput::Marshalling(Parcel &parcel) const NotificationUserInput *NotificationUserInput::Unmarshalling(Parcel &parcel) { - auto pUserInput = new NotificationUserInput(); + auto pUserInput = new (std::nothrow) NotificationUserInput(); if ((pUserInput != nullptr) && !pUserInput->ReadFromParcel(parcel)) { delete pUserInput; pUserInput = nullptr; @@ -306,9 +311,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; } } diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn old mode 100755 new mode 100644 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 65a4ab2..2c14f23 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -561,17 +561,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); @@ -622,8 +622,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); 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/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index fcb6d27..33135ef 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -152,7 +152,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(); + wantSenderInfo.type = (int32_t)paramsInfo.GetOperationType(); sptr target = AbilityManagerClient::GetInstance()->GetWantSender(wantSenderInfo, nullptr); if (target == nullptr) { @@ -308,13 +308,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; } @@ -325,13 +325,13 @@ 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; } diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index 7503e15..e2e71ea 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -16,9 +16,6 @@ #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" diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index 8cb3e39..a1a0f9a 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -16,15 +16,11 @@ #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_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 { @@ -35,7 +31,7 @@ public: * @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 +44,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 +85,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. @@ -199,7 +195,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 +204,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 +219,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_bundle_option.h b/interfaces/innerkits/ans/native/include/notification_bundle_option.h index 4ea4fb0..992bfff 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 { diff --git a/interfaces/innerkits/ans/native/include/notification_constant.h b/interfaces/innerkits/ans/native/include/notification_constant.h index 1f710ef..f3dd82c 100644 --- a/interfaces/innerkits/ans/native/include/notification_constant.h +++ b/interfaces/innerkits/ans/native/include/notification_constant.h @@ -105,7 +105,7 @@ public: */ 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 ea5abb8..9d5ebda 100644 --- a/interfaces/innerkits/ans/native/include/notification_content.h +++ b/interfaces/innerkits/ans/native/include/notification_content.h @@ -16,15 +16,13 @@ #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_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 { diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_content.h b/interfaces/innerkits/ans/native/include/notification_conversational_content.h index 7ff86ba..e352651 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -16,9 +16,6 @@ #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" diff --git a/interfaces/innerkits/ans/native/include/notification_conversational_message.h b/interfaces/innerkits/ans/native/include/notification_conversational_message.h index 06eb0b3..d46aacc 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_message.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_message.h @@ -16,8 +16,6 @@ #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 "parcel.h" #include "uri.h" diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index 0395b63..a5d94f4 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -524,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); 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 b64685f..c6ffcb6 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" diff --git a/interfaces/innerkits/ans/native/include/notification_media_content.h b/interfaces/innerkits/ans/native/include/notification_media_content.h index c725db2..54d90d2 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" diff --git a/interfaces/innerkits/ans/native/include/notification_multiline_content.h b/interfaces/innerkits/ans/native/include/notification_multiline_content.h index 485f6c1..a3d216f 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" diff --git a/interfaces/innerkits/ans/native/include/notification_normal_content.h b/interfaces/innerkits/ans/native/include/notification_normal_content.h index 4bb177e..cae7525 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" diff --git a/interfaces/innerkits/ans/native/include/notification_picture_content.h b/interfaces/innerkits/ans/native/include/notification_picture_content.h index 91a3dd8..df45286 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 { diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index a18b7d6..1e8a22b 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -16,17 +16,14 @@ #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 "context.h" #include "message_user.h" #include "notification_action_button.h" #include "notification_content.h" -#include "want_agent.h" -#include "context.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 { @@ -859,7 +856,7 @@ public: /** * Unmarshal object from a Parcel. - * @return the NotificationRequest + * @return the NotificationRequest. */ static NotificationRequest *Unmarshalling(Parcel &parcel); @@ -878,7 +875,7 @@ private: * the maximum number of action buttons is 3. */ static const std::size_t MAX_ACTION_BUTTONS; - + private: /** * Read a NotificationRequest object from a Parcel. diff --git a/interfaces/innerkits/ans/native/include/notification_slot.h b/interfaces/innerkits/ans/native/include/notification_slot.h index b8adaaf..6b53430 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" diff --git a/interfaces/innerkits/ans/native/include/notification_slot_group.h b/interfaces/innerkits/ans/native/include/notification_slot_group.h index bcba439..7becaca 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 { diff --git a/interfaces/innerkits/ans/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h index da7810b..cc02e74 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" diff --git a/interfaces/innerkits/ans/native/include/notification_sorting_map.h b/interfaces/innerkits/ans/native/include/notification_sorting_map.h index 0fe5e4b..cd7d83a 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting_map.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting_map.h @@ -16,10 +16,6 @@ #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" diff --git a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h index bb5ede5..7043ae6 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h +++ b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h @@ -16,10 +16,6 @@ #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 { diff --git a/interfaces/innerkits/ans/native/include/notification_subscriber.h b/interfaces/innerkits/ans/native/include/notification_subscriber.h index 688959d..aefa50b 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscriber.h +++ b/interfaces/innerkits/ans/native/include/notification_subscriber.h @@ -16,8 +16,6 @@ #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_request.h" diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 1327bca..74420e9 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -16,15 +16,10 @@ #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 "parcel.h" #include "uri.h" +#include "want.h" namespace OHOS { namespace Notification { @@ -50,22 +45,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 +81,7 @@ 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 +89,14 @@ 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 +104,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 +119,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. @@ -236,13 +231,13 @@ 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 +245,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 +265,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/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn old mode 100755 new mode 100644 diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 0f2075e..ca2751f 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -28,6 +28,9 @@ 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 class ContentType { NOTIFICATION_CONTENT_BASIC_TEXT, @@ -284,10 +287,14 @@ 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 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 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); @@ -371,7 +378,7 @@ public: 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, BundleOption &option); + 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); @@ -400,8 +407,6 @@ public: 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_; diff --git a/interfaces/kits/napi/ans/include/constant.h b/interfaces/kits/napi/ans/include/constant.h index 5eb46c1..323a4fd 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 { diff --git a/interfaces/kits/napi/ans/include/publish.h b/interfaces/kits/napi/ans/include/publish.h index 2f64e25..6d84052 100644 --- a/interfaces/kits/napi/ans/include/publish.h +++ b/interfaces/kits/napi/ans/include/publish.h @@ -15,7 +15,6 @@ #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 { diff --git a/interfaces/kits/napi/ans/src/cancel.cpp b/interfaces/kits/napi/ans/src/cancel.cpp index 1632d1f..799bc5c 100644 --- a/interfaces/kits/napi/ans/src/cancel.cpp +++ b/interfaces/kits/napi/ans/src/cancel.cpp @@ -59,31 +59,31 @@ 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); @@ -101,18 +101,18 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_valuetype valuetype = napi_undefined; // argv[0]: groupName: string - NAPI_CALL(env, napi_typeof(env, argv[0], &valuetype)); + 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[0], str, STR_MAX_SIZE - 1, &strLen)); + 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[CANCEL_GROUP_MIN_PARA], &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[CANCEL_GROUP_MIN_PARA], 1, ¶s.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 3e67eac..c995c0e 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -14,14 +14,8 @@ */ #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 { @@ -160,9 +154,9 @@ napi_value Common::ParseParaOnlyCallback(const napi_env &env, const napi_callbac // argv[0]:callback napi_valuetype valuetype = napi_undefined; if (argc >= ONLY_CALLBACK_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[ONLY_CALLBACK_MIN_PARA], &valuetype)); + 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[ONLY_CALLBACK_MIN_PARA], 1, &callback); + napi_create_reference(env, argv[PARAM0], 1, &callback); } return Common::NapiGetNull(env); @@ -1133,9 +1127,12 @@ napi_value Common::SetNotificationActionButtonByExtras( const napi_env &env, const std::shared_ptr &actionButton, napi_value &result) { ANS_LOGI("enter"); - + if (!actionButton) { + ANS_LOGE("actionButton is null"); + return NapiGetBoolean(env, false); + } // extras?: {[key: string]: any} - std::shared_ptr extras = nullptr; + auto extras = actionButton->GetAdditionalData(); if (extras) { napi_value nExtras = nullptr; nExtras = OHOS::AppExecFwk::WrapWantParams(env, *extras); @@ -1197,8 +1194,8 @@ napi_value Common::SetNotificationActionButtonByUserInput( napi_create_int64(env, userInput->GetEditType(), &value); napi_set_named_property(env, result, "editType", value); - // additionalData?: {[key: string]: any} - std::shared_ptr additionalData = nullptr; + // additionalData?: {[key: string]: Object} + auto additionalData = userInput->GetAdditionalData(); if (additionalData) { napi_value nAdditionalData = nullptr; nAdditionalData = OHOS::AppExecFwk::WrapWantParams(env, *additionalData); @@ -2131,6 +2128,7 @@ napi_value Common::GetNotificationActionButtonsDetailedByExtras( if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { return nullptr; } + pActionButton->AddAdditionalData(wantParams); } return NapiGetNull(env); } @@ -2223,14 +2221,13 @@ napi_value Common::GetNotificationUserInputByTag( // tag: string NAPI_CALL(env, napi_has_named_property(env, userInputResult, "tag", &hasProperty)); - if (hasProperty) { - 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); - } + 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); return NapiGetNull(env); } @@ -2254,24 +2251,24 @@ napi_value Common::GetNotificationUserInputByOptions( // options: Array NAPI_CALL(env, napi_has_named_property(env, userInputResult, "options", &hasProperty)); - if (hasProperty) { - 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, option, str, STR_MAX_SIZE - 1, &strLen)); - options.emplace_back(str); - } - userInput->SetOptions(options); + 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, option, str, STR_MAX_SIZE - 1, &strLen)); + options.emplace_back(str); } + userInput->SetOptions(options); + return NapiGetNull(env); } @@ -2382,7 +2379,7 @@ napi_value Common::GetNotificationUserInputByAdditionalData( return nullptr; } - // additionalData?: {[key: string]: any} + // 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); @@ -2392,6 +2389,7 @@ napi_value Common::GetNotificationUserInputByAdditionalData( if (!OHOS::AppExecFwk::UnwrapWantParams(env, result, wantParams)) { return nullptr; } + userInput->AddAdditionalData(wantParams); } return NapiGetNull(env); @@ -3396,7 +3394,7 @@ napi_value Common::GetNotificationSlotByVibration(const napi_env &env, const nap 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"); @@ -3413,15 +3411,17 @@ napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, NAPI_CALL(env, napi_typeof(env, result, &valuetype)); NAPI_ASSERT(env, valuetype == napi_string, "Wrong argument type. String expected."); NAPI_CALL(env, napi_get_value_string_utf8(env, result, str, STR_MAX_SIZE - 1, &strLen)); - option.bundle = str; + 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); + napi_get_value_int32(env, result, &uid); + option.SetUid(uid); } return NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/constant.cpp b/interfaces/kits/napi/ans/src/constant.cpp index 96e3e42..29fefc6 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 { diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 214b87b..737e640 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -22,7 +22,7 @@ const int ENABLE_BADGE_DISPLAYED_MIN_PARA = 2; const int IS_DISPLAY_BADGE_MAX_PARA = 2; struct EnableBadgeParams { - BundleOption option; + NotificationBundleOption option; bool enable = false; napi_ref callback = nullptr; }; @@ -35,7 +35,7 @@ struct AsyncCallbackInfoEnableBadge { }; struct IsDisplayBadgeParams { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; bool hasBundleOption = false; }; @@ -60,24 +60,24 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // 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)); + 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[1], &valuetype)); + 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[1], ¶ms.enable); + 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_CALL(env, napi_typeof(env, argv[PARAM2], &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_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -98,26 +98,26 @@ 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_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_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_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); @@ -149,15 +149,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,6 +185,30 @@ 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"); @@ -215,40 +236,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); diff --git a/interfaces/kits/napi/ans/src/disturb_mode.cpp b/interfaces/kits/napi/ans/src/disturb_mode.cpp index d9b056f..a27ba19 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -112,17 +112,17 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[0]: date 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."); - if (GetDoNotDisturbDate(env, argv[0], params) == nullptr) { + if (GetDoNotDisturbDate(env, argv[PARAM0], params) == nullptr) { return nullptr; } // argv[1]:callback if (argc >= SET_DISTURB_MAX_PARA) { - NAPI_CALL(env, napi_typeof(env, argv[SET_DISTURB_MIN_PARA], &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[SET_DISTURB_MIN_PARA], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } return Common::NapiGetNull(env); diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index f0d943a..7850a4f 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; }; @@ -60,24 +60,24 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // 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)); + 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[1], &valuetype)); + 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[1], ¶ms.enable); + 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_CALL(env, napi_typeof(env, argv[PARAM2], &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_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -98,31 +98,53 @@ 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_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_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_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); } +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 +171,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 +189,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 +241,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); diff --git a/interfaces/kits/napi/ans/src/publish.cpp b/interfaces/kits/napi/ans/src/publish.cpp index d94182c..b544ea7 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 { @@ -56,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; } } diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index cd9faf5..be24eca 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 { @@ -33,7 +31,7 @@ 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; }; @@ -51,7 +49,7 @@ struct AsyncCallbackInfoRemove { }; struct RemoveParamsGroupByBundle { - BundleOption option; + NotificationBundleOption option; std::string groupName = ""; napi_ref callback = nullptr; }; @@ -74,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."); @@ -82,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; @@ -113,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); } } @@ -136,25 +134,25 @@ 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); } } @@ -174,27 +172,27 @@ napi_value ParseParameters( NAPI_ASSERT(env, argc >= REMOVE_GROUP_BY_BUNDLE_MIN_PARA, "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]: groupName: string - NAPI_CALL(env, napi_typeof(env, argv[1], &valuetype)); + 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[1], str, STR_MAX_SIZE - 1, &strLen)); + 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[REMOVE_GROUP_BY_BUNDLE_MIN_PARA], &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_GROUP_BY_BUNDLE_MIN_PARA], 1, ¶ms.callback); + napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } return Common::NapiGetNull(env); @@ -233,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) { @@ -296,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(); } @@ -330,6 +326,28 @@ 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"); @@ -356,31 +374,14 @@ napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info) [](napi_env env, void *data) { ANS_LOGI("RemoveGroupByBundle napi_create_async_work start"); AsyncCallbackInfoRemoveGroupByBundle *asynccallbackinfo = (AsyncCallbackInfoRemoveGroupByBundle *)data; - NotificationBundleOption bundleOption( - asynccallbackinfo->params.option.bundle, asynccallbackinfo->params.option.uid); ANS_LOGI("option.bundle = %{public}s, option.uid = %{public}d, groupName = %{public}s", - asynccallbackinfo->params.option.bundle.c_str(), - asynccallbackinfo->params.option.uid, + asynccallbackinfo->params.option.GetBundleName().c_str(), + asynccallbackinfo->params.option.GetUid(), asynccallbackinfo->params.groupName.c_str()); - asynccallbackinfo->info.errorCode = - NotificationHelper::RemoveGroupByBundle(bundleOption, asynccallbackinfo->params.groupName); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("RemoveGroupByBundle napi_create_async_work end"); - 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; - } + asynccallbackinfo->info.errorCode = NotificationHelper::RemoveGroupByBundle( + asynccallbackinfo->params.option, asynccallbackinfo->params.groupName); }, + AsyncCompleteCallbackRemoveGroupByBundle, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/slot.cpp b/interfaces/kits/napi/ans/src/slot.cpp index 15d0156..7eab91e 100644 --- a/interfaces/kits/napi/ans/src/slot.cpp +++ b/interfaces/kits/napi/ans/src/slot.cpp @@ -54,7 +54,7 @@ struct AsyncCallbackInfoAddSlots { }; struct ParametersInfoSetSlotByBundle { - BundleOption option; + NotificationBundleOption option; std::vector> slots; napi_ref callback = nullptr; }; @@ -80,7 +80,7 @@ struct AsyncCallbackInfoGetSlot { }; struct ParametersInfoGetSlotNumByBundle { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; }; @@ -100,7 +100,7 @@ struct AsyncCallbackInfoGetSlots { }; struct ParametersInfoGetSlotsByBundle { - BundleOption option; + NotificationBundleOption option; napi_ref callback = nullptr; }; @@ -141,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); } @@ -179,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; @@ -198,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); } @@ -218,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; @@ -247,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); @@ -266,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); } @@ -296,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; @@ -306,9 +306,9 @@ 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); @@ -327,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; @@ -337,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); @@ -357,19 +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); + napi_create_reference(env, argv[PARAM1], 1, ¶s.callback); } return Common::NapiGetNull(env); } @@ -522,11 +522,8 @@ napi_value SetSlotByBundle(napi_env env, napi_callback_info info) ANS_LOGI("SetSlotByBundle napi_create_async_work start"); 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"); @@ -662,11 +659,8 @@ napi_value GetSlotNumByBundle(napi_env env, napi_callback_info info) ANS_LOGI("GetSlotNumByBundle napi_create_async_work start"); auto asynccallbackinfo = (AsyncCallbackInfoGetSlotNumByBundle *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - asynccallbackinfo->info.errorCode = - NotificationHelper::GetNotificationSlotNumAsBundle(bundleOption, asynccallbackinfo->num); + 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"); @@ -697,6 +691,54 @@ 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"); @@ -725,48 +767,7 @@ napi_value GetSlots(napi_env env, napi_callback_info info) auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlots(asynccallbackinfo->slots); }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlots napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoGetSlots *)data; - napi_value result = nullptr; - 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; - } - }, + AsyncCompleteCallbackGetSlots, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -779,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"); @@ -806,55 +855,10 @@ napi_value GetSlotsByBundle(napi_env env, napi_callback_info info) ANS_LOGI("GetSlotsByBundle napi_create_async_work start"); auto asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; - NotificationBundleOption bundleOption; - bundleOption.SetBundleName(asynccallbackinfo->params.option.bundle); - bundleOption.SetUid(asynccallbackinfo->params.option.uid); - asynccallbackinfo->info.errorCode = - NotificationHelper::GetNotificationSlotsForBundle(bundleOption, asynccallbackinfo->slots); - }, - [](napi_env env, napi_status status, void *data) { - ANS_LOGI("GetSlotsByBundle napi_create_async_work end"); - auto asynccallbackinfo = (AsyncCallbackInfoGetSlotsByBundle *)data; - - napi_value result = nullptr; - 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; - } + asynccallbackinfo->info.errorCode = NotificationHelper::GetNotificationSlotsForBundle( + asynccallbackinfo->params.option, asynccallbackinfo->slots); }, + AsyncCompleteCallbackGetSlotsByBundle, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index d35db62..8573dcb 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -13,8 +13,8 @@ * limitations under the License. */ -#include #include +#include #include "subscribe.h" namespace OHOS { @@ -957,12 +957,12 @@ 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; @@ -983,14 +983,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; } @@ -999,9 +999,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); diff --git a/interfaces/kits/napi/ans/src/unsubscribe.cpp b/interfaces/kits/napi/ans/src/unsubscribe.cpp index bd500e3..7ffc152 100644 --- a/interfaces/kits/napi/ans/src/unsubscribe.cpp +++ b/interfaces/kits/napi/ans/src/unsubscribe.cpp @@ -45,11 +45,11 @@ 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)) { + if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { ANS_LOGW("Subscriber not found"); } @@ -58,9 +58,9 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // 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); @@ -84,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, diff --git a/sa_profile/3203.xml b/sa_profile/3203.xml old mode 100755 new mode 100644 diff --git a/services/ans/test/unittest/mock/blob.cpp b/services/ans/test/unittest/mock/blob.cpp old mode 100755 new mode 100644 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/test/moduletest/mock/blob.cpp b/services/test/moduletest/mock/blob.cpp old mode 100755 new mode 100644 diff --git a/test/common/acts/actsnotificationfuzztest/BUILD.gn b/test/common/acts/actsnotificationfuzztest/BUILD.gn old mode 100755 new mode 100644 diff --git a/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap b/test/resource/ansSlotGroupHap/AnsSTSlotGroupTest.hap old mode 100755 new mode 100644 -- Gitee From c872cb4e41639d1fab80c86d220e0b2d05512adc Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Sat, 18 Dec 2021 11:53:58 +0000 Subject: [PATCH 052/131] Fix codex Signed-off-by: zhaoyuan17 --- .../ans/native/include/notification_user_input.h | 12 ++++++++---- interfaces/kits/napi/ans/src/remove.cpp | 2 +- 2 files changed, 9 insertions(+), 5 deletions(-) diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index 74420e9..e432cd2 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -81,7 +81,8 @@ public: public: /** * A static function used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the AAFwk::WantParams 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. */ @@ -89,7 +90,8 @@ public: /** * A static function used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the AAFwk::WantParams 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, @@ -231,13 +233,15 @@ private: /** * A constructor used to create a NotificationUserInput instance with the input parameters passed. - * @param inputKey Indicates the AAFwk::WantParams 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 AAFwk::WantParams 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, diff --git a/interfaces/kits/napi/ans/src/remove.cpp b/interfaces/kits/napi/ans/src/remove.cpp index be24eca..0757bbe 100644 --- a/interfaces/kits/napi/ans/src/remove.cpp +++ b/interfaces/kits/napi/ans/src/remove.cpp @@ -379,7 +379,7 @@ napi_value RemoveGroupByBundle(napi_env env, napi_callback_info info) asynccallbackinfo->params.option.GetUid(), asynccallbackinfo->params.groupName.c_str()); asynccallbackinfo->info.errorCode = NotificationHelper::RemoveGroupByBundle( - asynccallbackinfo->params.option, asynccallbackinfo->params.groupName); + asynccallbackinfo->params.option, asynccallbackinfo->params.groupName); }, AsyncCompleteCallbackRemoveGroupByBundle, (void *)asynccallbackinfo, -- Gitee From f7a48708043142f0d2f44bb4cca95cd75b8eb0e5 Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 20 Dec 2021 15:44:55 +0000 Subject: [PATCH 053/131] Modify the code format Signed-off-by: zhaoyuan17 --- frameworks/ans/core/src/ans_subscriber_stub.cpp | 1 - .../test/moduletest/mock/mock_bundle_manager.cpp | 1 - .../ans/test/moduletest/mock/mock_event_handler.cpp | 1 - .../innerkits/wantagent/include/cancel_listener.h | 2 +- .../wantagent/include/completed_callback.h | 4 ++-- .../innerkits/wantagent/include/trigger_info.h | 4 ++-- interfaces/innerkits/wantagent/include/want_agent.h | 13 ++++++------- .../innerkits/wantagent/include/want_agent_info.h | 2 +- interfaces/kits/napi/ans/BUILD.gn | 2 ++ interfaces/kits/napi/ans/include/unsubscribe.h | 1 - .../ans/src/notification_preferences_database.cpp | 1 - .../unittest/mock/mock_bundle_manager_helper.cpp | 1 + .../ans/test/unittest/mock/mock_single_kv_store.cpp | 1 - .../test/moduletest/mock/mock_bundle_manager.cpp | 1 - .../moduletest/mock/mock_bundle_manager_helper.cpp | 1 - .../test/moduletest/mock/mock_event_handler.cpp | 1 - .../test/moduletest/mock/mock_single_kv_store.cpp | 1 - tools/dump/src/main.cpp | 1 - 18 files changed, 15 insertions(+), 24 deletions(-) diff --git a/frameworks/ans/core/src/ans_subscriber_stub.cpp b/frameworks/ans/core/src/ans_subscriber_stub.cpp index b2432c4..932238a 100644 --- a/frameworks/ans/core/src/ans_subscriber_stub.cpp +++ b/frameworks/ans/core/src/ans_subscriber_stub.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ - #include "ans_subscriber_stub.h" #include "ans_const_define.h" diff --git a/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_manager.cpp index 98fd912..4ee0032 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_event_handler.cpp b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp index bbbeb49..bdadec5 100644 --- a/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_event_handler.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace AppExecFwk { - std::shared_ptr EventHandler::Current() { const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); diff --git a/interfaces/innerkits/wantagent/include/cancel_listener.h b/interfaces/innerkits/wantagent/include/cancel_listener.h index 10cea7b..cb3a244 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 5b83a2d..5657c86 100644 --- a/interfaces/innerkits/wantagent/include/completed_callback.h +++ b/interfaces/innerkits/wantagent/include/completed_callback.h @@ -23,6 +23,8 @@ namespace OHOS::Notification::WantAgent { class CompletedCallback { +public: + virtual ~CompletedCallback() = default; /** * Called when a Send operation as completed. * @@ -31,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/trigger_info.h b/interfaces/innerkits/wantagent/include/trigger_info.h index ba4cdba..a41ba98 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,11 +100,11 @@ public: */ public: class Builder final : public std::enable_shared_from_this { + public: /** * Default constructor used to create a {@code Builder} instance. * */ - public: Builder(); virtual ~Builder() = default; diff --git a/interfaces/innerkits/wantagent/include/want_agent.h b/interfaces/innerkits/wantagent/include/want_agent.h index f9a1908..3af5ac8 100644 --- a/interfaces/innerkits/wantagent/include/want_agent.h +++ b/interfaces/innerkits/wantagent/include/want_agent.h @@ -28,6 +28,11 @@ class WantAgent final : public std::enable_shared_from_this, public P public: WantAgent() {}; virtual ~WantAgent() = default; + /** + * Constructor. + * + * @param obj The proxy object. + */ explicit WantAgent(const std::shared_ptr &pendingWant); /** @@ -40,7 +45,7 @@ public: /** * Sets proxy obj. * - * @return Return obj. + * @param obj The proxy object. */ void SetPendingWant(const std::shared_ptr &pendingWant); @@ -62,12 +67,6 @@ public: private: std::shared_ptr pendingWant_; - - /** - * Constructor. - * - * @param obj The proxy object. - */ }; } // 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_info.h b/interfaces/innerkits/wantagent/include/want_agent_info.h index c363784..70315d1 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_info.h +++ b/interfaces/innerkits/wantagent/include/want_agent_info.h @@ -32,11 +32,11 @@ namespace OHOS::Notification::WantAgent { * */ class WantAgentInfo final : public std::enable_shared_from_this { +public: /** * Default constructor used to create an empty WantAgentInfo instance. * */ -public: WantAgentInfo(); virtual ~WantAgentInfo() = default; diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 2d7176e..66da342 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -61,6 +61,8 @@ 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", diff --git a/interfaces/kits/napi/ans/include/unsubscribe.h b/interfaces/kits/napi/ans/include/unsubscribe.h index 2751b46..670b257 100644 --- a/interfaces/kits/napi/ans/include/unsubscribe.h +++ b/interfaces/kits/napi/ans/include/unsubscribe.h @@ -22,7 +22,6 @@ 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/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 54c5a1e..809f7f7 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -14,7 +14,6 @@ */ #include "notification_preferences_database.h" - #include "ans_log_wrapper.h" #include "uri.h" diff --git a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp index 0d45485..f124d50 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -45,6 +45,7 @@ bool BundleManagerHelper::IsSystemApp(int uid) { return (uid == SYSTEM_APP_UID); } + void BundleManagerHelper::Connect() {} 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 bc79b19..e246e8d 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; diff --git a/services/test/moduletest/mock/mock_bundle_manager.cpp b/services/test/moduletest/mock/mock_bundle_manager.cpp index 98d2bca..cdb047e 100644 --- a/services/test/moduletest/mock/mock_bundle_manager.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager.cpp @@ -19,7 +19,6 @@ namespace OHOS { namespace AppExecFwk { - constexpr int SYSTEMAPP_UUID = 1000; void MockBundleMgrService::MockSetIsSystemApp(bool isSystemApp) diff --git a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp index 5fef8d2..70406de 100644 --- a/services/test/moduletest/mock/mock_bundle_manager_helper.cpp +++ b/services/test/moduletest/mock/mock_bundle_manager_helper.cpp @@ -45,6 +45,5 @@ void BundleManagerHelper::Connect() void BundleManagerHelper::Disconnect() {} - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/test/moduletest/mock/mock_event_handler.cpp b/services/test/moduletest/mock/mock_event_handler.cpp index bbbeb49..bdadec5 100644 --- a/services/test/moduletest/mock/mock_event_handler.cpp +++ b/services/test/moduletest/mock/mock_event_handler.cpp @@ -18,7 +18,6 @@ namespace OHOS { namespace AppExecFwk { - std::shared_ptr EventHandler::Current() { const std::weak_ptr &wp = std::make_shared(EventRunner::Create(true)); diff --git a/services/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index bc79b19..e246e8d 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/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; diff --git a/tools/dump/src/main.cpp b/tools/dump/src/main.cpp index b9557ac..b5ea105 100644 --- a/tools/dump/src/main.cpp +++ b/tools/dump/src/main.cpp @@ -13,7 +13,6 @@ * limitations under the License. */ - #include "notification_shell_command.h" int main(int argc, char *argv[]) -- Gitee From de7e3ab75057b5df31bf413e600fbf42b617070d Mon Sep 17 00:00:00 2001 From: zhaoyuan17 Date: Mon, 20 Dec 2021 16:40:07 +0000 Subject: [PATCH 054/131] Update session notification related d.ts Signed-off-by: zhaoyuan17 --- .../notificationActionButton.d.ts | 2 +- .../js/notification/notificationContent.d.ts | 73 ++++++++++++++++++- .../notification/notificationMessageUser.d.ts | 57 +++++++++++++++ .../js/notification/notificationRequest.d.ts | 2 +- .../notification/notificationUserInput.d.ts | 29 +++++++- 5 files changed, 158 insertions(+), 5 deletions(-) create mode 100644 interfaces/kits/js/notification/notificationMessageUser.d.ts diff --git a/interfaces/kits/js/notification/notificationActionButton.d.ts b/interfaces/kits/js/notification/notificationActionButton.d.ts index bf2549c..b2967c4 100644 --- a/interfaces/kits/js/notification/notificationActionButton.d.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, diff --git a/interfaces/kits/js/notification/notificationContent.d.ts b/interfaces/kits/js/notification/notificationContent.d.ts index d2cc36e..037300c 100644 --- a/interfaces/kits/js/notification/notificationContent.d.ts +++ b/interfaces/kits/js/notification/notificationContent.d.ts @@ -14,7 +14,9 @@ */ import notification from '../@ohos.notification'; -import image from './@ohos.multimedia.image'; +import image from '../@ohos.multimedia.image'; +import { MessageUser } from './notificationMessageUser'; + /** * Describes a normal text notification. * @@ -119,6 +121,68 @@ export interface NotificationPictureContent extends NotificationBasicContent { picture: image.PixelMap; } +/** + * 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. * @@ -153,4 +217,11 @@ export interface NotificationContent { * 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/notificationMessageUser.d.ts b/interfaces/kits/js/notification/notificationMessageUser.d.ts new file mode 100644 index 0000000..40d01bd --- /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 ce18332..6cefef3 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, diff --git a/interfaces/kits/js/notification/notificationUserInput.d.ts b/interfaces/kits/js/notification/notificationUserInput.d.ts index 1b44e87..389d1c4 100644 --- a/interfaces/kits/js/notification/notificationUserInput.d.ts +++ b/interfaces/kits/js/notification/notificationUserInput.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, @@ -17,7 +17,7 @@ * Describes a NotificationUserInput instance. * * @name NotificationUserInput - * @since 7 + * @since 8 * @devices phone, tablet, tv, wearable, car * @permission N/A * @sysCap SystemCapability.Notification.ANS @@ -27,4 +27,29 @@ 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}; } -- Gitee From 61f27e24023a15447fba71820f695cf434e9dc21 Mon Sep 17 00:00:00 2001 From: wangtiantian Date: Tue, 21 Dec 2021 04:51:02 +0000 Subject: [PATCH 055/131] IssueNo:https://gitee.com/openharmony/appexecfwk_standard/issues/I4N11L Description:fix compile problem Sig:appexecfwk Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: wangtiantian --- .../notificationfuzztest/src/notificationfuzztestmanager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp index b2c7ef2..4b5f41d 100644 --- a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp +++ b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp @@ -616,12 +616,12 @@ void NotificationFuzzTestManager::RegisterLauncherService() temp->IsAbilityEnabled(abilityInfo); }); - callFunctionMap_.emplace("LauncherServiceGetShortcutInfos", []() { + /*callFunctionMap_.emplace("LauncherServiceGetShortcutInfos", []() { std::shared_ptr temp = GetParamLauncherService(); const std::string bundleName = GetStringParam(); std::vector launcherShortcutInfo = GetParamLauncherShortcutInfoVector(); temp->GetShortcutInfos(bundleName, launcherShortcutInfo); - }); + });*/ callFunctionMap_.emplace("LauncherServiceRegisterCallback", []() { std::shared_ptr temp = GetParamLauncherService(); -- Gitee From b44cfdf4cee3504c4eff6bf2bf193a8d672bfbe3 Mon Sep 17 00:00:00 2001 From: liuwenhui_ddmp Date: Tue, 21 Dec 2021 22:38:49 +0800 Subject: [PATCH 056/131] TicketNo:AR000GH096 Description:add sync with subscribe Team:OTHERS Feature or Bugfix:Feature Binary Source:No PrivateCode(Yes/No):No Signed-off-by: liuwenhui_ddmp --- .../mock/include/mock_single_kv_store.h | 9 ++++++++- .../moduletest/mock/mock_single_kv_store.cpp | 20 +++++++++++++++++-- .../mock/include/mock_single_kv_store.h | 9 ++++++++- .../unittest/mock/mock_single_kv_store.cpp | 20 +++++++++++++++++-- .../mock/include/mock_single_kv_store.h | 9 ++++++++- .../moduletest/mock/mock_single_kv_store.cpp | 20 +++++++++++++++++-- 6 files changed, 78 insertions(+), 9 deletions(-) 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 0e2a140..0194762 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 @@ -52,7 +52,7 @@ public: 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; @@ -93,6 +93,13 @@ 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; 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 e246e8d..3f6d34b 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -66,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; } @@ -174,6 +174,22 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam 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 { @@ -190,4 +206,4 @@ 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/mock/include/mock_single_kv_store.h b/services/ans/test/unittest/mock/include/mock_single_kv_store.h index 811ef90..18a1399 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 @@ -54,7 +54,7 @@ public: 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,6 +95,13 @@ 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; 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 e246e8d..3f6d34b 100644 --- a/services/ans/test/unittest/mock/mock_single_kv_store.cpp +++ b/services/ans/test/unittest/mock/mock_single_kv_store.cpp @@ -66,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; } @@ -174,6 +174,22 @@ Status AnsTestSingleKvStore::Control(KvControlCmd cmd, const KvParam &inputParam 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 { @@ -190,4 +206,4 @@ Status AnsTestSingleKvStore::Clear() return Status::NOT_SUPPORT; } } // namespace DistributedKv -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/test/moduletest/mock/include/mock_single_kv_store.h b/services/test/moduletest/mock/include/mock_single_kv_store.h index 811ef90..18a1399 100644 --- a/services/test/moduletest/mock/include/mock_single_kv_store.h +++ b/services/test/moduletest/mock/include/mock_single_kv_store.h @@ -54,7 +54,7 @@ public: 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,6 +95,13 @@ 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; diff --git a/services/test/moduletest/mock/mock_single_kv_store.cpp b/services/test/moduletest/mock/mock_single_kv_store.cpp index e246e8d..b5eab9e 100644 --- a/services/test/moduletest/mock/mock_single_kv_store.cpp +++ b/services/test/moduletest/mock/mock_single_kv_store.cpp @@ -66,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; } @@ -185,9 +185,25 @@ Status AnsTestSingleKvStore::ReleaseKvStoreSnapshot(std::shared_ptr &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::Clear() { return Status::NOT_SUPPORT; } } // namespace DistributedKv -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From 594a2ea17daf92ebe121837bb5308842175e19b8 Mon Sep 17 00:00:00 2001 From: wangtiantian Date: Wed, 22 Dec 2021 03:55:12 +0000 Subject: [PATCH 057/131] IssueNo:https://gitee.com/openharmony/appexecfwk_standard/issues/I4N11L Description:fix compile problem Sig:appexecfwk Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: wangtiantian --- .../src/notificationfuzztestmanager.cpp | 7 ------- 1 file changed, 7 deletions(-) diff --git a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp index 4b5f41d..45eba38 100644 --- a/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp +++ b/test/resource/notificationfuzztest/src/notificationfuzztestmanager.cpp @@ -616,13 +616,6 @@ void NotificationFuzzTestManager::RegisterLauncherService() temp->IsAbilityEnabled(abilityInfo); }); - /*callFunctionMap_.emplace("LauncherServiceGetShortcutInfos", []() { - std::shared_ptr temp = GetParamLauncherService(); - const std::string bundleName = GetStringParam(); - std::vector launcherShortcutInfo = GetParamLauncherShortcutInfoVector(); - temp->GetShortcutInfos(bundleName, launcherShortcutInfo); - });*/ - callFunctionMap_.emplace("LauncherServiceRegisterCallback", []() { std::shared_ptr temp = GetParamLauncherService(); const sptr callback = GetParamIBundleStatusCallback(); -- Gitee From 3c93dcbdba23fb7c6591b88436551981f35cf5d1 Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 23 Dec 2021 21:05:13 +0800 Subject: [PATCH 058/131] 0330 Signed-off-by: derek Change-Id: Icb0730f2549f1f6255de01c92b5d861f86f4432a --- frameworks/ans/core/BUILD.gn | 10 + .../ans/core/common/include/ans_log_wrapper.h | 16 + .../ans/core/include/ans_manager_interface.h | 9 + .../ans/core/include/ans_manager_proxy.h | 7 + .../ans/core/include/ans_manager_stub.h | 8 + .../ans/core/include/ans_notification.h | 30 + frameworks/ans/core/src/ans_manager_proxy.cpp | 146 ++++ frameworks/ans/core/src/ans_manager_stub.cpp | 118 ++++ frameworks/ans/core/src/ans_notification.cpp | 54 ++ frameworks/ans/native/src/reminder_helper.cpp | 90 +++ .../ans/native/src/reminder_request.cpp | 644 ++++++++++++++++++ .../ans/native/src/reminder_request_alarm.cpp | 270 ++++++++ .../ans/native/src/reminder_request_timer.cpp | 139 ++++ frameworks/ans/native/test/unittest/BUILD.gn | 80 +++ .../unittest/reminder_request_alarm_test.cpp | 209 ++++++ .../test/unittest/reminder_request_test.cpp | 293 ++++++++ .../unittest/reminder_request_timer_test.cpp | 83 +++ interfaces/BUILD.gn | 1 + .../ans/native/include/reminder_helper.h | 107 +++ .../ans/native/include/reminder_request.h | 441 ++++++++++++ .../native/include/reminder_request_alarm.h | 155 +++++ .../native/include/reminder_request_timer.h | 78 +++ interfaces/kits/js/@ohos.reminderAgent.d.ts | 295 ++++++++ .../kits/napi/ans/include/reminder/common.h | 91 +++ .../napi/ans/include/reminder/native_module.h | 39 ++ .../kits/napi/ans/include/reminder/publish.h | 60 ++ .../kits/napi/ans/src/reminder/BUILD.gn | 81 +++ .../kits/napi/ans/src/reminder/common.cpp | 358 ++++++++++ .../napi/ans/src/reminder/native_module.cpp | 102 +++ .../kits/napi/ans/src/reminder/publish.cpp | 555 +++++++++++++++ notification.gni | 2 + ohos.build | 1 + services/ans/BUILD.gn | 6 + .../include/advanced_notification_service.h | 7 + services/ans/include/reminder_data_manager.h | 329 +++++++++ services/ans/include/reminder_event_manager.h | 51 ++ services/ans/include/reminder_timer_info.h | 67 ++ .../ans/src/advanced_notification_service.cpp | 117 ++++ services/ans/src/reminder_data_manager.cpp | 606 ++++++++++++++++ services/ans/src/reminder_event_manager.cpp | 100 +++ services/ans/src/reminder_timer_info.cpp | 61 ++ services/ans/test/unittest/BUILD.gn | 9 + 42 files changed, 5925 insertions(+) create mode 100644 frameworks/ans/native/src/reminder_helper.cpp create mode 100644 frameworks/ans/native/src/reminder_request.cpp create mode 100644 frameworks/ans/native/src/reminder_request_alarm.cpp create mode 100644 frameworks/ans/native/src/reminder_request_timer.cpp create mode 100644 frameworks/ans/native/test/unittest/BUILD.gn create mode 100644 frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp create mode 100644 frameworks/ans/native/test/unittest/reminder_request_test.cpp create mode 100644 frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp create mode 100644 interfaces/innerkits/ans/native/include/reminder_helper.h create mode 100644 interfaces/innerkits/ans/native/include/reminder_request.h create mode 100644 interfaces/innerkits/ans/native/include/reminder_request_alarm.h create mode 100644 interfaces/innerkits/ans/native/include/reminder_request_timer.h create mode 100644 interfaces/kits/js/@ohos.reminderAgent.d.ts create mode 100644 interfaces/kits/napi/ans/include/reminder/common.h create mode 100644 interfaces/kits/napi/ans/include/reminder/native_module.h create mode 100644 interfaces/kits/napi/ans/include/reminder/publish.h create mode 100644 interfaces/kits/napi/ans/src/reminder/BUILD.gn create mode 100644 interfaces/kits/napi/ans/src/reminder/common.cpp create mode 100644 interfaces/kits/napi/ans/src/reminder/native_module.cpp create mode 100644 interfaces/kits/napi/ans/src/reminder/publish.cpp create mode 100644 services/ans/include/reminder_data_manager.h create mode 100644 services/ans/include/reminder_event_manager.h create mode 100644 services/ans/include/reminder_timer_info.h create mode 100644 services/ans/src/reminder_data_manager.cpp create mode 100644 services/ans/src/reminder_event_manager.cpp create mode 100644 services/ans/src/reminder_timer_info.cpp diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index e262036..4f03215 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -31,6 +31,8 @@ config("public_ans_core_config") { "//utils/native/base/include", "//third_party/jsoncpp/include", ] + + cflags_cc = [ "-fexceptions" ] } ohos_shared_library("ans_core") { @@ -66,6 +68,10 @@ ohos_shared_library("ans_core") { "${frameworks_path}/ans/native/src/notification_subscribe_info.cpp", "${frameworks_path}/ans/native/src/notification_subscriber.cpp", "${frameworks_path}/ans/native/src/notification_user_input.cpp", + "${frameworks_path}/ans/native/src/reminder_helper.cpp", + "${frameworks_path}/ans/native/src/reminder_request.cpp", + "${frameworks_path}/ans/native/src/reminder_request_timer.cpp", + "${frameworks_path}/ans/native/src/reminder_request_alarm.cpp", ] configs = [ ":private_config" ] @@ -74,8 +80,12 @@ ohos_shared_library("ans_core") { deps = [ "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/miscservices/time/services:time_service", "//foundation/aafwk/standard/interfaces/innerkits/want:want", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", + "//foundation/appexecfwk/standard/kits:appkit_native", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", diff --git a/frameworks/ans/core/common/include/ans_log_wrapper.h b/frameworks/ans/core/common/include/ans_log_wrapper.h index c9543f7..a95f38e 100644 --- a/frameworks/ans/core/common/include/ans_log_wrapper.h +++ b/frameworks/ans/core/common/include/ans_log_wrapper.h @@ -33,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_derek"}; class AnsLogWrapper { public: @@ -71,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 REMINDER_LOGD(fmt, ...) PRINT_REMINDER_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) +#define REMINDER_LOGI(fmt, ...) PRINT_REMINDER_LOG(INFO, Info, fmt, ##__VA_ARGS__) +#define REMINDER_LOGW(fmt, ...) PRINT_REMINDER_LOG(WARN, Warn, fmt, ##__VA_ARGS__) +#define REMINDER_LOGE(fmt, ...) PRINT_REMINDER_LOG(ERROR, Error, fmt, ##__VA_ARGS__) +#define REMINDER_LOGF(fmt, ...) PRINT_REMINDER_LOG(FATAL, Fatal, fmt, ##__VA_ARGS__) } // 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 be9a8b1..9657c2b 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -28,6 +28,7 @@ #include "notification_slot.h" #include "notification_slot_group.h" #include "notification_subscribe_info.h" +#include "reminder_request.h" namespace OHOS { namespace Notification { @@ -113,6 +114,10 @@ public: 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; protected: enum TransactId : uint32_t { @@ -172,6 +177,10 @@ protected: SHELL_DUMP, PUBLISH_CONTINUOUS_TASK_NOTIFICATION, CANCEL_CONTINUOUS_TASK_NOTIFICATION, + PUBLISH_REMINDER, + CANCEL_REMINDER, + CANCEL_ALL_REMINDERS, + GET_ALL_VALID_REMINDERS }; }; } // namespace Notification diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index 77cd702..d5bd993 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -102,6 +102,11 @@ public: 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; + private: ErrCode InnerTransact(uint32_t code, MessageOption &flags, MessageParcel &data, MessageParcel &reply); @@ -111,6 +116,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 7947df7..5366ed9 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -106,6 +106,10 @@ public: 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; private: static const std::map> @@ -167,6 +171,10 @@ private: ErrCode HandleDoesSupportDoNotDisturbMode(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); 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 e030626..0c4e152 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -639,6 +639,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. diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index cdde8d2..3bb6fd0 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -20,6 +20,8 @@ #include "message_option.h" #include "message_parcel.h" #include "parcel.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" namespace OHOS { namespace Notification { @@ -1941,6 +1943,150 @@ ErrCode AnsManagerProxy::CancelContinuousTaskNotification(const std::string &lab return result; } +ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) +{ + REMINDER_LOGI("PublishReminder"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + REMINDER_LOGE("[PublishReminder] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (reminder == nullptr) { + REMINDER_LOGW("[PublishReminder] fail: reminder is null ptr."); + return ERR_ANS_INVALID_PARAM; + } + if (!data.WriteUint8(static_cast(reminder->GetReminderType()))) { + REMINDER_LOGE("[PublishReminder] fail: write reminder type failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteParcelable(reminder)) { + REMINDER_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) { + REMINDER_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } else { + int32_t reminderId = -1; + if (!reply.ReadInt32(reminderId)) { + REMINDER_LOGE("[PublishReminder] fail: derek read reminder id failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + reminder->SetReminderId(reminderId); + REMINDER_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); + } + return result; +} + +ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) +{ + REMINDER_LOGI("[CancelReminder]"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + REMINDER_LOGE("[CancelReminder] fail: write interface token failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!data.WriteInt32(reminderId)) { + REMINDER_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) { + REMINDER_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::CancelAllReminders() +{ + REMINDER_LOGI("[CancelAllReminders]"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + REMINDER_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) { + REMINDER_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } + return result; +} + +ErrCode AnsManagerProxy::GetValidReminders(std::vector> &reminders) +{ + REMINDER_LOGI("[GetValidReminders]"); + MessageParcel data; + if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { + REMINDER_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) { + REMINDER_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); + return ERR_ANS_TRANSACT_FAILED; + } else { + uint8_t count = 0; + if (!reply.ReadUint8(count)) { + REMINDER_LOGE("[GetValidReminders] fail: read reminder count failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + REMINDER_LOGD("[GetValidReminders] count=%{public}u", count); + reminders.clear(); + result = ReadReminders(count, reply, reminders); + if (result != ERR_OK) { + REMINDER_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); + } else { + REMINDER_LOGD("[GetValidReminders], size=%{public}d", 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)) { + REMINDER_LOGE("Failed to read reminder type"); + return ERR_ANS_PARCELABLE_FAILED; + } + auto reminderType = static_cast(typeInfo); + sptr reminder; + if (ReminderRequest::ReminderType::ALARM == reminderType) { + REMINDER_LOGD("[GetValidReminders] alarm"); + reminder = reply.ReadParcelable(); + } else if (ReminderRequest::ReminderType::TIMER == reminderType) { + REMINDER_LOGD("[GetValidReminders] timer"); + reminder = reply.ReadParcelable(); + } else { + REMINDER_LOGW("[GetValidReminders] type=%{public}d", typeInfo); + return ERR_ANS_INVALID_PARAM; + } + if (!reminder) { + REMINDER_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(); diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 9d3549f..51a2b3c 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -20,6 +20,8 @@ #include "message_option.h" #include "message_parcel.h" #include "parcel.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" namespace OHOS { namespace Notification { @@ -195,6 +197,19 @@ const std::map(ReminderRequest::ReminderType::INVALID); + if (!data.ReadUint8(typeInfo)) { + REMINDER_LOGE("Failed to read reminder type"); + return ERR_ANS_PARCELABLE_FAILED; + } + ReminderRequest::ReminderType reminderType = static_cast(typeInfo); + sptr reminder; + if (ReminderRequest::ReminderType::ALARM == reminderType) { + REMINDER_LOGD("Publish alarm"); + reminder = data.ReadParcelable(); + } else if (ReminderRequest::ReminderType::TIMER == reminderType) { + REMINDER_LOGD("Publish timer"); + reminder = data.ReadParcelable(); + } else { + REMINDER_LOGE("Reminder type invalid"); + return ERR_ANS_INVALID_PARAM; + } + if (!reminder) { + REMINDER_LOGE("Reminder ReadParcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + + ErrCode result = PublishReminder(reminder); + + if (!reply.WriteInt32(reminder->GetReminderId())) { + REMINDER_LOGE("Write back reminderId failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + return result; +} + +ErrCode AnsManagerStub::HandleCancelReminder(MessageParcel &data, MessageParcel &reply) +{ + REMINDER_LOGI("HandleCancelReminder"); + int32_t reminderId = -1; + if (!data.ReadInt32(reminderId)) { + REMINDER_LOGE("Read reminder id failed."); + return ERR_ANS_PARCELABLE_FAILED; + } + + REMINDER_LOGD("ReminderId=%{public}d", reminderId); + return CancelReminder(reminderId); +} + +ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessageParcel &reply) +{ + return CancelAllReminders(); +} + +ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParcel &reply) +{ + REMINDER_LOGI("HandleGetValidReminders"); + std::vector> validReminders; + ErrCode result = GetValidReminders(validReminders); + + REMINDER_LOGD("Write back size=%{public}d", validReminders.size()); + if (!reply.WriteUint8(static_cast(validReminders.size()))) { + REMINDER_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()); + REMINDER_LOGD("ReminderType=%{public}d", reminderType); + if (!reply.WriteUint8(reminderType)) { + REMINDER_LOGW("Write reminder type failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + if (!reply.WriteParcelable(reminder)) { + REMINDER_LOGW("Write reminder parcelable failed"); + return ERR_ANS_PARCELABLE_FAILED; + } + } + return result; +} + template bool AnsManagerStub::WriteParcelableVector( const std::vector> &parcelableVector, MessageParcel &reply, ErrCode &result) @@ -1638,5 +1733,28 @@ ErrCode AnsManagerStub::CancelContinuousTaskNotification(const std::string &labe 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; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index f6d751e..b033358 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -18,6 +18,8 @@ #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "iservice_registry.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.h" #include "system_ability_definition.h" namespace OHOS { @@ -862,6 +864,58 @@ 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; + if (reminder.GetReminderType() == ReminderRequest::ReminderType::ALARM) { + REMINDER_LOGI("Publish alarm"); + ReminderRequestAlarm &alarm = (ReminderRequestAlarm &)reminder; + tarReminder = new (std::nothrow) ReminderRequestAlarm(alarm); + } else if (reminder.GetReminderType() == ReminderRequest::ReminderType::TIMER) { + REMINDER_LOGI("Publish timer"); + ReminderRequestTimer &timer = (ReminderRequestTimer &)reminder; + tarReminder = new (std::nothrow) ReminderRequestTimer(timer); + } else { + REMINDER_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_) { diff --git a/frameworks/ans/native/src/reminder_helper.cpp b/frameworks/ans/native/src/reminder_helper.cpp new file mode 100644 index 0000000..6ac8013 --- /dev/null +++ b/frameworks/ans/native/src/reminder_helper.cpp @@ -0,0 +1,90 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "ans_notification.h" +#include "application_env_impl.h" +#include "iservice_registry.h" +#include "notification_helper.h" +#include "reminder_helper.h" +#include "system_ability_definition.h" +#include "singleton.h" + +namespace OHOS { +namespace Notification { +ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) +{ + REMINDER_LOGI("PublishReminder start"); + + // wait bundle manager to implement permission check. + // if (!CheckPermission()) { + // return ERR_PERMISSION_DENIED; + // } + + NotificationSlot slot(reminder.GetSlotType()); + NotificationHelper::AddNotificationSlot(slot); + return DelayedSingleton::GetInstance()->PublishReminder(reminder); +} + +ErrCode ReminderHelper::CancelReminder(const int32_t reminderId) +{ + REMINDER_LOGI("CancelReminder start"); + return DelayedSingleton::GetInstance()->CancelReminder(reminderId); +} + +ErrCode ReminderHelper::CancelAllReminders() +{ + REMINDER_LOGI("CancelAllReminders start"); + return DelayedSingleton::GetInstance()->CancelAllReminders(); +} + +bool ReminderHelper::CheckPermission() +{ + REMINDER_LOGI("CheckPermission"); + AppExecFwk::ApplicationEnvImpl* application = AppExecFwk::ApplicationEnvImpl::GetInstance(); + std::string pkgName = application->GetBundleName(); + sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (systemManager == nullptr) { + REMINDER_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) { + REMINDER_LOGE("Permission denied"); + return false; + } + return true; +} + +ErrCode ReminderHelper::GetValidReminders(std::vector> &validReminders) +{ + REMINDER_LOGI("GetValidReminders start"); + return DelayedSingleton::GetInstance()->GetValidReminders(validReminders); +} + +ErrCode AddNotificationSlot(const NotificationSlot &slot) +{ + REMINDER_LOGI("AddNotificationSlot start"); + return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); +} + +ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) +{ + REMINDER_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 0000000..3f74ce2 --- /dev/null +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -0,0 +1,644 @@ +/* + * 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.h" +#include "want_agent_helper.h" + +namespace OHOS { +namespace Notification { +int32_t ReminderRequest::GLOBAL_ID = 0; +const uint64_t ReminderRequest::INVALID_LONG_VALUE = 0; +const uint16_t ReminderRequest::MILLI_SECONDS = 1000; +const uint16_t ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS = 1000; +const uint8_t ReminderRequest::REMINDER_STATUS_INACTIVE = 0; +const uint8_t ReminderRequest::REMINDER_STATUS_SHOWING = 4; +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"; + +ReminderRequest::ReminderRequest() +{ + wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; +} + +ReminderRequest::ReminderRequest(const ReminderRequest &other) +{ + this->actionButtonMap_ = other.actionButtonMap_; + this->content_ = other.content_; + this->expiredContent_ = other.expiredContent_; + this->notificationId_ = other.notificationId_; + this->reminderId_ = other.reminderId_; + this->reminderType_ = other.reminderType_; + this->slotType_ = other.slotType_; + this->title_ = other.title_; + this->triggerTimeInMilli_ = other.triggerTimeInMilli_; + this->wantAgentInfo_ = other.wantAgentInfo_; +} + +ReminderRequest::ReminderRequest(ReminderType reminderType) +{ + reminderType_ = reminderType; + wantAgentInfo_ = wantAgentInfo_ == nullptr ? std::make_shared() : wantAgentInfo_; +} + +bool ReminderRequest::CanRemove() +{ + if ((state_ & REMINDER_STATUS_SHOWING) == 0) { + return true; + } + return false; +} + +std::string ReminderRequest::Dump() const +{ + struct tm *timeInfo; + const time_t nextTriggerTime = static_cast(triggerTimeInMilli_ / 1000); + timeInfo = localtime(&nextTriggerTime); + uint8_t dateTimeLen = 80; + char dateTimeBuffer[dateTimeLen]; + strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); + // todo + return "Reminder[" + "id=" + std::to_string(reminderId_) + + ", type=" + std::to_string(static_cast(reminderType_)) + + ", state=" + GetState(state_) + + ", nextTriggerTime=" + dateTimeBuffer + + // ", isExpired=" + std::to_string(isExpired_) + + // ", title=" + title_ + + // ", content=" + content_ + + // ", expiredContent=" + expiredContent_ + + // ", notificationId=" + std::to_string(notificationId_) + + // ", slotType=" + std::to_string(slotType_) + + // ", wantAgent=" + wantAgentInfo_->pkgName + "#" + wantAgentInfo_->abilityName + + "]"; +} + +ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type) +{ + if (type != ActionButtonType::CLOSE) { + REMINDER_LOGI("Button type only support: %{public}d", static_cast(ActionButtonType::CLOSE)); + 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) { + REMINDER_LOGW("GLOBAL_ID overdule"); + GLOBAL_ID = 0; + } + reminderId_ = ++GLOBAL_ID; + REMINDER_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) { + REMINDER_LOGE("onClose, the state of reminder is incorrect, state:%{public}s", GetState(state_).c_str()); + return; + } + SetState(false, REMINDER_STATUS_SHOWING, "onClose()"); + if (updateNext) { + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(false); + if (nextTriggerTime == INVALID_LONG_VALUE) { + isExpired_ = true; + } else { + SetTriggerTimeInMilli(nextTriggerTime); + } + } +} + +bool ReminderRequest::OnDateTimeChange() +{ + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(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_VALUE && optTriggerTime <= oriTriggerTime) { + // case1. switch to a previous time + SetTriggerTimeInMilli(optTriggerTime); + } else { + time_t now; + time(&now); // unit is seconds. + if (static_cast(now) < 0) { + REMINDER_LOGE("Get now time error"); + return false; + } + if (oriTriggerTime <= (static_cast(now) * MILLI_SECONDS)) { + // 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. + 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; + } + REMINDER_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", + oldZoneTriggerTime, newZoneTriggerTime); + bool showImmediately = false; + if (optTriggerTime != INVALID_LONG_VALUE && oldZoneTriggerTime < newZoneTriggerTime) { + // case1. timezone change to smaller + SetTriggerTimeInMilli(optTriggerTime); + } else { + time_t now; + time(&now); // unit is seconds. + if (static_cast(now) < 0) { + REMINDER_LOGE("Get now time error"); + return false; + } + if (newZoneTriggerTime <= (static_cast(now))) { + // case2. timezone change to larger + showImmediately = true; + } else { + SetTriggerTimeInMilli(newZoneTriggerTime); + showImmediately = false; + } + } + return showImmediately; +} + +void ReminderRequest::OnSameNotificationIdCovered() +{ + SetState(false, REMINDER_STATUS_SHOWING, "OnSameNotificationIdCovered"); +} + +void ReminderRequest::OnShow(bool isSysTimeChanged, bool allowToNotify) +{ + // todo isSysTimeChanged + if (allowToNotify) { + SetState(true, REMINDER_STATUS_SHOWING, "OnShow"); + } + UpdateNextReminder(); +} + +bool ReminderRequest::OnTimeZoneChange() +{ + time_t oldZoneTriggerTime = static_cast(triggerTimeInMilli_ / MILLI_SECONDS); + struct tm *oriTime; + oriTime = gmtime(&oldZoneTriggerTime); + time_t newZoneTriggerTime = mktime(oriTime); + uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(false); + return HandleTimeZoneChange(oldZoneTriggerTime, newZoneTriggerTime, nextTriggerTime); +} + +ReminderRequest& ReminderRequest::SetNotificationId(int32_t notificationId) +{ + notificationId_ = notificationId; + return *this; +} + +ReminderRequest& ReminderRequest::SetSlotType(const NotificationConstant::SlotType &slotType) +{ + slotType_ = slotType; + 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; +} + +std::map ReminderRequest::GetActionButtons() const +{ + return actionButtonMap_; +} + +std::string ReminderRequest::GetContent() const +{ + return content_; +} + +std::string ReminderRequest::GetExpiredContent() const +{ + return expiredContent_; +} + +int32_t ReminderRequest::GetNotificationId() const +{ + return notificationId_; +} + +sptr ReminderRequest::GetNotificationRequest() const +{ + return notificationRequest_; +} + +int32_t ReminderRequest::GetReminderId() const +{ + return reminderId_; +} + +void ReminderRequest::SetReminderId(int32_t reminderId) +{ + reminderId_ = reminderId; +} + +NotificationConstant::SlotType ReminderRequest::GetSlotType() const +{ + return slotType_; +} + +uint8_t ReminderRequest::GetState() const +{ + return state_; +} + +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_; +} + +bool ReminderRequest::UpdateNextReminder() +{ + return false; +} + +void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra) +{ + REMINDER_LOGI("UpdateNotification type=%{public}d", static_cast(type)); + switch(type) { + case UpdateNotificationType::ACTION_BUTTON: { + AddActionButtons(); + break; + } + case UpdateNotificationType::REMOVAL_WANT_AGENT: { + AddRemovalWantAgent(); + break; + } + case UpdateNotificationType::CONTENT: { + break; + } + default: + break; + } +} + +bool ReminderRequest::Marshalling(Parcel &parcel) const +{ + // write string + if (!parcel.WriteString(content_)) { + REMINDER_LOGE("Failed to write content"); + return false; + } + if (!parcel.WriteString(expiredContent_)) { + REMINDER_LOGE("Failed to write expiredContent"); + return false; + } + if (!parcel.WriteString(title_)) { + REMINDER_LOGE("Failed to write title"); + return false; + } + if (!parcel.WriteString(wantAgentInfo_->abilityName)) { + REMINDER_LOGE("Failed to write wantAgentInfo`s abilityName"); + return false; + } + if (!parcel.WriteString(wantAgentInfo_->pkgName)) { + REMINDER_LOGE("Failed to write wantAgentInfo`s pkgName"); + return false; + } + + // write int + if (!parcel.WriteInt32(reminderId_)) { + REMINDER_LOGE("Failed to write reminderId"); + return false; + } + if (!parcel.WriteInt32(notificationId_)) { + REMINDER_LOGE("Failed to write notificationId"); + return false; + } + if (!parcel.WriteUint64(triggerTimeInMilli_)) { + REMINDER_LOGE("Failed to write triggerTimeInMilli"); + return false; + } + + // write enum + if (!parcel.WriteUint8(static_cast(reminderType_))) { + REMINDER_LOGE("Failed to write reminder type"); + return false; + } + if (!parcel.WriteInt32(static_cast(slotType_))) { + REMINDER_LOGE("Failed to write slot type"); + return false; + } + + // write map + int32_t buttonMapSize = static_cast(actionButtonMap_.size()); + if (!parcel.WriteInt32(buttonMapSize)) { + REMINDER_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))) { + REMINDER_LOGE("Failed to write action button type"); + return false; + } + if (!parcel.WriteString(static_cast(it->second.title))) { + REMINDER_LOGE("Failed to write action button title"); + return false; + } + } + return true; +} + +ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) +{ + auto objptr = new ReminderRequest(); + if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + + return objptr; +} + +bool ReminderRequest::ReadFromParcel(Parcel &parcel) +{ + // read string + if (!parcel.ReadString(content_)) { + REMINDER_LOGE("Failed to read content"); + return false; + } + if (!parcel.ReadString(expiredContent_)) { + REMINDER_LOGE("to read expiredContent"); + return false; + } + if (!parcel.ReadString(title_)) { + REMINDER_LOGE("Failed to read title"); + return false; + } + if (!parcel.ReadString(wantAgentInfo_->abilityName)) { + REMINDER_LOGE("Failed to read wantAgentInfo`s abilityName"); + return false; + } + if (!parcel.ReadString(wantAgentInfo_->pkgName)) { + REMINDER_LOGE("Failed to read wantAgentInfo`s pkgName"); + return false; + } + + // read int + int32_t tempReminderId = -1; + if (!parcel.ReadInt32(tempReminderId)) { + REMINDER_LOGE("Failed to read tempReminderId"); + return false; + } + reminderId_ = tempReminderId == -1 ? reminderId_ : tempReminderId; + + if (!parcel.ReadInt32(notificationId_)) { + REMINDER_LOGE("Failed to read notificationId"); + return false; + } + if (!parcel.ReadUint64(triggerTimeInMilli_)) { + REMINDER_LOGE("Failed to read triggerTimeInMilli"); + return false; + } + + // read enum + uint8_t reminderType = static_cast(ReminderType::INVALID); + if (!parcel.ReadUint8(reminderType)) { + REMINDER_LOGE("Failed to read reminderType"); + return false; + } + reminderType_ = static_cast(reminderType); + + int32_t slotType = static_cast(NotificationConstant::SlotType::OTHER); + if (!parcel.ReadInt32(slotType)) { + REMINDER_LOGE("Failed to read slotType"); + return false; + } + slotType_ = static_cast(slotType); + + // read map + int32_t buttonMapSize = 0; + if (!parcel.ReadInt32(buttonMapSize)) { + REMINDER_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)) { + REMINDER_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() +{ + REMINDER_LOGI("Init notification"); + auto notificationNormalContent = std::make_shared(); + notificationNormalContent->SetText(content_); + notificationNormalContent->SetTitle(title_); + auto notificationContent = std::make_shared(notificationNormalContent); + notificationRequest_ = new NotificationRequest(notificationId_); + notificationRequest_->SetLabel(NOTIFICATION_LABEL); + notificationRequest_->SetSlotType(slotType_); + notificationRequest_->SetContent(notificationContent); + SetWantAgent(); // todo move to updateNotification +} + +std::string ReminderRequest::GetState(const uint8_t state) const +{ + std::string stateInfo = "Inactive"; + if (state == REMINDER_STATUS_INACTIVE) { + return stateInfo; + } else { + if ((state & REMINDER_STATUS_SHOWING) != 0) { + stateInfo = "Showing"; + } + } + return stateInfo; +} + +void ReminderRequest::AddActionButtons() +{ + 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); + REMINDER_LOGD("Add action button, type is close"); + } + 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() +{ + // todo add RemovalWantAgent + 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); + REMINDER_LOGD("~~1"); + WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, + flags, + wants, + nullptr + ); + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); + notificationRequest_->SetRemovalWantAgent(wantAgent); + REMINDER_LOGD("~~2"); +} + +void ReminderRequest::SetWantAgent() +{ + int requestCode = 10; + std::vector flags; + flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); + auto want = std::make_shared(); + AppExecFwk::ElementName element("", wantAgentInfo_->pkgName, wantAgentInfo_->abilityName); + want->SetElement(element); + std::vector> wants; + wants.push_back(want); + WantAgent::WantAgentInfo wantAgentInfo( + requestCode, + WantAgent::WantAgentConstant::OperationType::START_ABILITY, + flags, + wants, + nullptr + ); + std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); + 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; + } + REMINDER_LOGI("Switch the reminder(id=%{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()); +} +} +} \ No newline at end of file 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 0000000..1cfaf51 --- /dev/null +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -0,0 +1,270 @@ +/* + * 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 "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; + +ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) +: ReminderRequest(ReminderRequest::ReminderType::ALARM) +{ + 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_; + REMINDER_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); +} + +void ReminderRequestAlarm::CheckParamValid() const +{ + if (hour_ >= HOURS_PER_DAY || hour_ < 0) { + REMINDER_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) { + REMINDER_LOGE("setted minute is not between [0, 60)"); + throw std::invalid_argument("setted minute is not between [0, 60)"); + } +} + +void ReminderRequestAlarm::SetDaysOfWeek(bool set, std::vector daysOfWeek) +{ + if (daysOfWeek.size() == 0) { + return; + } + if (daysOfWeek.size() > DAYS_PER_WEEK) { + REMINDER_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 forceToGetNext) const +{ + return GetNextTriggerTime(false); +} + +uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const +{ + time_t now; + time(&now); // unit is seconds. + struct tm *nowTime; + nowTime = localtime(&now); + + 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; + REMINDER_LOGD("Now: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + "min=%{public}d, sec=%{public}d, week=%{public}d, tar_hour=%{public}d, tar_min=%{public}d", + nowTime->tm_year, nowTime->tm_mon, nowTime->tm_mday, nowTime->tm_hour, + nowTime->tm_min, nowTime->tm_sec, nowTime->tm_wday, hour_, minute_); + REMINDER_LOGD("Tar: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + "min=%{public}d, sec=%{public}d, week=%{public}d", + tar.tm_year, tar.tm_mon, tar.tm_mday, tar.tm_hour, tar.tm_min, tar.tm_sec, tar.tm_wday); + + 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; + test = localtime(&nextTriggerTime); + REMINDER_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", test->tm_year, + test->tm_mon, test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, test->tm_wday, 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; + } + } + REMINDER_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() +{ + if (repeatDays_ == 0) { + REMINDER_LOGD("Set reminder to expired"); + SetExpired(true); + return false; + } + uint64_t nextTriggerTime = GetNextTriggerTime(true); + if (nextTriggerTime != 0) { + REMINDER_LOGI("Set next trigger time=%{public}llu", nextTriggerTime); + SetTriggerTimeInMilli(nextTriggerTime); + return true; + } else { + REMINDER_LOGD("Set reminder to expired"); + SetExpired(true); + return false; + } +} + +bool ReminderRequestAlarm::Marshalling(Parcel &parcel) const +{ + ReminderRequest::Marshalling(parcel); + + // write int + if (!parcel.WriteUint8(hour_)) { + REMINDER_LOGE("Failed to write hour"); + return false; + } + if (!parcel.WriteUint8(minute_)) { + REMINDER_LOGE("Failed to write minute"); + return false; + } + if (!parcel.WriteUint8(repeatDays_)) { + REMINDER_LOGE("Failed to write daysOfWeek"); + return false; + } + + return true; +} + +ReminderRequestAlarm *ReminderRequestAlarm::Unmarshalling(Parcel &parcel) +{ + std::vector daysOfWeek; + REMINDER_LOGD("New alarm"); + auto objptr = new ReminderRequestAlarm(); + if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) +{ + ReminderRequest::ReadFromParcel(parcel); + + // read int + if (!parcel.ReadUint8(hour_)) { + REMINDER_LOGE("Failed to read hour"); + return false; + } + if (!parcel.ReadUint8(minute_)) { + REMINDER_LOGE("Failed to read minute"); + return false; + } + if (!parcel.ReadUint8(repeatDays_)) { + REMINDER_LOGE("Failed to read repeatDays"); + return false; + } + REMINDER_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_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp new file mode 100644 index 0000000..cb00579 --- /dev/null +++ b/frameworks/ans/native/src/reminder_request_timer.cpp @@ -0,0 +1,139 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include "ans_log_wrapper.h" +#include "reminder_request_timer.h" +#include "time_service_client.h" + +namespace OHOS { +namespace Notification { +ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) +: ReminderRequest(ReminderRequest::ReminderType::TIMER) +{ + CheckParamsValid(countDownTimeInSeconds); + countDownTimeInSeconds_ = countDownTimeInSeconds; + time_t now; // unit is seconds. + 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 forceToGetNext) const +{ + REMINDER_LOGD("countdonw time not support PreGetNextTriggerTimeIgnoreSnooze"); + return ReminderRequest::INVALID_LONG_VALUE; +} + +bool ReminderRequestTimer::OnDateTimeChange() +{ + UpdateTimeInfo("onDateTimeChange"); + return false; +} + +bool ReminderRequestTimer::OnTimeZoneChange() +{ + UpdateTimeInfo("onTimeZoneChange"); + return false; +} + +bool ReminderRequestTimer::UpdateNextReminder() +{ + REMINDER_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)) { + REMINDER_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; + } + REMINDER_LOGD("%{public}s, update countdown time trigger time", description.c_str()); + time_t now; + 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_)) { + REMINDER_LOGE("Failed to write firstRealTimeInMilliSeconds"); + return false; + } + if (!parcel.WriteUint64(countDownTimeInSeconds_)) { + REMINDER_LOGE("Failed to write countDownTimeInSeconds"); + return false; + } + return true; +} + +ReminderRequestTimer *ReminderRequestTimer::Unmarshalling(Parcel &parcel) +{ + auto objptr = new ReminderRequestTimer(); + if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + delete objptr; + objptr = nullptr; + } + return objptr; +} + +bool ReminderRequestTimer::ReadFromParcel(Parcel &parcel) +{ + ReminderRequest::ReadFromParcel(parcel); + + // read int + if (!parcel.ReadUint64(firstRealTimeInMilliSeconds_)) { + REMINDER_LOGE("Failed to read firstRealTimeInMilliSeconds"); + return false; + } + if (!parcel.ReadUint64(countDownTimeInSeconds_)) { + REMINDER_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 0000000..2b7d71c --- /dev/null +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -0,0 +1,80 @@ +# 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", + "//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", + ] + + sources = [ + "${native_path}/test/unittest/reminder_request_test.cpp", + "${native_path}/test/unittest/reminder_request_alarm_test.cpp", + ] + + configs = [ "//utils/native/base:utils_config" ] + + deps = [ + "${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", + ] + + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_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 0000000..fff49ef --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp @@ -0,0 +1,209 @@ +/* + * 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) { + REMINDER_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) { + REMINDER_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) { + REMINDER_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) { + REMINDER_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_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_test.cpp new file mode 100644 index 0000000..f85933a --- /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, 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, 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, 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(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, 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(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); + 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 0000000..0d37307 --- /dev/null +++ b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp @@ -0,0 +1,83 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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(){}; + 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 { + auto rrc = std::make_shared(0); + EXPECT_TRUE(false) << "countDownTime < 0 should throw exception."; + } catch (const std::invalid_argument &e) { + REMINDER_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) { + REMINDER_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) +{ + auto rrc = std::make_shared(1); + EXPECT_TRUE(rrc->GetInitInfo() == 1) << "countDownTime is not 1"; + + auto rrc2 = std::make_shared(10); + EXPECT_TRUE(rrc2->GetInitInfo() == 1) << "countDownTime is not 10"; + + auto rrc3 = std::make_shared(100); + EXPECT_TRUE(rrc3->GetInitInfo() == 1) << "countDownTime is not 1"; +} +} +} \ No newline at end of file diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn index 2c3010f..848eae1 100644 --- a/interfaces/BUILD.gn +++ b/interfaces/BUILD.gn @@ -15,5 +15,6 @@ group("interfaces_target") { deps = [ "kits/napi/ans:notification", "kits/napi/wantagent:wantagent", + "kits/napi/ans/src/reminder:reminderagent", ] } 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 0000000..3f4877e --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_helper.h @@ -0,0 +1,107 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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 0000000..529bdca --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -0,0 +1,441 @@ +/* + * 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 { + ACTION_BUTTON, + REMOVAL_WANT_AGENT, + CONTENT + }; + + /** + * @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 = ""; + }; + + /** + * @brief Copy construct from an exist reminder. + * + * @param Indicates the exist reminder. + */ + explicit ReminderRequest(const ReminderRequest &other); + ReminderRequest& operator = (const ReminderRequest &other); + virtual ~ReminderRequest() {}; + + /** + * @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(); + + /** + * @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; + + /** + * @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; + + /** + * @brief Obtains reminder type. + * + * @return reminder type. + */ + ReminderType GetReminderType() const; + + /** + * @brief Obtains slot type. + * + * @return slot type. + */ + NotificationConstant::SlotType GetSlotType() const; + + uint8_t GetState() 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 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 Close the reminder by manual. + * + * @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 Show the reminder on panel. TriggerTime will be updated to next. + * + * @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 isSysTimeChanged, bool allowToNotify); + + /** + * @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); + + /** + * @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); + + /** + * @brief Sets slot type. + * + * @param slotType Indicates slot type. + * @return Current reminder self. + */ + ReminderRequest& SetSlotType(const NotificationConstant::SlotType &slotType); + + /** + * @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); + + /** + * @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_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; + +protected: + ReminderRequest(); + explicit ReminderRequest(ReminderType reminderType); + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const { + return INVALID_LONG_VALUE; + }; + +private: + void AddActionButtons(); + void AddRemovalWantAgent(); + 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 SetState(bool deSet, const uint8_t newState, std::string function); + void SetWantAgent(); + + static const uint8_t REMINDER_STATUS_INACTIVE; + static const uint8_t REMINDER_STATUS_SHOWING; + + std::string content_ {}; + std::string expiredContent_ {}; + std::string title_ {}; + bool isExpired_ {false}; + uint8_t state_ {0}; + int32_t notificationId_ {0}; + int32_t reminderId_ {-1}; + uint64_t triggerTimeInMilli_ {0}; + ReminderType reminderType_ {ReminderType::INVALID}; + NotificationConstant::SlotType slotType_ {NotificationConstant::SlotType::SOCIAL_COMMUNICATION}; + sptr notificationRequest_ = nullptr; + std::shared_ptr wantAgentInfo_ = 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 0000000..686bb14 --- /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 +#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(){}; + + /** + * 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 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; + 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; + + 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_timer.h b/interfaces/innerkits/ans/native/include/reminder_request_timer.h new file mode 100644 index 0000000..1542d8b --- /dev/null +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -0,0 +1,78 @@ +/* + * 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(){}; + + 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 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/kits/js/@ohos.reminderAgent.d.ts b/interfaces/kits/js/@ohos.reminderAgent.d.ts new file mode 100644 index 0000000..96c26e2 --- /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/napi/ans/include/reminder/common.h b/interfaces/kits/napi/ans/include/reminder/common.h new file mode 100644 index 0000000..3de9524 --- /dev/null +++ b/interfaces/kits/napi/ans/include/reminder/common.h @@ -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. + */ +#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* REMINDER_TYPE = "reminderType"; +const char* ALARM_HOUR = "hour"; +const char* ALARM_MINUTE = "minute"; +const char* ALARM_DAYS_OF_WEEK = "daysOfWeek"; +const char* TIMER_COUNT_DOWN_TIME = "triggerTimeInSeconds"; +const char* ACTION_BUTTON = "actionButton"; +const char* ACTION_BUTTON_TITLE = "title"; +const char* ACTION_BUTTON_TYPE = "type"; +const char* WANT_AGENT = "wantAgent"; +const char* WANT_AGENT_PKG = "pkgName"; +const char* WANT_AGENT_ABILITY = "abilityName"; +const char* TITLE = "title"; +const char* CONTENT = "content"; +const char* EXPIRED_CONTENT = "expiredContent"; +const char* NOTIFICATION_ID = "notificationId"; +const char* SLOT_TYPE = "slotType"; +} + +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); + + 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 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 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 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); +}; +} // namespace OHOS +} // namespace ReminderAgentNapi + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_COMMON_H diff --git a/interfaces/kits/napi/ans/include/reminder/native_module.h b/interfaces/kits/napi/ans/include/reminder/native_module.h new file mode 100644 index 0000000..b720a91 --- /dev/null +++ b/interfaces/kits/napi/ans/include/reminder/native_module.h @@ -0,0 +1,39 @@ +/* + * 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_NATIVE_MODULE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_NATIVE_MODULE_H + +#include "napi/native_api.h" +#include "napi/native_node_api.h" + +namespace OHOS { +namespace ReminderAgentNapi { +#ifdef __cplusplus +extern "C" { +#endif + +__attribute__((constructor)) void RegisterModule(void); +napi_value ConstantInit(napi_env env, napi_value exports); +napi_value ReminderAgentInit(napi_env env, napi_value exports); + +static napi_value Init(napi_env env, napi_value exports); + +#ifdef __cplusplus +} +#endif +} // namespace OHOS +} // namespace ReminderAgentNapi + +#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 0000000..7252a45 --- /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/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/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn new file mode 100644 index 0000000..eaba4fa --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -0,0 +1,81 @@ +# 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/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/jsoncpp/include", + ] + + configs = [ ":native_module_config" ] + + sources = [ + "../common.cpp", + "../slot.cpp", + "native_module.cpp", + "common.cpp", + "publish.cpp", + ] + + 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_native", + "//third_party/jsoncpp:jsoncpp", + "//third_party/libuv:uv_static", + "//utils/native/base:utils", + ] + + external_deps = [ + "appexecfwk_standard:appexecfwk_base", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + ] + + relative_install_dir = "module" + subsystem_name = "notification" + part_name = "ans_standard" +} \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/reminder/common.cpp b/interfaces/kits/napi/ans/src/reminder/common.cpp new file mode 100644 index 0000000..af16820 --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/common.cpp @@ -0,0 +1,358 @@ +/* + * 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/common.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.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) { + REMINDER_LOGE("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)) { + bool isArray = false; + napi_is_array(env, actionButtons, &isArray); + if (!isArray) { + REMINDER_LOGE("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) { + REMINDER_LOGE("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)) { + if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE) { + REMINDER_LOGE("Wrong argument type:%{public}s. buttonType not support.", ACTION_BUTTON); + return false; + } + std::string title(str); + reminder->SetActionButton(title, static_cast(buttonType)); + REMINDER_LOGD("button title=%{public}s, type=%{public}d", title.c_str(), buttonType); + } + } + } + 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)) { + std::shared_ptr wantAgentInfo(new ReminderRequest::WantAgentInfo()); + 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); + } +} + +napi_value ReminderCommon::GenReminder( + const napi_env &env, const napi_value &value, std::shared_ptr& reminder) +{ + bool hasProperty = false; + + // reminderType + NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); + if (!hasProperty) { + REMINDER_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); + return nullptr; + } + napi_value result = nullptr; + napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); + int32_t propertyVal = 0; + napi_get_value_int32(env, result, &propertyVal); + + switch (ReminderRequest::ReminderType(propertyVal)) { + case ReminderRequest::ReminderType::TIMER: + CreateReminderTimer(env, value, reminder); + break; + case ReminderRequest::ReminderType::ALARM: + CreateReminderAlarm(env, value, reminder); + break; + default: + break; + } + + if (reminder == nullptr) { + REMINDER_LOGE("Instance of reminder error."); + 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); + } + + // notificationId + if (GetInt32(env, value, ReminderAgentNapi::NOTIFICATION_ID, propertyVal)) { + reminder->SetNotificationId(propertyVal); + } + + // slotType + int32_t slotType = 0; + if (GetInt32(env, value, ReminderAgentNapi::SLOT_TYPE, slotType)) { + enum NotificationConstant::SlotType actureType = NotificationConstant::SlotType::OTHER; + if (!NotificationNapi::Common::SlotTypeJSToC(NotificationNapi::SlotType(slotType), actureType)) { + return nullptr; + } + reminder->SetSlotType(actureType); + } + + // wantAgent + GenWantAgent(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) { + REMINDER_LOGE("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) +{ + napi_value result = nullptr; + if (!GetPropertyValIfExist(env, value, propertyName, result)) { + 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) { + REMINDER_LOGE("Wrong argument type. number expected."); + } else { + REMINDER_LOGE("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 true; + } + napi_get_named_property(env, value, propertyName, &propertyVal); + NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); + if (valuetype != napi_object) { + REMINDER_LOGE("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)) { + REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); + return nullptr; + } + + if (propertyCountDownTime <= 0 || + propertyCountDownTime > static_cast((UINT64_MAX / ReminderRequest::MILLI_SECONDS))) { + REMINDER_LOGE("Property %{public}s must between (0, %{public}llu).", + ReminderAgentNapi::ALARM_MINUTE, (UINT64_MAX / ReminderRequest::MILLI_SECONDS)); + 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)) { + REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_HOUR); + return nullptr; + } + + // minute + int32_t propertyMinuteVal = 0; + if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal)) { + REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_MINUTE); + return nullptr; + } + if (propertyHourVal < 0 || propertyHourVal > 23) { + REMINDER_LOGE("Property %{public}s must between [0, 23].", ReminderAgentNapi::ALARM_HOUR); + return nullptr; + } + if (propertyMinuteVal < 0 || propertyMinuteVal > 59) { + REMINDER_LOGE("Property %{public}s must between [0, 59].", ReminderAgentNapi::ALARM_MINUTE); + return nullptr; + } + + // daysOfWeek + napi_value result = nullptr; + if (!GetObject(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { + REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + return nullptr; + } + std::vector daysOfWeek; + if (result != nullptr) { // function line too long + bool isArray = false; + napi_is_array(env, result, &isArray); + if (!isArray) { + REMINDER_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + return nullptr; + } + uint32_t length = 0; + napi_get_array_length(env, result, &length); + uint8_t maxDaysOfWeek = 7; + if (length > maxDaysOfWeek) { + REMINDER_LOGE("The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + 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) { + REMINDER_LOGE("%{public}s's element is expected to be number.", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + return nullptr; + } + napi_get_value_int32(env, repeatDayVal, &propertyDayVal); + if (propertyDayVal < 1 || propertyDayVal > maxDaysOfWeek) { + REMINDER_LOGE("%{public}s's element must between [1, %{public}d].", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + return nullptr; + } + daysOfWeek.push_back(static_cast(propertyDayVal)); + } + } + reminder = std::make_shared( + static_cast(propertyHourVal), static_cast(propertyMinuteVal), daysOfWeek); + return NotificationNapi::Common::NapiGetNull(env); +} +} +} \ No newline at end of file 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 0000000..8b0223d --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/native_module.cpp @@ -0,0 +1,102 @@ +/* + * 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/native_module.h" +#include "reminder/publish.h" +#include "slot.h" + +namespace OHOS { +namespace ReminderAgentNapi { +EXTERN_C_START +napi_value ReminderAgentInit(napi_env env, napi_value exports) +{ + REMINDER_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) +{ + REMINDER_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); + } + + 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); + } + + 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 0000000..962c94f --- /dev/null +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -0,0 +1,555 @@ +/* + * 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/publish.h" +#include "reminder_request_alarm.h" +#include "reminder_request_timer.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) { + REMINDER_LOGE("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) { + REMINDER_LOGE("Wrong number of arguments"); + return nullptr; + } + + // argv[0] : reminderRequest + if (ReminderCommon::GetReminderRequest(env, argv[0], params.reminder) == nullptr) { + REMINDER_LOGE("[reminderAgent]CreateReminder returns nullptr"); + return nullptr; + } + + // argv[1]: callback + if (argc == PUBLISH_PARAM_LEN) { + if (GetCallback(env, argv[1], params) == nullptr) { + REMINDER_LOGE("[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) +{ + REMINDER_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) { + REMINDER_LOGE("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: reminder id + int32_t reminderId = -1; + if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId)) { + REMINDER_LOGE("Param id of cancels Reminder should be a number."); + return nullptr; + } + if (reminderId < 0) { + REMINDER_LOGE("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) { + REMINDER_LOGE("GetCallbak is nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) +{ + REMINDER_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) { + REMINDER_LOGE("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: callback + if (argc == CANCEL_ALL_PARAM_LEN) { + if (GetCallback(env, argv[0], params) == nullptr) { + REMINDER_LOGE("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) { + REMINDER_LOGE("Wrong number of arguments"); + return nullptr; + } + + // argv[0]: callback + if (argc == GET_VALID_PARAM_LEN) { + if (GetCallback(env, argv[0], params) == nullptr) { + REMINDER_LOGI("getCallbak is nullptr"); + return nullptr; + } + } + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value CancelReminder(napi_env env, napi_callback_info info) { + REMINDER_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) { + REMINDER_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) { + REMINDER_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); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + REMINDER_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) +{ + REMINDER_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) { + REMINDER_LOGI("CancelAll napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + asynccallbackinfo->info.errorCode = ReminderHelper::CancelAllReminders(); + }, + [](napi_env env, napi_status status, void *data) { + REMINDER_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); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + REMINDER_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 ParseReminder( + const napi_env &env, ReminderRequest::ReminderType &type, ReminderRequest &reminder, napi_value &result) +{ + napi_value value = nullptr; + switch (type) { + case ReminderRequest::ReminderType::TIMER: { + ReminderRequestTimer& timer = (ReminderRequestTimer&)reminder; + napi_create_uint32(env, timer.GetInitInfo(), &value); + napi_set_named_property(env, result, TIMER_COUNT_DOWN_TIME, value); + break; + } + case ReminderRequest::ReminderType::ALARM: { + REMINDER_LOGD("Parse alarm info"); + + // hour + ReminderRequestAlarm& alarm = (ReminderRequestAlarm&)reminder; + napi_create_uint32(env, static_cast(alarm.GetHour()), &value); + + // minute + napi_set_named_property(env, result, ALARM_HOUR, value); + 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++; + } + } + REMINDER_LOGD("Parse alarm info end"); + 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); +} + +napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi_value &result) +{ + REMINDER_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); + + // notificationId + napi_create_int32(env, reminder.GetNotificationId(), &value); + napi_set_named_property(env, result, NOTIFICATION_ID, value); + + // slotType + napi_create_int32(env, static_cast(reminder.GetSlotType()), &value); + napi_set_named_property(env, result, SLOT_TYPE, value); + + // wantAgent + ParseWantAgent(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) { + REMINDER_LOGE("reminder is null"); + continue; + } + napi_value result = nullptr; + napi_create_object(env, &result); + if (!SetValidReminder(env, *reminder, result)) { + REMINDER_LOGW("Set reminder object failed"); + continue; + } + napi_set_element(env, arr, count, result); + count++; + } + REMINDER_LOGI("GetValid reminders count = %{public}d", count); +} + +napi_value GetValidReminders(napi_env env, napi_callback_info info) +{ + REMINDER_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) { + REMINDER_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) { + REMINDER_LOGI("GetValid reminders 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); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + REMINDER_LOGI("GetValid reminders 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 PublishReminder(napi_env env, napi_callback_info info) +{ + REMINDER_LOGI("PublishReminder"); + + // param + Parameters params; + if (ParseParameters(env, info, params) == nullptr) { + REMINDER_LOGE("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) { + REMINDER_LOGI("Publish napi_create_async_work start"); + AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; + asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); + REMINDER_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + }, + [](napi_env env, napi_status status, void *data) { + REMINDER_LOGI("Publish 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); + if (asynccallbackinfo) { + delete asynccallbackinfo; + asynccallbackinfo = nullptr; + } + REMINDER_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/notification.gni b/notification.gni index 61aa51b..3039d02 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" diff --git a/ohos.build b/ohos.build index 747cde4..96a234c 100644 --- a/ohos.build +++ b/ohos.build @@ -14,6 +14,7 @@ "//base/notification/ans_standard/services/ans/test/unittest:ans_unit_test", "//base/notification/ans_standard/services/test/moduletest:ans_module_test", "//base/notification/ans_standard/frameworks/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" ] diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 1f8e18f..b45ae62 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -21,6 +21,7 @@ group("ans_targets") { config("public_ans_config") { include_dirs = [ "${services_path}/ans/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", @@ -45,6 +46,9 @@ ohos_shared_library("libans") { "src/notification_subscriber_manager.cpp", "src/permission_filter.cpp", "src/system_event_observer.cpp", + "src/reminder_timer_info.cpp", + "src/reminder_data_manager.cpp", + "src/reminder_event_manager.cpp", ] configs = [ @@ -58,8 +62,10 @@ ohos_shared_library("libans") { "${frameworks_path}/wantagent:wantagent_innerkits", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", + "//base/miscservices/time/services:time_service", ] if (is_double_framework) { diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 95214c0..55b751e 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -108,12 +108,19 @@ public: 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; // SystemEvent void OnBundleRemoved(const sptr &bundleOption); // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); + void SaveNotificationInfo(sptr &request, sptr &bundleOption); + ErrCode PublishSavedNotification( + sptr &request, sptr &bundleOption); private: struct RecentInfo; diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h new file mode 100644 index 0000000..07d5378 --- /dev/null +++ b/services/ans/include/reminder_data_manager.h @@ -0,0 +1,329 @@ +/* + * 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 "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); + + /** + * 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 ShowReminder(bool isSysTimeChanged); + + static const uint8_t TIME_ZONE_CHANGE; + static const uint8_t DATE_TIME_CHANGE; + +private: + /** + * Add default slot to the reminder if no slot set by user. + * + * @param reminder Indicates the reminder. + */ + void AddDefaultSlotIfNeeded(sptr &reminder); + + /** + * Cancels the notification relative to the reminder. + * + * @param reminder Indicates the reminder. + */ + void CancelNotification(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 int32_t &reminderId, bool cancelNotification); + + /** + * Create a information for timer, such as timer type, repeat policy, interval and want agent. + * + * @return pointer of ReminderTimerInfo. + */ + std::shared_ptr CreateTimerInfo() const; + + /** + * 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); + + /** + * 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); + + /** + * 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); + + /** + * @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_ with 0. + * 2. Sets activeReminderId_ with -1. + */ + void ResetStates(); + + void ShowDesignatedReminderLocked(sptr &reminder, bool isSysTimeChanged); + + /** + * Starts the recent reminder timing. + */ + void StartRecentReminder(); + + /** + * Starts timing actually. + * + * @param reminderRequest Indicates the reminder. + */ + void StartTimerLocked(sptr &reminderRequest); + + /** + * Stops timing. + */ + void StopTimer(); + + /** + * Stops timing. + */ + void StopTimerLocked(); + + /** + * @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); + + 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; + + /** + * 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; + + static const uint16_t SAME_TIME_DISTINGUISH_MILLISECONDS; + + /** + * Vector used to record all the reminders in system. + */ + std::vector> reminderVector_; + + /** + * Map used to record all the bundle information of the reminders in system. + */ + std::map> notificationBundleOptionMap_; + + /** + * Indicates the id of the timer that has called StartTimerLocked. + */ + uint64_t timerId_ {0}; + + /** + * Indicates the active reminder that timing is taking effect. + */ + int32_t activeReminderId_ {-1}; + + /** + * 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 0000000..83b88f9 --- /dev/null +++ b/services/ans/include/reminder_event_manager.h @@ -0,0 +1,51 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef 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: + std::shared_ptr reminderDataManager_; +}; +}; +} // 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 0000000..28179f8 --- /dev/null +++ b/services/ans/include/reminder_timer_info.h @@ -0,0 +1,67 @@ +/* + * 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 "itimer_info.h" +#include "notification_request.h" +#include "reminder_request.h" +#include "advanced_notification_service.h" + +namespace OHOS { +namespace Notification { +class ReminderTimerInfo : public MiscServices::ITimerInfo { +public: + ReminderTimerInfo(){}; + virtual ~ReminderTimerInfo(){}; + + ReminderTimerInfo(ReminderTimerInfo &other) = delete; + ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; + + /** + * 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; + + /** + * Publish common event. + */ + bool PublishCommonEvent(const std::string &action) const; +}; +} // namespace OHOS +} // namespace Notification + +#endif // BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index c0995fc..c0f1e93 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -32,6 +32,8 @@ #include "notification_subscriber_manager.h" #include "permission_filter.h" +#include "reminder_data_manager.h" + namespace OHOS { namespace Notification { namespace { @@ -227,6 +229,68 @@ sptr AdvancedNotificationService::GenerateValidBundleO return validBundleOption; } +void AdvancedNotificationService::SaveNotificationInfo( + sptr &request, sptr &bundleOption) +{ + ErrCode result = PrepereNotificationRequest(request); + if (result != ERR_OK) { + REMINDER_LOGE("SaveNotificationInfo fail"); + return; + } + bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + REMINDER_LOGE("SaveNotificationInfo fail."); + return; + } + REMINDER_LOGI( + "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid()); +} + +ErrCode AdvancedNotificationService::PublishSavedNotification( + sptr &request, sptr &bundleOption) +{ + REMINDER_LOGI("PublishSavedNotification"); + auto record = std::make_shared(); + record->request = request; + record->notification = new Notification(request); + record->bundleOption = bundleOption; + + ErrCode result = ERR_OK; + + handler_->PostSyncTask(std::bind([&]() { + 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())) { + 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); + } + + UpdateRecentNotification(record->notification, false, 0); + sptr sortingMap = GenerateSortingMap(); + NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); + })); + return result; +} + ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); @@ -1376,6 +1440,59 @@ ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std: return result; } +ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) +{ + REMINDER_LOGI("Publish reminder"); + ReminderDataManager::GetInstance()->SetService(this); + sptr notificationRequest = reminder->GetNotificationRequest(); + sptr bundleOption = nullptr; + SaveNotificationInfo(notificationRequest, bundleOption); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ReminderDataManager::GetInstance()->PublishReminder(reminder, bundleOption); + return ERR_OK; +} + +ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) +{ + REMINDER_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() +{ + REMINDER_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) +{ + REMINDER_LOGI("GetValidReminders"); + ReminderDataManager::GetInstance()->SetService(this); + reminders.clear(); + sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + ReminderDataManager::GetInstance()->GetValidReminders(bundleOption, reminders); + REMINDER_LOGD("Valid reminders size=%{public}d", reminders.size()); + REMINDER_LOGD("Dump:%{public}s", ReminderDataManager::GetInstance()->Dump().c_str()); // todo delete + return ERR_OK; +} + ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vector &dumpInfo) { ANS_LOGD("%{public}s", __FUNCTION__); diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp new file mode 100644 index 0000000..ba2829e --- /dev/null +++ b/services/ans/src/reminder_data_manager.cpp @@ -0,0 +1,606 @@ +/* + * 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_support.h" +#include "reminder_data_manager.h" +#include "reminder_event_manager.h" +#include "time_service_client.h" +#include "singleton.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 uint16_t ReminderDataManager::SAME_TIME_DISTINGUISH_MILLISECONDS = 1000; +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; + +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) { + REMINDER_LOGW("Cancel reminder, not find the reminder"); + return; + } + if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { + REMINDER_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_); + StopTimerLocked(); + } + int32_t id = reminderId; + RemoveReminderLocked(id); + CancelNotification(reminder); + StartRecentReminder(); +} + +void ReminderDataManager::CancelNotification(sptr &reminder) const +{ + if (!(reminder->IsShowing())) { + REMINDER_LOGD("No need to cancel notification"); + return; + } + sptr notification = reminder->GetNotificationRequest(); + if (notification == nullptr) { + REMINDER_LOGW("Cancel notification fail"); + } else { + REMINDER_LOGD("Cancel notification"); + if (advancedNotificationService_ == nullptr) { + REMINDER_LOGE("Cancel notification fail"); + return; + } + advancedNotificationService_->Cancel(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL); + } +} + +bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bundleName) const +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { + REMINDER_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()) { + REMINDER_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) { + REMINDER_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ + reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); + return true; + } + return false; +} + +void ReminderDataManager::CancelAllReminders(const sptr &bundleOption) +{ + MUTEX.lock(); + auto it = notificationBundleOptionMap_.find(activeReminderId_); + if (it == notificationBundleOptionMap_.end()) { + REMINDER_LOGD("Get bundle option error, reminderId=%{public}d", activeReminderId_); + } else { + if (it->second->GetBundleName() == bundleOption->GetBundleName()) { + StopTimer(); + } + } + for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { + int32_t reminderId = (*vit)->GetReminderId(); + auto mit = notificationBundleOptionMap_.find(reminderId); + if (mit == notificationBundleOptionMap_.end()) { + REMINDER_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + } else { + if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { + CancelNotification(*vit); + REMINDER_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()) { + REMINDER_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + } else { + if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { + reminders.push_back(*it); + } + } + } +} + +void ReminderDataManager::AddDefaultSlotIfNeeded(sptr &reminder) +{ + // todo +} + +std::shared_ptr ReminderDataManager::CreateTimerInfo() const +{ + auto sharedTimerInfo = std::make_shared(); + sharedTimerInfo->SetType(sharedTimerInfo->TIMER_TYPE_WAKEUP|sharedTimerInfo->TIMER_TYPE_EXACT); + sharedTimerInfo->SetRepeat(false); + sharedTimerInfo->SetInterval(0); + sharedTimerInfo->SetWantAgent(nullptr); + 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; + } + } + REMINDER_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) { + REMINDER_LOGW("Not find the reminder due to bundle info is null"); + return nullptr; + } + if (bundleOption -> GetBundleName() != pkgName) { + REMINDER_LOGW("Not find the reminder due to package name not match"); + return nullptr; + } + return reminder; +} + +sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) +{ + 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)); // todo fail to get param + CloseReminder(reminderId, cancelNotification); +} + +void ReminderDataManager::CloseReminder(const int32_t &reminderId, bool cancelNotification) +{ + sptr reminder = FindReminderRequestLocked(reminderId); + if (reminder == nullptr) { + REMINDER_LOGW("Invilate reminder id: %{public}d", reminderId); + return; + } + if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { + REMINDER_LOGD("Stop active reminder due to CloseReminder"); + StopTimerLocked(); + } + reminder->OnClose(true); + 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"; + REMINDER_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); + if (activeReminderId_ != -1) { + REMINDER_LOGD("Stop active reminder due to date/time or timeZone change"); + StopTimerLocked(); + } + std::vector> showImmediately = RefreshRemindersLocked(type); + if (!showImmediately.empty()) { + REMINDER_LOGD("Refresh all reminders, show expired reminders immediately"); + HandleImmediatelyShow(showImmediately, true); + } + StartRecentReminder(); +} + +void ReminderDataManager::UpdateAndSaveReminderLocked( + const sptr &reminder, const sptr &bundleOption) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + reminder->InitReminderId(); + int32_t reminderId = reminder->GetReminderId(); + REMINDER_LOGD("Containers(vector/map) add. reminderId=%{public}d", reminderId); + auto ret = notificationBundleOptionMap_.insert( + std::pair>(reminderId, bundleOption)); + if (!ret.second) { + REMINDER_LOGE("Containers add to map error"); + return; + } + reminderVector_.push_back(reminder); + totalCount_++; +} + +void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotificationService) +{ + advancedNotificationService_ = advancedNotificationService; +} + +void ReminderDataManager::ShowReminder(bool isSysTimeChanged) +{ + REMINDER_LOGD("ShowReminder"); + if (activeReminderId_ == -1) { + REMINDER_LOGE("Active reminder not exist"); + return; + } + sptr reminder = FindReminderRequestLocked(activeReminderId_); + ShowDesignatedReminderLocked(reminder, isSysTimeChanged); + ResetStates(); + StartRecentReminder(); +} + +void ReminderDataManager::ShowDesignatedReminderLocked(sptr &reminder, bool isSysTimeChanged) +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + uint64_t triggerTime = reminder->GetTriggerTimeInMilli(); + for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { + if ((*it)->IsExpired()) { + continue; + } + if ((*it)->GetTriggerTimeInMilli() - triggerTime > ReminderDataManager::SAME_TIME_DISTINGUISH_MILLISECONDS) { + continue; + } + if (isSysTimeChanged) { + if ((*it)->GetReminderId() != reminder->GetReminderId()) { + continue; + } + } + int32_t reminderId = (*it)->GetReminderId(); + sptr bundleOption = FindNotificationBundleOption(reminderId); + sptr notificationRequest = (*it)->GetNotificationRequest(); + if (bundleOption == nullptr) { + REMINDER_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); + continue; + } + if (advancedNotificationService_ == nullptr) { + REMINDER_LOGE("ShowReminder fail"); + (*it)->OnShow(isSysTimeChanged, false); + } else { + REMINDER_LOGD("publish notification.(reminderId=%{public}d)", reminderId); + (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); + (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); + + // todo update expiredContent + advancedNotificationService_->PublishSavedNotification(notificationRequest, bundleOption); + (*it)->OnShow(isSysTimeChanged, true); + HandleSameNotificationIdShowing((*it)); + } + } +} + +void ReminderDataManager::StartRecentReminder() +{ + sptr reminder = GetRecentReminderLocked(); + if (reminder == nullptr) { + REMINDER_LOGI("No reminder need to start"); + return; + } + + bool toStart = true; + if (activeReminderId_ != -1) { + if (activeReminderId_ != reminder->GetReminderId()) { + REMINDER_LOGI("Stop active reminder"); + StopTimerLocked(); + } else { + REMINDER_LOGI("Recent reminder has already run, no need to start again."); + toStart = false; + } + } + if (toStart) { + REMINDER_LOGI("Start recent reminder"); + StartTimerLocked(reminder); + } +} + +void ReminderDataManager::StopTimer() +{ + if (timerId_ == 0) { + REMINDER_LOGD("Timer is not running"); + return; + } + REMINDER_LOGD("Stop timer id=%{public}llu", timerId_); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + timer->StopTimer(timerId_); + ResetStates(); +} + +void ReminderDataManager::StopTimerLocked() +{ + std::lock_guard lock(ReminderDataManager::MUTEX); + StopTimer(); +} + +std::string ReminderDataManager::Dump() const +{ + REMINDER_LOGD("Enter"); + 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()) { + REMINDER_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 reminder = reminderVector_.begin(); reminder != reminderVector_.end();) { + if (!(*reminder)->IsExpired()) { + REMINDER_LOGD("GetRecentReminderLocked: %{public}s", (*reminder)->Dump().c_str()); + return *reminder; + } + if (!(*reminder)->CanRemove()) { + REMINDER_LOGD("Reminder has been expired: %{public}s", (*reminder)->Dump().c_str()); + reminder++; + continue; + } + int32_t reminderId = (*reminder)->GetReminderId(); + REMINDER_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + auto it = notificationBundleOptionMap_.find((*reminder)->GetReminderId()); + if (it == notificationBundleOptionMap_.end()) { + REMINDER_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", + (*reminder)->GetReminderId()); + } else { + REMINDER_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); + notificationBundleOptionMap_.erase(it); + } + reminder = reminderVector_.erase(reminder); + 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) { + REMINDER_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) +{ + for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { + ShowDesignatedReminderLocked((*it), isSysTimeChanged); + } +} + +sptr ReminderDataManager::HandleRefreshReminder(uint8_t &type, sptr &reminder) +{ + bool needShowImmediately = false; + if (type == TIME_ZONE_CHANGE) { + needShowImmediately = reminder->OnTimeZoneChange(); + } + if (type == DATE_TIME_CHANGE) { + needShowImmediately = reminder->OnDateTimeChange(); + } + if (!needShowImmediately) { + return nullptr; + } else { + return reminder; + } +} + +void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) +{ + // not add ReminderDataManager::MUTEX, as ShowDesignatedReminderLocked has locked + int32_t notificationId = reminder->GetNotificationId(); + REMINDER_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) { + REMINDER_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); + continue; + } + if (notificationId == (*it)->GetNotificationId() && + IsBelongToSameApp(reminder, bundleOption->GetBundleName(), 0)) { + (*it)->OnSameNotificationIdCovered(); + } + } +} + +bool ReminderDataManager::IsBelongToSameApp( + const sptr reminder, const std::string otherPkgName, const int otherUserId) +{ + REMINDER_LOGD("otherUserId=%{public}d, (currently, userId not support)", otherUserId); + int32_t reminderId = reminder->GetReminderId(); + sptr bundleOption = FindNotificationBundleOption(reminderId); + if (bundleOption == nullptr) { + REMINDER_LOGW("IsBelongToSameApp get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + return false; + } + if (bundleOption->GetBundleName() == otherPkgName) { + return true; + } + return false; +} + +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()) { + REMINDER_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + it = reminderVector_.erase(it); + totalCount_--; + REMINDER_LOGD("Remove reminder(id=%{public}d) success", reminderId); + break; + } else { + ++it; + } + } + auto it = notificationBundleOptionMap_.find(reminderId); + if (it == notificationBundleOptionMap_.end()) { + REMINDER_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); + } else { + REMINDER_LOGD("Containers(map) remove: reminderId=%{public}d", reminderId); + notificationBundleOptionMap_.erase(it); + } +} + +void ReminderDataManager::ResetStates() +{ + REMINDER_LOGD("ResetStates"); + timerId_ = 0; + activeReminderId_ = -1; +} + +void ReminderDataManager::StartTimerLocked(sptr &reminderRequest) +{ + REMINDER_LOGD("Start timer: millSeconds=%{public}llu", reminderRequest->GetTriggerTimeInMilli()); + std::lock_guard lock(ReminderDataManager::MUTEX); + sptr timer = MiscServices::TimeServiceClient::GetInstance(); + timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo()); + timer->StartTimer(timerId_, reminderRequest->GetTriggerTimeInMilli()); + activeReminderId_ = reminderRequest->GetReminderId(); +} +} +} \ 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 0000000..d3d98b3 --- /dev/null +++ b/services/ans/src/reminder_event_manager.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 "ans_log_wrapper.h" +#include "common_event_manager.h" +#include "common_event_support.h" +#include "reminder_event_manager.h" +#include "bundle_constants.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_CLOSE_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)) { + REMINDER_LOGD("SubscribeCommonEvent ok"); + } else { + REMINDER_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(); + REMINDER_LOGD("Recieved common event:%{public}s", action.c_str()); + if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { + reminderDataManager_->ShowReminder(false); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_CLOSE_ALERT) { + reminderDataManager_->CloseReminder(want, true); + return; + } + if (action == ReminderRequest::REMINDER_EVENT_REMOVE_NOTIFICATION) { + reminderDataManager_->CloseReminder(want, false); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED) { + OHOS::AppExecFwk::ElementName ele = want.GetElement(); + std::string bundleName = ele.GetBundleName(); + int uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); + REMINDER_LOGD("bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); + sptr bundleOption = new NotificationBundleOption(bundleName, uid); + reminderDataManager_->CancelAllReminders(bundleOption); + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { + // todo + return; + } + if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { + // todo + 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; + } +} +} // namespace OHOS +} // namespace Notification \ No newline at end of file diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp new file mode 100644 index 0000000..a649651 --- /dev/null +++ b/services/ans/src/reminder_timer_info.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "ans_log_wrapper.h" +#include "reminder_timer_info.h" +#include "reminder_request.h" +#include "common_event_manager.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() +{ + REMINDER_LOGI("ReminderTimer is triggerred"); + PublishCommonEvent(ReminderRequest::REMINDER_EVENT_ALARM_ALERT); +} + +bool ReminderTimerInfo::PublishCommonEvent(const std::string &action) const +{ + Want want; + want.SetAction(action); + CommonEventData data; + data.SetWant(want); + CommonEventPublishInfo publishInfo; + publishInfo.SetOrdered(false); + return CommonEventManager::PublishCommonEvent(data, publishInfo); +} +} +} \ No newline at end of file diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index b404f89..508d221 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -22,6 +22,9 @@ ohos_unittest("ans_unit_test") { include_dirs = [ ".", "include", + "//base/miscservices/time/interfaces/innerkits/include", + "//base/miscservices/time/services/time_manager/include", + "//base/miscservices/time/utils/native/include", "//foundation/appexecfwk/standard/libs/libeventhandler/src", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy/include", "//utils/native/base/include", @@ -47,6 +50,9 @@ ohos_unittest("ans_unit_test") { "${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", @@ -68,10 +74,13 @@ ohos_unittest("ans_unit_test") { configs = [ "//utils/native/base:utils_config" ] deps = [ + "//base/miscservices/time/services:time_service", "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", -- Gitee From 378464dc6e498b53eec52f7007865fe8f45077a2 Mon Sep 17 00:00:00 2001 From: derek Date: Sat, 25 Dec 2021 10:21:52 +0800 Subject: [PATCH 059/131] =?UTF-8?q?fix=20js=20interface=201=E3=80=81Publis?= =?UTF-8?q?hReminder=20return=20value=202.fix=20dayOfWeek=20must=20be=20se?= =?UTF-8?q?tted?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: derek Change-Id: Ibae0678cbe19e3c2dbfc7001aca237e5394517c2 --- .../ans/native/src/reminder_request.cpp | 9 --- .../kits/napi/ans/src/reminder/common.cpp | 64 +++++++++---------- .../kits/napi/ans/src/reminder/publish.cpp | 7 +- services/ans/include/reminder_data_manager.h | 7 -- .../ans/src/advanced_notification_service.cpp | 1 - services/ans/src/reminder_data_manager.cpp | 9 +-- 6 files changed, 38 insertions(+), 59 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 3f74ce2..614275f 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -75,19 +75,11 @@ std::string ReminderRequest::Dump() const uint8_t dateTimeLen = 80; char dateTimeBuffer[dateTimeLen]; strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); - // todo return "Reminder[" "id=" + std::to_string(reminderId_) + ", type=" + std::to_string(static_cast(reminderType_)) + ", state=" + GetState(state_) + ", nextTriggerTime=" + dateTimeBuffer + - // ", isExpired=" + std::to_string(isExpired_) + - // ", title=" + title_ + - // ", content=" + content_ + - // ", expiredContent=" + expiredContent_ + - // ", notificationId=" + std::to_string(notificationId_) + - // ", slotType=" + std::to_string(slotType_) + - // ", wantAgent=" + wantAgentInfo_->pkgName + "#" + wantAgentInfo_->abilityName + "]"; } @@ -232,7 +224,6 @@ void ReminderRequest::OnSameNotificationIdCovered() void ReminderRequest::OnShow(bool isSysTimeChanged, bool allowToNotify) { - // todo isSysTimeChanged if (allowToNotify) { SetState(true, REMINDER_STATUS_SHOWING, "OnShow"); } diff --git a/interfaces/kits/napi/ans/src/reminder/common.cpp b/interfaces/kits/napi/ans/src/reminder/common.cpp index af16820..86850ef 100644 --- a/interfaces/kits/napi/ans/src/reminder/common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/common.cpp @@ -253,7 +253,7 @@ bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value, NAPI_CALL(env, napi_has_named_property(env, value, propertyName, &hasProperty)); if (!hasProperty) { - return true; + return false; } napi_get_named_property(env, value, propertyName, &propertyVal); NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); @@ -311,43 +311,41 @@ napi_value ReminderCommon::CreateReminderAlarm( // daysOfWeek napi_value result = nullptr; - if (!GetObject(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { - REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); - return nullptr; - } std::vector daysOfWeek; - if (result != nullptr) { // function line too long - bool isArray = false; - napi_is_array(env, result, &isArray); - if (!isArray) { - REMINDER_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); - return nullptr; - } - uint32_t length = 0; - napi_get_array_length(env, result, &length); - uint8_t maxDaysOfWeek = 7; - if (length > maxDaysOfWeek) { - REMINDER_LOGE("The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); - 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) { - REMINDER_LOGE("%{public}s's element is expected to be number.", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + if (GetObject(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { + if (result != nullptr) { // function line too long + bool isArray = false; + napi_is_array(env, result, &isArray); + if (!isArray) { + REMINDER_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); return nullptr; } - napi_get_value_int32(env, repeatDayVal, &propertyDayVal); - if (propertyDayVal < 1 || propertyDayVal > maxDaysOfWeek) { - REMINDER_LOGE("%{public}s's element must between [1, %{public}d].", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + uint32_t length = 0; + napi_get_array_length(env, result, &length); + uint8_t maxDaysOfWeek = 7; + if (length > maxDaysOfWeek) { + REMINDER_LOGE("The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); return nullptr; } - daysOfWeek.push_back(static_cast(propertyDayVal)); + 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) { + REMINDER_LOGE("%{public}s's element is expected to be number.", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + return nullptr; + } + napi_get_value_int32(env, repeatDayVal, &propertyDayVal); + if (propertyDayVal < 1 || propertyDayVal > maxDaysOfWeek) { + REMINDER_LOGE("%{public}s's element must between [1, %{public}d].", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + return nullptr; + } + daysOfWeek.push_back(static_cast(propertyDayVal)); + } } } reminder = std::make_shared( diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 962c94f..8e8a2c3 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -525,12 +525,17 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); REMINDER_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) { REMINDER_LOGI("Publish napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; NotificationNapi::Common::ReturnCallbackPromise( - env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); + env, asynccallbackinfo->info, asynccallbackinfo->result); if (asynccallbackinfo->info.callback != nullptr) { napi_delete_reference(env, asynccallbackinfo->info.callback); } diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 07d5378..049682b 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -112,13 +112,6 @@ public: static const uint8_t DATE_TIME_CHANGE; private: - /** - * Add default slot to the reminder if no slot set by user. - * - * @param reminder Indicates the reminder. - */ - void AddDefaultSlotIfNeeded(sptr &reminder); - /** * Cancels the notification relative to the reminder. * diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index c0f1e93..a5a8fb7 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1489,7 +1489,6 @@ ErrCode AdvancedNotificationService::GetValidReminders(std::vectorGetValidReminders(bundleOption, reminders); REMINDER_LOGD("Valid reminders size=%{public}d", reminders.size()); - REMINDER_LOGD("Dump:%{public}s", ReminderDataManager::GetInstance()->Dump().c_str()); // todo delete return ERR_OK; } diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index ba2829e..9be038e 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -159,11 +159,6 @@ void ReminderDataManager::GetValidReminders( } } -void ReminderDataManager::AddDefaultSlotIfNeeded(sptr &reminder) -{ - // todo -} - std::shared_ptr ReminderDataManager::CreateTimerInfo() const { auto sharedTimerInfo = std::make_shared(); @@ -223,7 +218,7 @@ bool ReminderDataManager::cmp(sptr &reminderRequest, sptr(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); // todo fail to get param + int32_t reminderId = static_cast(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); CloseReminder(reminderId, cancelNotification); } @@ -335,8 +330,6 @@ void ReminderDataManager::ShowDesignatedReminderLocked(sptr &re REMINDER_LOGD("publish notification.(reminderId=%{public}d)", reminderId); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); - - // todo update expiredContent advancedNotificationService_->PublishSavedNotification(notificationRequest, bundleOption); (*it)->OnShow(isSysTimeChanged, true); HandleSameNotificationIdShowing((*it)); -- Gitee From 6e2ae5b1128c07978c7314003e9e9c5d1e2a95a2 Mon Sep 17 00:00:00 2001 From: zhongjianfei Date: Sat, 25 Dec 2021 11:49:44 +0800 Subject: [PATCH 060/131] zhongjianfei@huawei.com Signed-off-by: zhongjianfei Change-Id: I056bcd37eabe7d6955d0b4b06d57e903e3605d5b --- .../kits/napi/wantagent/napi_want_agent.cpp | 61 ++++++++++++++++++- 1 file changed, 60 insertions(+), 1 deletion(-) diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.cpp b/interfaces/kits/napi/wantagent/napi_want_agent.cpp index 1d7fa5f..8239cca 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.cpp +++ b/interfaces/kits/napi/wantagent/napi_want_agent.cpp @@ -235,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; @@ -251,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( @@ -354,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; @@ -376,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( @@ -478,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; @@ -499,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( @@ -622,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; @@ -638,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( @@ -751,8 +799,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) @@ -898,6 +951,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; @@ -914,6 +971,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) { @@ -924,6 +982,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( @@ -1298,4 +1357,4 @@ napi_value NapiGetNull(napi_env env) napi_get_null(env, &result); return result; } -} // namespace OHOS \ No newline at end of file +} // namespace OHOS -- Gitee From 1e175cc94042979963ad25a250942ef030dc005d Mon Sep 17 00:00:00 2001 From: derek Date: Sat, 25 Dec 2021 16:57:09 +0800 Subject: [PATCH 061/131] fix codeCheck Signed-off-by: derek Change-Id: If4edaac53b3b89b5427a390e92a8c998c4abf9e5 --- .../ans/core/common/include/ans_log_wrapper.h | 12 +- frameworks/ans/core/src/ans_manager_proxy.cpp | 54 +++--- frameworks/ans/core/src/ans_manager_stub.cpp | 34 ++-- frameworks/ans/core/src/ans_notification.cpp | 6 +- frameworks/ans/native/src/reminder_helper.cpp | 29 ++-- .../ans/native/src/reminder_request.cpp | 91 +++++----- .../ans/native/src/reminder_request_alarm.cpp | 51 +++--- .../ans/native/src/reminder_request_timer.cpp | 31 ++-- .../unittest/reminder_request_alarm_test.cpp | 19 ++- .../unittest/reminder_request_timer_test.cpp | 18 +- .../ans/native/include/reminder_request.h | 5 +- .../native/include/reminder_request_alarm.h | 3 +- .../native/include/reminder_request_timer.h | 5 +- .../kits/napi/ans/include/reminder/publish.h | 10 +- .../reminder/{common.h => reminder_common.h} | 3 + .../kits/napi/ans/src/reminder/BUILD.gn | 2 +- .../napi/ans/src/reminder/native_module.cpp | 8 +- .../kits/napi/ans/src/reminder/publish.cpp | 81 +++++---- .../{common.cpp => reminder_common.cpp} | 160 ++++++++++-------- services/ans/include/reminder_data_manager.h | 7 +- services/ans/include/reminder_event_manager.h | 9 +- services/ans/include/reminder_timer_info.h | 6 +- .../ans/src/advanced_notification_service.cpp | 18 +- services/ans/src/reminder_data_manager.cpp | 113 +++++++------ services/ans/src/reminder_event_manager.cpp | 11 +- services/ans/src/reminder_timer_info.cpp | 7 +- 26 files changed, 400 insertions(+), 393 deletions(-) rename interfaces/kits/napi/ans/include/reminder/{common.h => reminder_common.h} (96%) rename interfaces/kits/napi/ans/src/reminder/{common.cpp => reminder_common.cpp} (68%) diff --git a/frameworks/ans/core/common/include/ans_log_wrapper.h b/frameworks/ans/core/common/include/ans_log_wrapper.h index a95f38e..cbcc8a9 100644 --- a/frameworks/ans/core/common/include/ans_log_wrapper.h +++ b/frameworks/ans/core/common/include/ans_log_wrapper.h @@ -33,7 +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_derek"}; +static constexpr OHOS::HiviewDFX::HiLogLabel ANS_REMINDER_LABEL = {LOG_CORE, LOG_DOMAIN, "ANS_REMINDER"}; class AnsLogWrapper { public: @@ -82,11 +82,11 @@ private: __LINE__, \ ##__VA_ARGS__) -#define REMINDER_LOGD(fmt, ...) PRINT_REMINDER_LOG(DEBUG, Debug, fmt, ##__VA_ARGS__) -#define REMINDER_LOGI(fmt, ...) PRINT_REMINDER_LOG(INFO, Info, fmt, ##__VA_ARGS__) -#define REMINDER_LOGW(fmt, ...) PRINT_REMINDER_LOG(WARN, Warn, fmt, ##__VA_ARGS__) -#define REMINDER_LOGE(fmt, ...) PRINT_REMINDER_LOG(ERROR, Error, fmt, ##__VA_ARGS__) -#define REMINDER_LOGF(fmt, ...) PRINT_REMINDER_LOG(FATAL, Fatal, fmt, ##__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/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 3bb6fd0..18d9c68 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1945,22 +1945,22 @@ ErrCode AnsManagerProxy::CancelContinuousTaskNotification(const std::string &lab ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) { - REMINDER_LOGI("PublishReminder"); + ANSR_LOGI("PublishReminder"); MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - REMINDER_LOGE("[PublishReminder] fail: write interface token failed."); + ANSR_LOGE("[PublishReminder] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } if (reminder == nullptr) { - REMINDER_LOGW("[PublishReminder] fail: reminder is null ptr."); + ANSR_LOGW("[PublishReminder] fail: reminder is null ptr."); return ERR_ANS_INVALID_PARAM; } if (!data.WriteUint8(static_cast(reminder->GetReminderType()))) { - REMINDER_LOGE("[PublishReminder] fail: write reminder type failed"); + ANSR_LOGE("[PublishReminder] fail: write reminder type failed"); return ERR_ANS_PARCELABLE_FAILED; } if (!data.WriteParcelable(reminder)) { - REMINDER_LOGE("[Publish] fail: write reminder parcelable failed"); + ANSR_LOGE("[Publish] fail: write reminder parcelable failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1968,30 +1968,30 @@ ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) MessageOption option = {MessageOption::TF_SYNC}; ErrCode result = InnerTransact(PUBLISH_REMINDER, option, data, reply); if (result != ERR_OK) { - REMINDER_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); + ANSR_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } else { int32_t reminderId = -1; if (!reply.ReadInt32(reminderId)) { - REMINDER_LOGE("[PublishReminder] fail: derek read reminder id failed."); + ANSR_LOGE("[PublishReminder] fail: derek read reminder id failed."); return ERR_ANS_PARCELABLE_FAILED; } reminder->SetReminderId(reminderId); - REMINDER_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); + ANSR_LOGD("ReminderId=%{public}d", reminder->GetReminderId()); } return result; } ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) { - REMINDER_LOGI("[CancelReminder]"); + ANSR_LOGI("[CancelReminder]"); MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - REMINDER_LOGE("[CancelReminder] fail: write interface token failed."); + ANSR_LOGE("[CancelReminder] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } if (!data.WriteInt32(reminderId)) { - REMINDER_LOGE("[CancelReminder] fail: write reminder id failed"); + ANSR_LOGE("[CancelReminder] fail: write reminder id failed"); return ERR_ANS_PARCELABLE_FAILED; } @@ -1999,7 +1999,7 @@ ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) MessageOption option = {MessageOption::TF_SYNC}; ErrCode result = InnerTransact(CANCEL_REMINDER, option, data, reply); if (result != ERR_OK) { - REMINDER_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); + ANSR_LOGE("[CancelReminder] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } return result; @@ -2007,10 +2007,10 @@ ErrCode AnsManagerProxy::CancelReminder(const int32_t reminderId) ErrCode AnsManagerProxy::CancelAllReminders() { - REMINDER_LOGI("[CancelAllReminders]"); + ANSR_LOGI("[CancelAllReminders]"); MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - REMINDER_LOGE("[CancelAllReminders] fail: write interface token failed."); + ANSR_LOGE("[CancelAllReminders] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -2018,7 +2018,7 @@ ErrCode AnsManagerProxy::CancelAllReminders() MessageOption option = {MessageOption::TF_SYNC}; ErrCode result = InnerTransact(CANCEL_ALL_REMINDERS, option, data, reply); if (result != ERR_OK) { - REMINDER_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); + ANSR_LOGE("[CancelAllReminders] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } return result; @@ -2026,10 +2026,10 @@ ErrCode AnsManagerProxy::CancelAllReminders() ErrCode AnsManagerProxy::GetValidReminders(std::vector> &reminders) { - REMINDER_LOGI("[GetValidReminders]"); + ANSR_LOGI("[GetValidReminders]"); MessageParcel data; if (!data.WriteInterfaceToken(AnsManagerProxy::GetDescriptor())) { - REMINDER_LOGE("[GetValidReminders] fail: write interface token failed."); + ANSR_LOGE("[GetValidReminders] fail: write interface token failed."); return ERR_ANS_PARCELABLE_FAILED; } @@ -2037,21 +2037,21 @@ ErrCode AnsManagerProxy::GetValidReminders(std::vector> &r MessageOption option = {MessageOption::TF_SYNC}; ErrCode result = InnerTransact(GET_ALL_VALID_REMINDERS, option, data, reply); if (result != ERR_OK) { - REMINDER_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); + ANSR_LOGE("[GetValidReminders] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; } else { uint8_t count = 0; if (!reply.ReadUint8(count)) { - REMINDER_LOGE("[GetValidReminders] fail: read reminder count failed."); + ANSR_LOGE("[GetValidReminders] fail: read reminder count failed."); return ERR_ANS_PARCELABLE_FAILED; } - REMINDER_LOGD("[GetValidReminders] count=%{public}u", count); + ANSR_LOGD("[GetValidReminders] count=%{public}u", count); reminders.clear(); result = ReadReminders(count, reply, reminders); if (result != ERR_OK) { - REMINDER_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); + ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); } else { - REMINDER_LOGD("[GetValidReminders], size=%{public}d", reminders.size()); + ANSR_LOGD("[GetValidReminders], size=%{public}d", reminders.size()); } } return result; @@ -2063,23 +2063,23 @@ ErrCode AnsManagerProxy::ReadReminders( for (int i = 0; i < count; i++) { uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); if (!reply.ReadUint8(typeInfo)) { - REMINDER_LOGE("Failed to read reminder type"); + ANSR_LOGE("Failed to read reminder type"); return ERR_ANS_PARCELABLE_FAILED; } auto reminderType = static_cast(typeInfo); sptr reminder; if (ReminderRequest::ReminderType::ALARM == reminderType) { - REMINDER_LOGD("[GetValidReminders] alarm"); + ANSR_LOGD("[GetValidReminders] alarm"); reminder = reply.ReadParcelable(); } else if (ReminderRequest::ReminderType::TIMER == reminderType) { - REMINDER_LOGD("[GetValidReminders] timer"); + ANSR_LOGD("[GetValidReminders] timer"); reminder = reply.ReadParcelable(); } else { - REMINDER_LOGW("[GetValidReminders] type=%{public}d", typeInfo); + ANSR_LOGW("[GetValidReminders] type=%{public}d", typeInfo); return ERR_ANS_INVALID_PARAM; } if (!reminder) { - REMINDER_LOGE("[GetValidReminders] fail: Reminder ReadParcelable failed"); + ANSR_LOGE("[GetValidReminders] fail: Reminder ReadParcelable failed"); return ERR_ANS_PARCELABLE_FAILED; } reminders.push_back(reminder); diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 51a2b3c..16032b5 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -1267,33 +1267,33 @@ ErrCode AnsManagerStub::HandleShellDump(MessageParcel &data, MessageParcel &repl ErrCode AnsManagerStub::HandlePublishReminder(MessageParcel &data, MessageParcel &reply) { - REMINDER_LOGI("HandlePublishReminder"); + ANSR_LOGI("HandlePublishReminder"); uint8_t typeInfo = static_cast(ReminderRequest::ReminderType::INVALID); if (!data.ReadUint8(typeInfo)) { - REMINDER_LOGE("Failed to read reminder type"); + 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) { - REMINDER_LOGD("Publish alarm"); + ANSR_LOGD("Publish alarm"); reminder = data.ReadParcelable(); } else if (ReminderRequest::ReminderType::TIMER == reminderType) { - REMINDER_LOGD("Publish timer"); + ANSR_LOGD("Publish timer"); reminder = data.ReadParcelable(); } else { - REMINDER_LOGE("Reminder type invalid"); + ANSR_LOGE("Reminder type invalid"); return ERR_ANS_INVALID_PARAM; } if (!reminder) { - REMINDER_LOGE("Reminder ReadParcelable failed"); + ANSR_LOGE("Reminder ReadParcelable failed"); return ERR_ANS_PARCELABLE_FAILED; } ErrCode result = PublishReminder(reminder); if (!reply.WriteInt32(reminder->GetReminderId())) { - REMINDER_LOGE("Write back reminderId failed"); + ANSR_LOGE("Write back reminderId failed"); return ERR_ANS_PARCELABLE_FAILED; } return result; @@ -1301,14 +1301,14 @@ ErrCode AnsManagerStub::HandlePublishReminder(MessageParcel &data, MessageParcel ErrCode AnsManagerStub::HandleCancelReminder(MessageParcel &data, MessageParcel &reply) { - REMINDER_LOGI("HandleCancelReminder"); + ANSR_LOGI("HandleCancelReminder"); int32_t reminderId = -1; if (!data.ReadInt32(reminderId)) { - REMINDER_LOGE("Read reminder id failed."); + ANSR_LOGE("Read reminder id failed."); return ERR_ANS_PARCELABLE_FAILED; } - - REMINDER_LOGD("ReminderId=%{public}d", reminderId); + + ANSR_LOGD("ReminderId=%{public}d", reminderId); return CancelReminder(reminderId); } @@ -1319,26 +1319,26 @@ ErrCode AnsManagerStub::HandleCancelAllReminders(MessageParcel &data, MessagePar ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParcel &reply) { - REMINDER_LOGI("HandleGetValidReminders"); + ANSR_LOGI("HandleGetValidReminders"); std::vector> validReminders; ErrCode result = GetValidReminders(validReminders); - REMINDER_LOGD("Write back size=%{public}d", validReminders.size()); + ANSR_LOGD("Write back size=%{public}d", validReminders.size()); if (!reply.WriteUint8(static_cast(validReminders.size()))) { - REMINDER_LOGE("Write back reminder count failed"); + 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()); - REMINDER_LOGD("ReminderType=%{public}d", reminderType); + ANSR_LOGD("ReminderType=%{public}d", reminderType); if (!reply.WriteUint8(reminderType)) { - REMINDER_LOGW("Write reminder type failed"); + ANSR_LOGW("Write reminder type failed"); return ERR_ANS_PARCELABLE_FAILED; } if (!reply.WriteParcelable(reminder)) { - REMINDER_LOGW("Write reminder parcelable failed"); + ANSR_LOGW("Write reminder parcelable failed"); return ERR_ANS_PARCELABLE_FAILED; } } diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index b033358..9f2214e 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -873,15 +873,15 @@ ErrCode AnsNotification::PublishReminder(ReminderRequest &reminder) sptr tarReminder; if (reminder.GetReminderType() == ReminderRequest::ReminderType::ALARM) { - REMINDER_LOGI("Publish alarm"); + ANSR_LOGI("Publish alarm"); ReminderRequestAlarm &alarm = (ReminderRequestAlarm &)reminder; tarReminder = new (std::nothrow) ReminderRequestAlarm(alarm); } else if (reminder.GetReminderType() == ReminderRequest::ReminderType::TIMER) { - REMINDER_LOGI("Publish timer"); + ANSR_LOGI("Publish timer"); ReminderRequestTimer &timer = (ReminderRequestTimer &)reminder; tarReminder = new (std::nothrow) ReminderRequestTimer(timer); } else { - REMINDER_LOGW("PublishReminder fail."); + ANSR_LOGW("PublishReminder fail."); return ERR_ANS_INVALID_PARAM; } ErrCode code = ansManagerProxy_->PublishReminder(tarReminder); diff --git a/frameworks/ans/native/src/reminder_helper.cpp b/frameworks/ans/native/src/reminder_helper.cpp index 6ac8013..aa36349 100644 --- a/frameworks/ans/native/src/reminder_helper.cpp +++ b/frameworks/ans/native/src/reminder_helper.cpp @@ -18,21 +18,16 @@ #include "application_env_impl.h" #include "iservice_registry.h" #include "notification_helper.h" -#include "reminder_helper.h" -#include "system_ability_definition.h" #include "singleton.h" +#include "system_ability_definition.h" + +#include "reminder_helper.h" namespace OHOS { namespace Notification { ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) { - REMINDER_LOGI("PublishReminder start"); - - // wait bundle manager to implement permission check. - // if (!CheckPermission()) { - // return ERR_PERMISSION_DENIED; - // } - + ANSR_LOGI("PublishReminder start"); NotificationSlot slot(reminder.GetSlotType()); NotificationHelper::AddNotificationSlot(slot); return DelayedSingleton::GetInstance()->PublishReminder(reminder); @@ -40,30 +35,30 @@ ErrCode ReminderHelper::PublishReminder(ReminderRequest &reminder) ErrCode ReminderHelper::CancelReminder(const int32_t reminderId) { - REMINDER_LOGI("CancelReminder start"); + ANSR_LOGI("CancelReminder start"); return DelayedSingleton::GetInstance()->CancelReminder(reminderId); } ErrCode ReminderHelper::CancelAllReminders() { - REMINDER_LOGI("CancelAllReminders start"); + ANSR_LOGI("CancelAllReminders start"); return DelayedSingleton::GetInstance()->CancelAllReminders(); } bool ReminderHelper::CheckPermission() { - REMINDER_LOGI("CheckPermission"); + ANSR_LOGI("CheckPermission"); AppExecFwk::ApplicationEnvImpl* application = AppExecFwk::ApplicationEnvImpl::GetInstance(); std::string pkgName = application->GetBundleName(); sptr systemManager = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); if (systemManager == nullptr) { - REMINDER_LOGE("Permission denied"); + 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) { - REMINDER_LOGE("Permission denied"); + ANSR_LOGE("Permission denied"); return false; } return true; @@ -71,19 +66,19 @@ bool ReminderHelper::CheckPermission() ErrCode ReminderHelper::GetValidReminders(std::vector> &validReminders) { - REMINDER_LOGI("GetValidReminders start"); + ANSR_LOGI("GetValidReminders start"); return DelayedSingleton::GetInstance()->GetValidReminders(validReminders); } ErrCode AddNotificationSlot(const NotificationSlot &slot) { - REMINDER_LOGI("AddNotificationSlot start"); + ANSR_LOGI("AddNotificationSlot start"); return DelayedSingleton::GetInstance()->AddNotificationSlot(slot); } ErrCode RemoveNotificationSlot(const NotificationConstant::SlotType &slotType) { - REMINDER_LOGI("RemoveNotificationSlot start"); + ANSR_LOGI("RemoveNotificationSlot start"); return DelayedSingleton::GetInstance()->RemoveNotificationSlot(slotType); } } diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 614275f..a3296a6 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -14,9 +14,10 @@ */ #include "ans_log_wrapper.h" -#include "reminder_request.h" #include "want_agent_helper.h" +#include "reminder_request.h" + namespace OHOS { namespace Notification { int32_t ReminderRequest::GLOBAL_ID = 0; @@ -74,7 +75,7 @@ std::string ReminderRequest::Dump() const timeInfo = localtime(&nextTriggerTime); uint8_t dateTimeLen = 80; char dateTimeBuffer[dateTimeLen]; - strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); + (void)strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); return "Reminder[" "id=" + std::to_string(reminderId_) + ", type=" + std::to_string(static_cast(reminderType_)) + @@ -86,7 +87,7 @@ std::string ReminderRequest::Dump() const ReminderRequest& ReminderRequest::SetActionButton(const std::string &title, const ActionButtonType &type) { if (type != ActionButtonType::CLOSE) { - REMINDER_LOGI("Button type only support: %{public}d", static_cast(ActionButtonType::CLOSE)); + ANSR_LOGI("Button type only support: %{public}d", static_cast(ActionButtonType::CLOSE)); return *this; } ActionButtonInfo actionButtonInfo; @@ -117,11 +118,11 @@ void ReminderRequest::InitReminderId() { std::lock_guard lock(std::mutex); if (GLOBAL_ID < 0) { - REMINDER_LOGW("GLOBAL_ID overdule"); + ANSR_LOGW("GLOBAL_ID overdule"); GLOBAL_ID = 0; } reminderId_ = ++GLOBAL_ID; - REMINDER_LOGI("reminderId_=%{public}d", reminderId_); + ANSR_LOGI("reminderId_=%{public}d", reminderId_); } bool ReminderRequest::IsExpired() const @@ -140,7 +141,7 @@ bool ReminderRequest::IsShowing() const void ReminderRequest::OnClose(bool updateNext) { if ((state_ & REMINDER_STATUS_SHOWING) == 0) { - REMINDER_LOGE("onClose, the state of reminder is incorrect, state:%{public}s", GetState(state_).c_str()); + ANSR_LOGE("onClose, the state of reminder is incorrect, state:%{public}s", GetState(state_).c_str()); return; } SetState(false, REMINDER_STATUS_SHOWING, "onClose()"); @@ -173,7 +174,7 @@ bool ReminderRequest::HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optT time_t now; time(&now); // unit is seconds. if (static_cast(now) < 0) { - REMINDER_LOGE("Get now time error"); + ANSR_LOGE("Get now time error"); return false; } if (oriTriggerTime <= (static_cast(now) * MILLI_SECONDS)) { @@ -188,12 +189,13 @@ bool ReminderRequest::HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optT return showImmediately; } -bool ReminderRequest::HandleTimeZoneChange(uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime) +bool ReminderRequest::HandleTimeZoneChange( + uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime) { if (isExpired_) { return false; } - REMINDER_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", + ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", oldZoneTriggerTime, newZoneTriggerTime); bool showImmediately = false; if (optTriggerTime != INVALID_LONG_VALUE && oldZoneTriggerTime < newZoneTriggerTime) { @@ -203,7 +205,7 @@ bool ReminderRequest::HandleTimeZoneChange(uint64_t oldZoneTriggerTime, uint64_t time_t now; time(&now); // unit is seconds. if (static_cast(now) < 0) { - REMINDER_LOGE("Get now time error"); + ANSR_LOGE("Get now time error"); return false; } if (newZoneTriggerTime <= (static_cast(now))) { @@ -269,8 +271,8 @@ ReminderRequest& ReminderRequest::SetWantAgentInfo(const std::shared_ptr ReminderRequest::GetActionButtons() const +std::map ReminderRequest::GetActionButtons() + const { return actionButtonMap_; } @@ -342,8 +344,8 @@ bool ReminderRequest::UpdateNextReminder() void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra) { - REMINDER_LOGI("UpdateNotification type=%{public}d", static_cast(type)); - switch(type) { + ANSR_LOGI("UpdateNotification type=%{public}d", static_cast(type)); + switch (type) { case UpdateNotificationType::ACTION_BUTTON: { AddActionButtons(); break; @@ -364,63 +366,63 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const { // write string if (!parcel.WriteString(content_)) { - REMINDER_LOGE("Failed to write content"); + ANSR_LOGE("Failed to write content"); return false; } if (!parcel.WriteString(expiredContent_)) { - REMINDER_LOGE("Failed to write expiredContent"); + ANSR_LOGE("Failed to write expiredContent"); return false; } if (!parcel.WriteString(title_)) { - REMINDER_LOGE("Failed to write title"); + ANSR_LOGE("Failed to write title"); return false; } if (!parcel.WriteString(wantAgentInfo_->abilityName)) { - REMINDER_LOGE("Failed to write wantAgentInfo`s abilityName"); + ANSR_LOGE("Failed to write wantAgentInfo`s abilityName"); return false; } if (!parcel.WriteString(wantAgentInfo_->pkgName)) { - REMINDER_LOGE("Failed to write wantAgentInfo`s pkgName"); + ANSR_LOGE("Failed to write wantAgentInfo`s pkgName"); return false; } // write int if (!parcel.WriteInt32(reminderId_)) { - REMINDER_LOGE("Failed to write reminderId"); + ANSR_LOGE("Failed to write reminderId"); return false; } if (!parcel.WriteInt32(notificationId_)) { - REMINDER_LOGE("Failed to write notificationId"); + ANSR_LOGE("Failed to write notificationId"); return false; } if (!parcel.WriteUint64(triggerTimeInMilli_)) { - REMINDER_LOGE("Failed to write triggerTimeInMilli"); + ANSR_LOGE("Failed to write triggerTimeInMilli"); return false; } // write enum if (!parcel.WriteUint8(static_cast(reminderType_))) { - REMINDER_LOGE("Failed to write reminder type"); + ANSR_LOGE("Failed to write reminder type"); return false; } if (!parcel.WriteInt32(static_cast(slotType_))) { - REMINDER_LOGE("Failed to write slot type"); + ANSR_LOGE("Failed to write slot type"); return false; } // write map int32_t buttonMapSize = static_cast(actionButtonMap_.size()); if (!parcel.WriteInt32(buttonMapSize)) { - REMINDER_LOGE("Failed to write action button size"); + 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))) { - REMINDER_LOGE("Failed to write action button type"); + ANSR_LOGE("Failed to write action button type"); return false; } if (!parcel.WriteString(static_cast(it->second.title))) { - REMINDER_LOGE("Failed to write action button title"); + ANSR_LOGE("Failed to write action button title"); return false; } } @@ -430,7 +432,7 @@ bool ReminderRequest::Marshalling(Parcel &parcel) const ReminderRequest *ReminderRequest::Unmarshalling(Parcel &parcel) { auto objptr = new ReminderRequest(); - if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -442,54 +444,54 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) { // read string if (!parcel.ReadString(content_)) { - REMINDER_LOGE("Failed to read content"); + ANSR_LOGE("Failed to read content"); return false; } if (!parcel.ReadString(expiredContent_)) { - REMINDER_LOGE("to read expiredContent"); + ANSR_LOGE("to read expiredContent"); return false; } if (!parcel.ReadString(title_)) { - REMINDER_LOGE("Failed to read title"); + ANSR_LOGE("Failed to read title"); return false; } if (!parcel.ReadString(wantAgentInfo_->abilityName)) { - REMINDER_LOGE("Failed to read wantAgentInfo`s abilityName"); + ANSR_LOGE("Failed to read wantAgentInfo`s abilityName"); return false; } if (!parcel.ReadString(wantAgentInfo_->pkgName)) { - REMINDER_LOGE("Failed to read wantAgentInfo`s pkgName"); + ANSR_LOGE("Failed to read wantAgentInfo`s pkgName"); return false; } // read int int32_t tempReminderId = -1; if (!parcel.ReadInt32(tempReminderId)) { - REMINDER_LOGE("Failed to read tempReminderId"); + ANSR_LOGE("Failed to read tempReminderId"); return false; } reminderId_ = tempReminderId == -1 ? reminderId_ : tempReminderId; if (!parcel.ReadInt32(notificationId_)) { - REMINDER_LOGE("Failed to read notificationId"); + ANSR_LOGE("Failed to read notificationId"); return false; } if (!parcel.ReadUint64(triggerTimeInMilli_)) { - REMINDER_LOGE("Failed to read triggerTimeInMilli"); + ANSR_LOGE("Failed to read triggerTimeInMilli"); return false; } // read enum uint8_t reminderType = static_cast(ReminderType::INVALID); if (!parcel.ReadUint8(reminderType)) { - REMINDER_LOGE("Failed to read 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)) { - REMINDER_LOGE("Failed to read slotType"); + ANSR_LOGE("Failed to read slotType"); return false; } slotType_ = static_cast(slotType); @@ -497,13 +499,13 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) // read map int32_t buttonMapSize = 0; if (!parcel.ReadInt32(buttonMapSize)) { - REMINDER_LOGE("Failed to read 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)) { - REMINDER_LOGE("Failed to read buttonType"); + ANSR_LOGE("Failed to read buttonType"); return false; } ActionButtonType type = static_cast(buttonType); @@ -519,7 +521,7 @@ bool ReminderRequest::ReadFromParcel(Parcel &parcel) void ReminderRequest::InitNotificationRequest() { - REMINDER_LOGI("Init notification"); + ANSR_LOGI("Init notification"); auto notificationNormalContent = std::make_shared(); notificationNormalContent->SetText(content_); notificationNormalContent->SetTitle(title_); @@ -554,7 +556,7 @@ void ReminderRequest::AddActionButtons() auto type = it->first; if (type == ActionButtonType::CLOSE) { want->SetAction(REMINDER_EVENT_CLOSE_ALERT); - REMINDER_LOGD("Add action button, type is close"); + ANSR_LOGD("Add action button, type is close"); } want->SetParam("REMINDER_ID", reminderId_); std::vector> wants; @@ -577,7 +579,6 @@ void ReminderRequest::AddActionButtons() void ReminderRequest::AddRemovalWantAgent() { - // todo add RemovalWantAgent int requestCode = 10; std::vector flags; flags.push_back(WantAgent::WantAgentConstant::Flags::UPDATE_PRESENT_FLAG); @@ -586,7 +587,6 @@ void ReminderRequest::AddRemovalWantAgent() want->SetParam(PARAM_REMINDER_ID, reminderId_); std::vector> wants; wants.push_back(want); - REMINDER_LOGD("~~1"); WantAgent::WantAgentInfo wantAgentInfo( requestCode, WantAgent::WantAgentConstant::OperationType::SEND_COMMON_EVENT, @@ -596,7 +596,6 @@ void ReminderRequest::AddRemovalWantAgent() ); std::shared_ptr wantAgent = WantAgent::WantAgentHelper::GetWantAgent(wantAgentInfo); notificationRequest_->SetRemovalWantAgent(wantAgent); - REMINDER_LOGD("~~2"); } void ReminderRequest::SetWantAgent() @@ -628,7 +627,7 @@ void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string f } else { state_ &= ~newState; } - REMINDER_LOGI("Switch the reminder(id=%{public}d) state, from %{public}s to %{public}s, called by %{public}s", + ANSR_LOGI("Switch the reminder(id=%{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()); } } diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index 1cfaf51..185be05 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -13,11 +13,8 @@ * limitations under the License. */ -#include -#include - -#include "ans_log_wrapper.h" #include "reminder_request_alarm.h" +#include "ans_log_wrapper.h" namespace OHOS { namespace Notification { @@ -29,8 +26,8 @@ const uint16_t ReminderRequestAlarm::SECONDS_PER_HOUR = 3600; const uint8_t ReminderRequestAlarm::MINUTES_PER_HOUR = 60; const int8_t ReminderRequestAlarm::INVALID_INT_VALUE = -1; -ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) -: ReminderRequest(ReminderRequest::ReminderType::ALARM) +ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) : + ReminderRequest(ReminderRequest::ReminderType::ALARM) { hour_ = hour; minute_ = minute; @@ -44,17 +41,17 @@ ReminderRequestAlarm::ReminderRequestAlarm(const ReminderRequestAlarm &other) : this->hour_ = other.hour_; this->minute_ = other.minute_; this->repeatDays_ = other.repeatDays_; - REMINDER_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, 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) { - REMINDER_LOGE("setted hour is not between [0, 24)"); + 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) { - REMINDER_LOGE("setted minute is not between [0, 60)"); + ANSR_LOGE("setted minute is not between [0, 60)"); throw std::invalid_argument("setted minute is not between [0, 60)"); } } @@ -65,7 +62,7 @@ void ReminderRequestAlarm::SetDaysOfWeek(bool set, std::vector daysOfWe return; } if (daysOfWeek.size() > DAYS_PER_WEEK) { - REMINDER_LOGE("The length of daysOfWeek should not larger than 7"); + 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) { @@ -88,7 +85,7 @@ uint64_t ReminderRequestAlarm::PreGetNextTriggerTimeIgnoreSnooze(bool forceToGet uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. struct tm *nowTime; nowTime = localtime(&now); @@ -99,11 +96,11 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const tar.tm_hour = hour_; tar.tm_min = minute_; tar.tm_sec = 0; - REMINDER_LOGD("Now: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + ANSR_LOGD("Now: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " "min=%{public}d, sec=%{public}d, week=%{public}d, tar_hour=%{public}d, tar_min=%{public}d", nowTime->tm_year, nowTime->tm_mon, nowTime->tm_mday, nowTime->tm_hour, nowTime->tm_min, nowTime->tm_sec, nowTime->tm_wday, hour_, minute_); - REMINDER_LOGD("Tar: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + ANSR_LOGD("Tar: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " "min=%{public}d, sec=%{public}d, week=%{public}d", tar.tm_year, tar.tm_mon, tar.tm_mday, tar.tm_hour, tar.tm_min, tar.tm_sec, tar.tm_wday); @@ -123,7 +120,7 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const } struct tm *test; test = localtime(&nextTriggerTime); - REMINDER_LOGI("NextTriggerTime: year=%{public}d, mon=%{public}d, day=%{public}d, hour=%{public}d, " + 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", test->tm_year, test->tm_mon, test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, test->tm_wday, nextTriggerTime); @@ -147,7 +144,7 @@ int8_t ReminderRequestAlarm::GetNextAlarm(const time_t now, const time_t target) break; } } - REMINDER_LOGI("NextDayInterval is %{public}d", dayCount); + ANSR_LOGI("NextDayInterval is %{public}d", dayCount); return dayCount; } @@ -197,17 +194,17 @@ bool ReminderRequestAlarm::OnTimeZoneChange() bool ReminderRequestAlarm::UpdateNextReminder() { if (repeatDays_ == 0) { - REMINDER_LOGD("Set reminder to expired"); + ANSR_LOGD("Set reminder to expired"); SetExpired(true); return false; } uint64_t nextTriggerTime = GetNextTriggerTime(true); if (nextTriggerTime != 0) { - REMINDER_LOGI("Set next trigger time=%{public}llu", nextTriggerTime); + ANSR_LOGI("Set next trigger time=%{public}llu", nextTriggerTime); SetTriggerTimeInMilli(nextTriggerTime); return true; } else { - REMINDER_LOGD("Set reminder to expired"); + ANSR_LOGD("Set reminder to expired"); SetExpired(true); return false; } @@ -219,15 +216,15 @@ bool ReminderRequestAlarm::Marshalling(Parcel &parcel) const // write int if (!parcel.WriteUint8(hour_)) { - REMINDER_LOGE("Failed to write hour"); + ANSR_LOGE("Failed to write hour"); return false; } if (!parcel.WriteUint8(minute_)) { - REMINDER_LOGE("Failed to write minute"); + ANSR_LOGE("Failed to write minute"); return false; } if (!parcel.WriteUint8(repeatDays_)) { - REMINDER_LOGE("Failed to write daysOfWeek"); + ANSR_LOGE("Failed to write daysOfWeek"); return false; } @@ -237,9 +234,9 @@ bool ReminderRequestAlarm::Marshalling(Parcel &parcel) const ReminderRequestAlarm *ReminderRequestAlarm::Unmarshalling(Parcel &parcel) { std::vector daysOfWeek; - REMINDER_LOGD("New alarm"); + ANSR_LOGD("New alarm"); auto objptr = new ReminderRequestAlarm(); - if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -252,18 +249,18 @@ bool ReminderRequestAlarm::ReadFromParcel(Parcel &parcel) // read int if (!parcel.ReadUint8(hour_)) { - REMINDER_LOGE("Failed to read hour"); + ANSR_LOGE("Failed to read hour"); return false; } if (!parcel.ReadUint8(minute_)) { - REMINDER_LOGE("Failed to read minute"); + ANSR_LOGE("Failed to read minute"); return false; } if (!parcel.ReadUint8(repeatDays_)) { - REMINDER_LOGE("Failed to read repeatDays"); + ANSR_LOGE("Failed to read repeatDays"); return false; } - REMINDER_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); + ANSR_LOGD("hour_=%{public}d, minute_=%{public}d, repeatDays_=%{public}d", hour_, minute_, repeatDays_); return true; } } diff --git a/frameworks/ans/native/src/reminder_request_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp index cb00579..8e44f16 100644 --- a/frameworks/ans/native/src/reminder_request_timer.cpp +++ b/frameworks/ans/native/src/reminder_request_timer.cpp @@ -14,21 +14,22 @@ */ #include -#include +#include #include "ans_log_wrapper.h" -#include "reminder_request_timer.h" #include "time_service_client.h" +#include "reminder_request_timer.h" + namespace OHOS { namespace Notification { -ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) -: ReminderRequest(ReminderRequest::ReminderType::TIMER) +ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) : + ReminderRequest(ReminderRequest::ReminderType::TIMER) { CheckParamsValid(countDownTimeInSeconds); countDownTimeInSeconds_ = countDownTimeInSeconds; time_t now; // unit is seconds. - time(&now); + (void)time(&now); ReminderRequest::SetTriggerTimeInMilli( (static_cast(now) + countDownTimeInSeconds_) * ReminderRequest::MILLI_SECONDS); sptr timer = MiscServices::TimeServiceClient::GetInstance(); @@ -48,7 +49,7 @@ uint64_t ReminderRequestTimer::GetInitInfo() const uint64_t ReminderRequestTimer::PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const { - REMINDER_LOGD("countdonw time not support PreGetNextTriggerTimeIgnoreSnooze"); + ANSR_LOGD("countdonw time not support PreGetNextTriggerTimeIgnoreSnooze"); return ReminderRequest::INVALID_LONG_VALUE; } @@ -66,7 +67,7 @@ bool ReminderRequestTimer::OnTimeZoneChange() bool ReminderRequestTimer::UpdateNextReminder() { - REMINDER_LOGD("countdonw time not support repeat reminder, no need to update next triggerTime"); + ANSR_LOGD("countdonw time not support repeat reminder, no need to update next triggerTime"); SetExpired(true); return false; } @@ -74,7 +75,7 @@ bool ReminderRequestTimer::UpdateNextReminder() void ReminderRequestTimer::CheckParamsValid(const uint64_t countDownTimeInSeconds) const { if (countDownTimeInSeconds == 0 || countDownTimeInSeconds >= (UINT64_MAX / ReminderRequest::MILLI_SECONDS)) { - REMINDER_LOGE("Illegal count down time, please check the description of the constructor"); + 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"); } } @@ -84,9 +85,9 @@ void ReminderRequestTimer::UpdateTimeInfo(const std::string description) if (IsExpired()) { return; } - REMINDER_LOGD("%{public}s, update countdown time trigger time", description.c_str()); + ANSR_LOGD("%{public}s, update countdown time trigger time", description.c_str()); time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. whenToChangeSysTime_ = static_cast(now) * MILLI_SECONDS; sptr timer = MiscServices::TimeServiceClient::GetInstance(); int64_t bootTime = timer->GetBootTimeMs(); @@ -100,11 +101,11 @@ bool ReminderRequestTimer::Marshalling(Parcel &parcel) const // write int if (!parcel.WriteUint64(firstRealTimeInMilliSeconds_)) { - REMINDER_LOGE("Failed to write firstRealTimeInMilliSeconds"); + ANSR_LOGE("Failed to write firstRealTimeInMilliSeconds"); return false; } if (!parcel.WriteUint64(countDownTimeInSeconds_)) { - REMINDER_LOGE("Failed to write countDownTimeInSeconds"); + ANSR_LOGE("Failed to write countDownTimeInSeconds"); return false; } return true; @@ -113,7 +114,7 @@ bool ReminderRequestTimer::Marshalling(Parcel &parcel) const ReminderRequestTimer *ReminderRequestTimer::Unmarshalling(Parcel &parcel) { auto objptr = new ReminderRequestTimer(); - if ((nullptr != objptr) && !objptr->ReadFromParcel(parcel)) { + if ((objptr != nullptr) && !objptr->ReadFromParcel(parcel)) { delete objptr; objptr = nullptr; } @@ -126,11 +127,11 @@ bool ReminderRequestTimer::ReadFromParcel(Parcel &parcel) // read int if (!parcel.ReadUint64(firstRealTimeInMilliSeconds_)) { - REMINDER_LOGE("Failed to read firstRealTimeInMilliSeconds"); + ANSR_LOGE("Failed to read firstRealTimeInMilliSeconds"); return false; } if (!parcel.ReadUint64(countDownTimeInSeconds_)) { - REMINDER_LOGE("Failed to read countDownTimeInSeconds"); + ANSR_LOGE("Failed to read countDownTimeInSeconds"); return false; } return true; diff --git a/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp index fff49ef..3e76090 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_alarm_test.cpp @@ -24,12 +24,13 @@ namespace OHOS { namespace Notification { class ReminderRequestAlarmTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){ + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() + { ReminderHelper::CancelAllReminders(); - }; + } }; /** @@ -44,7 +45,7 @@ HWTEST_F(ReminderRequestAlarmTest, initHour_00100, Function | SmallTest | Level1 auto rrc = std::make_shared(-1, 1, daysOfWeek); EXPECT_TRUE(false) << "hour < 0 should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("hour < 0 throw exception."); + ANSR_LOGI("hour < 0 throw exception."); } } @@ -60,7 +61,7 @@ HWTEST_F(ReminderRequestAlarmTest, initHour_00200, Function | SmallTest | Level1 auto rrc = std::make_shared(24, 1, daysOfWeek); EXPECT_TRUE(false) << "hour > 23 should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("hour > 23 throw exception."); + ANSR_LOGI("hour > 23 throw exception."); } } @@ -100,7 +101,7 @@ HWTEST_F(ReminderRequestAlarmTest, initHour_00400, Function | SmallTest | Level1 auto rrc = std::make_shared(1, -1, daysOfWeek); EXPECT_TRUE(false) << "minute < 0 should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("minute < 0 throw exception."); + ANSR_LOGI("minute < 0 throw exception."); } } @@ -116,7 +117,7 @@ HWTEST_F(ReminderRequestAlarmTest, initHour_00500, Function | SmallTest | Level1 auto rrc = std::make_shared(1, 60, daysOfWeek); EXPECT_TRUE(false) << "minute > 59 should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("minute > 59 throw exception."); + ANSR_LOGI("minute > 59 throw exception."); } } diff --git a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp index 0d37307..161cb30 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp @@ -24,12 +24,16 @@ namespace OHOS { namespace Notification { class ReminderRequestTimerTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){ + static void SetUpTestCase() + { ReminderHelper::CancelAllReminders(); - }; + } + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() + { + ReminderHelper::CancelAllReminders(); + } }; /** @@ -43,7 +47,7 @@ HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00100, Function | SmallTest auto rrc = std::make_shared(0); EXPECT_TRUE(false) << "countDownTime < 0 should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("countDownTime < 0 throw exception."); + ANSR_LOGI("countDownTime < 0 throw exception."); } } @@ -58,7 +62,7 @@ HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00200, Function | SmallTest auto rrc = std::make_shared(UINT64_MAX / 1000); EXPECT_TRUE(false) << "countDownTime >= (UINT64_MAX / 1000) should throw exception."; } catch (const std::invalid_argument &e) { - REMINDER_LOGI("countDownTime > (UINT64_MAX / 1000) throw exception."); + ANSR_LOGI("countDownTime > (UINT64_MAX / 1000) throw exception."); } } diff --git a/interfaces/innerkits/ans/native/include/reminder_request.h b/interfaces/innerkits/ans/native/include/reminder_request.h index 529bdca..f20b4a0 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request.h +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -404,9 +404,10 @@ public: protected: ReminderRequest(); explicit ReminderRequest(ReminderType reminderType); - virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const { + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const + { return INVALID_LONG_VALUE; - }; + } private: void AddActionButtons(); diff --git a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h index 686bb14..1c6f50c 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h @@ -48,7 +48,7 @@ public: */ explicit ReminderRequestAlarm(const ReminderRequestAlarm &other); ReminderRequestAlarm& operator = (const ReminderRequestAlarm &other); - ~ReminderRequestAlarm(){}; + ~ReminderRequestAlarm() {}; /** * Obtains the repeat days vector. @@ -148,7 +148,6 @@ private: uint8_t minute_ = {0}; uint8_t repeatDays_ = {0}; }; - } // namespace Notification } // namespace OHOS diff --git a/interfaces/innerkits/ans/native/include/reminder_request_timer.h b/interfaces/innerkits/ans/native/include/reminder_request_timer.h index 1542d8b..0370550 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_timer.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -40,7 +40,7 @@ public: */ explicit ReminderRequestTimer(const ReminderRequestTimer &other); ReminderRequestTimer& operator = (const ReminderRequestTimer &other); - ~ReminderRequestTimer(){}; + ~ReminderRequestTimer() {}; uint64_t GetInitInfo() const; virtual bool OnDateTimeChange() override; @@ -65,14 +65,13 @@ protected: virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const override; private: - ReminderRequestTimer(){}; + 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/kits/napi/ans/include/reminder/publish.h b/interfaces/kits/napi/ans/include/reminder/publish.h index 7252a45..bb31247 100644 --- a/interfaces/kits/napi/ans/include/reminder/publish.h +++ b/interfaces/kits/napi/ans/include/reminder/publish.h @@ -15,13 +15,13 @@ #ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_PUBLISH_H #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_REMINDER_PUBLISH_H -#include "reminder/common.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 @@ -30,7 +30,7 @@ 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 @@ -39,7 +39,7 @@ 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 @@ -48,7 +48,7 @@ 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 diff --git a/interfaces/kits/napi/ans/include/reminder/common.h b/interfaces/kits/napi/ans/include/reminder/reminder_common.h similarity index 96% rename from interfaces/kits/napi/ans/include/reminder/common.h rename to interfaces/kits/napi/ans/include/reminder/reminder_common.h index 3de9524..9d0eaa8 100644 --- a/interfaces/kits/napi/ans/include/reminder/common.h +++ b/interfaces/kits/napi/ans/include/reminder/reminder_common.h @@ -84,6 +84,9 @@ private: static napi_value CreateReminderAlarm( const napi_env &env, const napi_value &value, std::shared_ptr& reminder); + + static napi_value ParseDaysOfWeek( + const napi_env &env, const napi_value &value, std::vector &daysOfWeek); }; } // namespace OHOS } // namespace ReminderAgentNapi diff --git a/interfaces/kits/napi/ans/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn index eaba4fa..ca0f48b 100644 --- a/interfaces/kits/napi/ans/src/reminder/BUILD.gn +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -49,7 +49,7 @@ ohos_shared_library("reminderagent") { "../common.cpp", "../slot.cpp", "native_module.cpp", - "common.cpp", + "reminder_common.cpp", "publish.cpp", ] diff --git a/interfaces/kits/napi/ans/src/reminder/native_module.cpp b/interfaces/kits/napi/ans/src/reminder/native_module.cpp index 8b0223d..386a92f 100644 --- a/interfaces/kits/napi/ans/src/reminder/native_module.cpp +++ b/interfaces/kits/napi/ans/src/reminder/native_module.cpp @@ -15,16 +15,17 @@ #include "napi/native_api.h" #include "napi/native_node_api.h" -#include "reminder/native_module.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) { - REMINDER_LOGI("ReminderAgentInit start"); + ANSR_LOGI("ReminderAgentInit start"); napi_property_descriptor desc[] = { DECLARE_NAPI_FUNCTION("cancelReminder", CancelReminder), DECLARE_NAPI_FUNCTION("cancelAllReminders", CancelAllReminders), @@ -39,7 +40,7 @@ napi_value ReminderAgentInit(napi_env env, napi_value exports) napi_value ConstantInit(napi_env env, napi_value exports) { - REMINDER_LOGI("ConstantInit start"); + ANSR_LOGI("ConstantInit start"); napi_value objReminderType = nullptr; napi_create_object(env, &objReminderType); @@ -97,6 +98,5 @@ 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 index 8e8a2c3..431f736 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -15,10 +15,11 @@ #include "ans_log_wrapper.h" #include "common.h" -#include "reminder/publish.h" #include "reminder_request_alarm.h" #include "reminder_request_timer.h" +#include "reminder/publish.h" + namespace OHOS { namespace ReminderAgentNapi { static const int32_t PUBLISH_PARAM_LEN = 2; @@ -46,7 +47,7 @@ napi_value GetCallback(const napi_env &env, const napi_value &value, Parameters napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); if (valuetype != napi_function) { - REMINDER_LOGE("Wrong argument type. Function expected."); + ANSR_LOGE("Wrong argument type. Function expected."); return nullptr; } napi_create_reference(env, value, 1, ¶ms.callback); @@ -71,20 +72,20 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, 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) { - REMINDER_LOGE("Wrong number of arguments"); + ANSR_LOGE("Wrong number of arguments"); return nullptr; } // argv[0] : reminderRequest if (ReminderCommon::GetReminderRequest(env, argv[0], params.reminder) == nullptr) { - REMINDER_LOGE("[reminderAgent]CreateReminder returns nullptr"); + ANSR_LOGE("[reminderAgent]CreateReminder returns nullptr"); return nullptr; } // argv[1]: callback if (argc == PUBLISH_PARAM_LEN) { if (GetCallback(env, argv[1], params) == nullptr) { - REMINDER_LOGE("[reminderAgent]GetCallbak returns nullptr"); + ANSR_LOGE("[reminderAgent]GetCallbak returns nullptr"); return nullptr; } } @@ -93,23 +94,23 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) { - REMINDER_LOGI("ParseCanCelParameter"); + 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) { - REMINDER_LOGE("Wrong number of arguments"); + ANSR_LOGE("Wrong number of arguments"); return nullptr; } // argv[0]: reminder id int32_t reminderId = -1; if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId)) { - REMINDER_LOGE("Param id of cancels Reminder should be a number."); + ANSR_LOGE("Param id of cancels Reminder should be a number."); return nullptr; } if (reminderId < 0) { - REMINDER_LOGE("Param id of cancels Reminder is illegal."); + ANSR_LOGE("Param id of cancels Reminder is illegal."); return nullptr; } params.reminderId = reminderId; @@ -117,7 +118,7 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i // argv[1]: callback if (argc >= CANCEL_PARAM_LEN) { if (GetCallback(env, argv[1], params) == nullptr) { - REMINDER_LOGE("GetCallbak is nullptr"); + ANSR_LOGE("GetCallbak is nullptr"); return nullptr; } } @@ -126,19 +127,19 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info &info, Parameters ¶ms) { - REMINDER_LOGI("ParseCanCelAllParameter"); + 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) { - REMINDER_LOGE("Wrong number of arguments"); + ANSR_LOGE("Wrong number of arguments"); return nullptr; } // argv[0]: callback if (argc == CANCEL_ALL_PARAM_LEN) { if (GetCallback(env, argv[0], params) == nullptr) { - REMINDER_LOGE("getCallbak is nullptr"); + ANSR_LOGE("getCallbak is nullptr"); return nullptr; } } @@ -151,22 +152,23 @@ napi_value ParseGetValidParameter(const napi_env &env, const napi_callback_info 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) { - REMINDER_LOGE("Wrong number of arguments"); + ANSR_LOGE("Wrong number of arguments"); return nullptr; } // argv[0]: callback if (argc == GET_VALID_PARAM_LEN) { if (GetCallback(env, argv[0], params) == nullptr) { - REMINDER_LOGI("getCallbak is nullptr"); + ANSR_LOGI("getCallbak is nullptr"); return nullptr; } } return NotificationNapi::Common::NapiGetNull(env); } -napi_value CancelReminder(napi_env env, napi_callback_info info) { - REMINDER_LOGI("Cancel reminder"); +napi_value CancelReminder(napi_env env, napi_callback_info info) +{ + ANSR_LOGI("Cancel reminder"); // param Parameters params; @@ -191,12 +193,12 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) { nullptr, resourceName, [](napi_env env, void *data) { - REMINDER_LOGI("Cancel napi_create_async_work start"); + 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) { - REMINDER_LOGI("Cancel napi_create_async_work complete start"); + ANSR_LOGI("Cancel napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); @@ -208,7 +210,7 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) { delete asynccallbackinfo; asynccallbackinfo = nullptr; } - REMINDER_LOGI("Cancel napi_create_async_work complete end"); + ANSR_LOGI("Cancel napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -223,7 +225,7 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) { napi_value CancelAllReminders(napi_env env, napi_callback_info info) { - REMINDER_LOGI("Cancel all reminder"); + ANSR_LOGI("Cancel all reminder"); // param Parameters params; @@ -247,12 +249,12 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - REMINDER_LOGI("CancelAll napi_create_async_work start"); + 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) { - REMINDER_LOGD("CancelAll napi_create_async_work complete start"); + ANSR_LOGD("CancelAll napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, NotificationNapi::Common::NapiGetNull(env)); @@ -264,7 +266,7 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) delete asynccallbackinfo; asynccallbackinfo = nullptr; } - REMINDER_LOGD("CancelAll napi_create_async_work complete end"); + ANSR_LOGD("CancelAll napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -289,7 +291,7 @@ void ParseReminder( break; } case ReminderRequest::ReminderType::ALARM: { - REMINDER_LOGD("Parse alarm info"); + ANSR_LOGD("Parse alarm info"); // hour ReminderRequestAlarm& alarm = (ReminderRequestAlarm&)reminder; @@ -312,7 +314,7 @@ void ParseReminder( count++; } } - REMINDER_LOGD("Parse alarm info end"); + ANSR_LOGD("Parse alarm info end"); break; } default: { @@ -332,7 +334,6 @@ void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_val 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); @@ -365,7 +366,7 @@ void ParseWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value & napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi_value &result) { - REMINDER_LOGI("enter"); + ANSR_LOGI("enter"); napi_value value = nullptr; napi_create_string_utf8(env, reminder.Dump().c_str(), NAPI_AUTO_LENGTH, &value); @@ -414,24 +415,24 @@ void GetValidRemindersInner(napi_env env, std::vector>& va napi_create_array(env, &arr); for (auto reminder : validReminders) { if (reminder == nullptr) { - REMINDER_LOGE("reminder is null"); + ANSR_LOGE("reminder is null"); continue; } napi_value result = nullptr; napi_create_object(env, &result); if (!SetValidReminder(env, *reminder, result)) { - REMINDER_LOGW("Set reminder object failed"); + ANSR_LOGW("Set reminder object failed"); continue; } napi_set_element(env, arr, count, result); count++; } - REMINDER_LOGI("GetValid reminders count = %{public}d", count); + ANSR_LOGI("GetValid reminders count = %{public}d", count); } napi_value GetValidReminders(napi_env env, napi_callback_info info) { - REMINDER_LOGI("Get valid reminders"); + ANSR_LOGI("Get valid reminders"); // param Parameters params; @@ -455,7 +456,7 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - REMINDER_LOGI("GetValid reminders napi_create_async_work start"); + ANSR_LOGI("GetValid reminders napi_create_async_work start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; std::vector> validReminders; asynccallbackinfo->info.errorCode = ReminderHelper::GetValidReminders(validReminders); @@ -468,7 +469,6 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) asynccallbackinfo->result = arr; }, [](napi_env env, napi_status status, void *data) { - REMINDER_LOGI("GetValid reminders napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, asynccallbackinfo->result); @@ -480,7 +480,6 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) delete asynccallbackinfo; asynccallbackinfo = nullptr; } - REMINDER_LOGI("GetValid reminders napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -495,12 +494,12 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) napi_value PublishReminder(napi_env env, napi_callback_info info) { - REMINDER_LOGI("PublishReminder"); + ANSR_LOGI("PublishReminder"); // param Parameters params; if (ParseParameters(env, info, params) == nullptr) { - REMINDER_LOGE("Parse params error"); + ANSR_LOGE("Parse params error"); return NotificationNapi::Common::JSParaError(env, params.callback); } @@ -521,10 +520,10 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) nullptr, resourceName, [](napi_env env, void *data) { - REMINDER_LOGI("Publish napi_create_async_work start"); + ANSR_LOGI("Publish napi_create_async_work start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; asynccallbackinfo->info.errorCode = ReminderHelper::PublishReminder(*(asynccallbackinfo->reminder)); - REMINDER_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); + ANSR_LOGD("Return reminderId=%{public}d", asynccallbackinfo->reminder->GetReminderId()); // reminderId napi_value napiReminderId = nullptr; @@ -532,7 +531,7 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) asynccallbackinfo->result = napiReminderId; }, [](napi_env env, napi_status status, void *data) { - REMINDER_LOGI("Publish napi_create_async_work complete start"); + ANSR_LOGI("Publish napi_create_async_work complete start"); AsyncCallbackInfo *asynccallbackinfo = (AsyncCallbackInfo *)data; NotificationNapi::Common::ReturnCallbackPromise( env, asynccallbackinfo->info, asynccallbackinfo->result); @@ -544,7 +543,7 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) delete asynccallbackinfo; asynccallbackinfo = nullptr; } - REMINDER_LOGI("Publish napi_create_async_work complete end"); + ANSR_LOGI("Publish napi_create_async_work complete end"); }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); diff --git a/interfaces/kits/napi/ans/src/reminder/common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp similarity index 68% rename from interfaces/kits/napi/ans/src/reminder/common.cpp rename to interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index 86850ef..bc186d7 100644 --- a/interfaces/kits/napi/ans/src/reminder/common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -15,10 +15,11 @@ #include "ans_log_wrapper.h" #include "common.h" -#include "reminder/common.h" #include "reminder_request_alarm.h" #include "reminder_request_timer.h" +#include "reminder/reminder_common.h" + namespace OHOS { namespace ReminderAgentNapi { using namespace OHOS::Notification; @@ -29,7 +30,7 @@ napi_value ReminderCommon::GetReminderRequest( napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); if (valuetype != napi_object) { - REMINDER_LOGE("Wrong argument type. Object expected."); + ANSR_LOGE("Wrong argument type. Object expected."); return nullptr; } @@ -45,39 +46,39 @@ bool ReminderCommon::GenActionButtons( { char str[NotificationNapi::STR_MAX_SIZE] = {0}; napi_valuetype valuetype = napi_undefined; - napi_value actionButtons = nullptr; - if (GetObject(env, value, ReminderAgentNapi::ACTION_BUTTON, actionButtons)) { - bool isArray = false; - napi_is_array(env, actionButtons, &isArray); - if (!isArray) { - REMINDER_LOGE("Wrong argument type:%{public}s. array expected.", ACTION_BUTTON); + if (!GetObject(env, value, ReminderAgentNapi::ACTION_BUTTON, actionButtons)) { + return true; + } + bool isArray = false; + napi_is_array(env, actionButtons, &isArray); + if (!isArray) { + ANSR_LOGE("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_LOGE("Wrong element type:%{public}s. object 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) { - REMINDER_LOGE("Wrong element type:%{public}s. object expected.", ACTION_BUTTON); + 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)) { + if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE) { + ANSR_LOGE("Wrong argument type:%{public}s. buttonType not support.", 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)) { - if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE) { - REMINDER_LOGE("Wrong argument type:%{public}s. buttonType not support.", ACTION_BUTTON); - return false; - } - std::string title(str); - reminder->SetActionButton(title, static_cast(buttonType)); - REMINDER_LOGD("button title=%{public}s, type=%{public}d", title.c_str(), buttonType); - } + std::string title(str); + reminder->SetActionButton(title, static_cast(buttonType)); + ANSR_LOGD("button title=%{public}s, type=%{public}d", title.c_str(), buttonType); } } return true; @@ -89,7 +90,7 @@ void ReminderCommon::GenWantAgent( char str[NotificationNapi::STR_MAX_SIZE] = {0}; napi_value wantAgent = nullptr; if (GetObject(env, value, ReminderAgentNapi::WANT_AGENT, wantAgent)) { - std::shared_ptr wantAgentInfo(new ReminderRequest::WantAgentInfo()); + auto wantAgentInfo = std::make_shared(); if (GetStringUtf8(env, wantAgent, ReminderAgentNapi::WANT_AGENT_PKG, str, NotificationNapi::STR_MAX_SIZE)) { wantAgentInfo->pkgName = str; } @@ -109,7 +110,7 @@ napi_value ReminderCommon::GenReminder( // reminderType NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); if (!hasProperty) { - REMINDER_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); + ANSR_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); return nullptr; } napi_value result = nullptr; @@ -129,7 +130,7 @@ napi_value ReminderCommon::GenReminder( } if (reminder == nullptr) { - REMINDER_LOGE("Instance of reminder error."); + ANSR_LOGE("Instance of reminder error."); return nullptr; } @@ -189,7 +190,7 @@ bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value, napi_get_named_property(env, value, propertyName, &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); if (valuetype != napi_string) { - REMINDER_LOGE("Wrong argument type:%{public}s. string expected.", propertyName); + ANSR_LOGE("Wrong argument type:%{public}s. string expected.", propertyName); return false; } NAPI_CALL(env, napi_get_value_string_utf8(env, result, propertyVal, size - 1, &strLen)); @@ -236,9 +237,9 @@ bool ReminderCommon::GetPropertyValIfExist(const napi_env &env, const napi_value NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); if (valuetype != napi_number) { if (propertyName == nullptr) { - REMINDER_LOGE("Wrong argument type. number expected."); + ANSR_LOGE("Wrong argument type. number expected."); } else { - REMINDER_LOGE("Wrong argument type:%{public}s. number expected.", propertyName); + ANSR_LOGE("Wrong argument type:%{public}s. number expected.", propertyName); } return false; } @@ -258,7 +259,7 @@ bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value, napi_get_named_property(env, value, propertyName, &propertyVal); NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); if (valuetype != napi_object) { - REMINDER_LOGE("Wrong argument type:%{public}s. object expected.", propertyName); + ANSR_LOGE("Wrong argument type:%{public}s. object expected.", propertyName); return false; } return true; @@ -269,13 +270,13 @@ napi_value ReminderCommon::CreateReminderTimer( { int64_t propertyCountDownTime = 0; if (!GetInt64(env, value, ReminderAgentNapi::TIMER_COUNT_DOWN_TIME, propertyCountDownTime)) { - REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); + ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); return nullptr; } if (propertyCountDownTime <= 0 || propertyCountDownTime > static_cast((UINT64_MAX / ReminderRequest::MILLI_SECONDS))) { - REMINDER_LOGE("Property %{public}s must between (0, %{public}llu).", + ANSR_LOGE("Property %{public}s must between (0, %{public}llu).", ReminderAgentNapi::ALARM_MINUTE, (UINT64_MAX / ReminderRequest::MILLI_SECONDS)); return nullptr; } @@ -290,66 +291,75 @@ napi_value ReminderCommon::CreateReminderAlarm( // hour int32_t propertyHourVal = 0; if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal)) { - REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_HOUR); + ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_HOUR); return nullptr; } // minute int32_t propertyMinuteVal = 0; if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal)) { - REMINDER_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_MINUTE); + ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_MINUTE); return nullptr; } if (propertyHourVal < 0 || propertyHourVal > 23) { - REMINDER_LOGE("Property %{public}s must between [0, 23].", ReminderAgentNapi::ALARM_HOUR); + ANSR_LOGE("Property %{public}s must between [0, 23].", ReminderAgentNapi::ALARM_HOUR); return nullptr; } if (propertyMinuteVal < 0 || propertyMinuteVal > 59) { - REMINDER_LOGE("Property %{public}s must between [0, 59].", ReminderAgentNapi::ALARM_MINUTE); + ANSR_LOGE("Property %{public}s must between [0, 59].", ReminderAgentNapi::ALARM_MINUTE); return nullptr; } // daysOfWeek - napi_value result = nullptr; std::vector daysOfWeek; - if (GetObject(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { - if (result != nullptr) { // function line too long - bool isArray = false; - napi_is_array(env, result, &isArray); - if (!isArray) { - REMINDER_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + ParseDaysOfWeek(env, value, daysOfWeek); + reminder = std::make_shared( + static_cast(propertyHourVal), static_cast(propertyMinuteVal), daysOfWeek); + return NotificationNapi::Common::NapiGetNull(env); +} + +napi_value ReminderCommon::ParseDaysOfWeek( + const napi_env &env, const napi_value &value, std::vector &daysOfWeek) +{ + napi_value result = nullptr; + if (!GetObject(env, value, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { + return NotificationNapi::Common::NapiGetNull(env); + } + if (result != nullptr) { + bool isArray = false; + napi_is_array(env, result, &isArray); + if (!isArray) { + ANSR_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + return nullptr; + } + uint32_t length = 0; + napi_get_array_length(env, result, &length); + uint8_t maxDaysOfWeek = 7; + if (length > maxDaysOfWeek) { + ANSR_LOGE( + "The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + 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_LOGE("%{public}s's element is expected to be number.", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK); return nullptr; } - uint32_t length = 0; - napi_get_array_length(env, result, &length); - uint8_t maxDaysOfWeek = 7; - if (length > maxDaysOfWeek) { - REMINDER_LOGE("The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + napi_get_value_int32(env, repeatDayVal, &propertyDayVal); + if (propertyDayVal < 1 || propertyDayVal > maxDaysOfWeek) { + ANSR_LOGE("%{public}s's element must between [1, %{public}d].", + ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); 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) { - REMINDER_LOGE("%{public}s's element is expected to be number.", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK); - return nullptr; - } - napi_get_value_int32(env, repeatDayVal, &propertyDayVal); - if (propertyDayVal < 1 || propertyDayVal > maxDaysOfWeek) { - REMINDER_LOGE("%{public}s's element must between [1, %{public}d].", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); - return nullptr; - } - daysOfWeek.push_back(static_cast(propertyDayVal)); - } + daysOfWeek.push_back(static_cast(propertyDayVal)); } } - reminder = std::make_shared( - static_cast(propertyHourVal), static_cast(propertyMinuteVal), daysOfWeek); return NotificationNapi::Common::NapiGetNull(env); } } diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 049682b..8990973 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -25,11 +25,10 @@ namespace OHOS { namespace Notification { -class ReminderDataManager final -{ +class ReminderDataManager final { public: - ReminderDataManager(){}; - ~ReminderDataManager(){}; + ReminderDataManager() {}; + ~ReminderDataManager() {}; ReminderDataManager(ReminderDataManager &other) = delete; ReminderDataManager& operator = (const ReminderDataManager &other) = delete; diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h index 83b88f9..25a2079 100644 --- a/services/ans/include/reminder_event_manager.h +++ b/services/ans/include/reminder_event_manager.h @@ -23,19 +23,17 @@ namespace OHOS { namespace Notification { -class ReminderEventManager -{ +class ReminderEventManager { public: ReminderEventManager(std::shared_ptr &reminderDataManager); - virtual ~ReminderEventManager(){}; + 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 -{ +class ReminderEventSubscriber : public EventFwk::CommonEventSubscriber { public: ReminderEventSubscriber(const EventFwk::CommonEventSubscribeInfo &subscriberInfo, std::shared_ptr &reminderDataManager); @@ -47,5 +45,4 @@ private: }; } // 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 index 28179f8..c680cfe 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -17,16 +17,16 @@ #define BASE_NOTIFICATION_ANS_STANDARD_FRAMEWORKS_ANS_CORE_INCLUDE_REMINDER_TIMER_INFO_H #include "itimer_info.h" +#include "advanced_notification_service.h" #include "notification_request.h" #include "reminder_request.h" -#include "advanced_notification_service.h" namespace OHOS { namespace Notification { class ReminderTimerInfo : public MiscServices::ITimerInfo { public: - ReminderTimerInfo(){}; - virtual ~ReminderTimerInfo(){}; + ReminderTimerInfo() {}; + virtual ~ReminderTimerInfo() {}; ReminderTimerInfo(ReminderTimerInfo &other) = delete; ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index a5a8fb7..d0a6283 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -234,22 +234,22 @@ void AdvancedNotificationService::SaveNotificationInfo( { ErrCode result = PrepereNotificationRequest(request); if (result != ERR_OK) { - REMINDER_LOGE("SaveNotificationInfo fail"); + ANSR_LOGE("SaveNotificationInfo fail"); return; } bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - REMINDER_LOGE("SaveNotificationInfo fail."); + ANSR_LOGE("SaveNotificationInfo fail."); return; } - REMINDER_LOGI( + ANSR_LOGI( "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid()); } ErrCode AdvancedNotificationService::PublishSavedNotification( sptr &request, sptr &bundleOption) { - REMINDER_LOGI("PublishSavedNotification"); + ANSR_LOGI("PublishSavedNotification"); auto record = std::make_shared(); record->request = request; record->notification = new Notification(request); @@ -1442,7 +1442,7 @@ ErrCode AdvancedNotificationService::CancelContinuousTaskNotification(const std: ErrCode AdvancedNotificationService::PublishReminder(sptr &reminder) { - REMINDER_LOGI("Publish reminder"); + ANSR_LOGI("Publish reminder"); ReminderDataManager::GetInstance()->SetService(this); sptr notificationRequest = reminder->GetNotificationRequest(); sptr bundleOption = nullptr; @@ -1456,7 +1456,7 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) { - REMINDER_LOGI("Cancel Reminder"); + ANSR_LOGI("Cancel Reminder"); ReminderDataManager::GetInstance()->SetService(this); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { @@ -1468,7 +1468,7 @@ ErrCode AdvancedNotificationService::CancelReminder(const int32_t reminderId) ErrCode AdvancedNotificationService::CancelAllReminders() { - REMINDER_LOGI("Cancel all reminders"); + ANSR_LOGI("Cancel all reminders"); ReminderDataManager::GetInstance()->SetService(this); sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { @@ -1480,7 +1480,7 @@ ErrCode AdvancedNotificationService::CancelAllReminders() ErrCode AdvancedNotificationService::GetValidReminders(std::vector> &reminders) { - REMINDER_LOGI("GetValidReminders"); + ANSR_LOGI("GetValidReminders"); ReminderDataManager::GetInstance()->SetService(this); reminders.clear(); sptr bundleOption = GenerateBundleOption(); @@ -1488,7 +1488,7 @@ ErrCode AdvancedNotificationService::GetValidReminders(std::vectorGetValidReminders(bundleOption, reminders); - REMINDER_LOGD("Valid reminders size=%{public}d", reminders.size()); + ANSR_LOGD("Valid reminders size=%{public}d", reminders.size()); return ERR_OK; } diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 9be038e..61e5bf3 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -15,11 +15,12 @@ #include "ans_log_wrapper.h" #include "common_event_support.h" -#include "reminder_data_manager.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; @@ -45,11 +46,11 @@ void ReminderDataManager::CancelReminder( { sptr reminder = FindReminderRequestLocked(reminderId, bundleOption->GetBundleName()); if (reminder == nullptr) { - REMINDER_LOGW("Cancel reminder, not find the reminder"); + ANSR_LOGW("Cancel reminder, not find the reminder"); return; } if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { - REMINDER_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_); + ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_); StopTimerLocked(); } int32_t id = reminderId; @@ -61,16 +62,16 @@ void ReminderDataManager::CancelReminder( void ReminderDataManager::CancelNotification(sptr &reminder) const { if (!(reminder->IsShowing())) { - REMINDER_LOGD("No need to cancel notification"); + ANSR_LOGD("No need to cancel notification"); return; } sptr notification = reminder->GetNotificationRequest(); if (notification == nullptr) { - REMINDER_LOGW("Cancel notification fail"); + ANSR_LOGW("Cancel notification fail"); } else { - REMINDER_LOGD("Cancel notification"); + ANSR_LOGD("Cancel notification"); if (advancedNotificationService_ == nullptr) { - REMINDER_LOGE("Cancel notification fail"); + ANSR_LOGE("Cancel notification fail"); return; } advancedNotificationService_->Cancel(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL); @@ -81,8 +82,8 @@ bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bu { std::lock_guard lock(ReminderDataManager::MUTEX); if (totalCount_ >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_SYSTEM) { - REMINDER_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); + 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; @@ -92,7 +93,7 @@ bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bu } auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); if (mit == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Error occur when get bundle option, reminderId=%{public}d", (*it)->GetReminderId()); + ANSR_LOGE("Error occur when get bundle option, reminderId=%{public}d", (*it)->GetReminderId()); } else { if (mit->second->GetBundleName() == bundleName) { count++; @@ -100,8 +101,8 @@ bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bu } } if (count >= ReminderDataManager::MAX_NUM_REMINDER_LIMIT_APP) { - REMINDER_LOGW("The number of validate reminders exceeds the application upper limit:%{public}d, and new \ - reminder can not be published", MAX_NUM_REMINDER_LIMIT_SYSTEM); + 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_SYSTEM); return true; } return false; @@ -112,7 +113,7 @@ void ReminderDataManager::CancelAllReminders(const sptrsecond->GetBundleName() == bundleOption->GetBundleName()) { StopTimer(); @@ -122,11 +123,11 @@ void ReminderDataManager::CancelAllReminders(const sptrGetReminderId(); auto mit = notificationBundleOptionMap_.find(reminderId); if (mit == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); } else { if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { CancelNotification(*vit); - REMINDER_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); vit = reminderVector_.erase(vit); notificationBundleOptionMap_.erase(mit); totalCount_--; @@ -150,7 +151,7 @@ void ReminderDataManager::GetValidReminders( int32_t reminderId = (*it)->GetReminderId(); auto mit = notificationBundleOptionMap_.find(reminderId); if (mit == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); + ANSR_LOGE("Get bundle option occur error, reminderId=%{public}d", reminderId); } else { if (mit->second->GetBundleName() == bundleOption->GetBundleName()) { reminders.push_back(*it); @@ -177,7 +178,7 @@ sptr ReminderDataManager::FindReminderRequestLocked(const int32 return *it; } } - REMINDER_LOGD("Not find the reminder"); + ANSR_LOGD("Not find the reminder"); return nullptr; } @@ -191,11 +192,11 @@ sptr ReminderDataManager::FindReminderRequestLocked( } auto bundleOption = FindNotificationBundleOption(reminderId); if (bundleOption == nullptr) { - REMINDER_LOGW("Not find the reminder due to bundle info is null"); + ANSR_LOGW("Not find the reminder due to bundle info is null"); return nullptr; } if (bundleOption -> GetBundleName() != pkgName) { - REMINDER_LOGW("Not find the reminder due to package name not match"); + ANSR_LOGW("Not find the reminder due to package name not match"); return nullptr; } return reminder; @@ -226,11 +227,11 @@ void ReminderDataManager::CloseReminder(const int32_t &reminderId, bool cancelNo { sptr reminder = FindReminderRequestLocked(reminderId); if (reminder == nullptr) { - REMINDER_LOGW("Invilate reminder id: %{public}d", reminderId); + ANSR_LOGW("Invilate reminder id: %{public}d", reminderId); return; } if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { - REMINDER_LOGD("Stop active reminder due to CloseReminder"); + ANSR_LOGD("Stop active reminder due to CloseReminder"); StopTimerLocked(); } reminder->OnClose(true); @@ -252,14 +253,14 @@ std::shared_ptr ReminderDataManager::GetInstance() void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) { std::string typeInfo = type == TIME_ZONE_CHANGE ? "timeZone" : "dateTime"; - REMINDER_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); + ANSR_LOGI("Refresh all reminders due to %{public}s changed by user", typeInfo.c_str()); if (activeReminderId_ != -1) { - REMINDER_LOGD("Stop active reminder due to date/time or timeZone change"); + ANSR_LOGD("Stop active reminder due to date/time or timeZone change"); StopTimerLocked(); } std::vector> showImmediately = RefreshRemindersLocked(type); if (!showImmediately.empty()) { - REMINDER_LOGD("Refresh all reminders, show expired reminders immediately"); + ANSR_LOGD("Refresh all reminders, show expired reminders immediately"); HandleImmediatelyShow(showImmediately, true); } StartRecentReminder(); @@ -271,11 +272,11 @@ void ReminderDataManager::UpdateAndSaveReminderLocked( std::lock_guard lock(ReminderDataManager::MUTEX); reminder->InitReminderId(); int32_t reminderId = reminder->GetReminderId(); - REMINDER_LOGD("Containers(vector/map) add. reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(vector/map) add. reminderId=%{public}d", reminderId); auto ret = notificationBundleOptionMap_.insert( std::pair>(reminderId, bundleOption)); if (!ret.second) { - REMINDER_LOGE("Containers add to map error"); + ANSR_LOGE("Containers add to map error"); return; } reminderVector_.push_back(reminder); @@ -289,9 +290,9 @@ void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotifi void ReminderDataManager::ShowReminder(bool isSysTimeChanged) { - REMINDER_LOGD("ShowReminder"); + ANSR_LOGD("ShowReminder"); if (activeReminderId_ == -1) { - REMINDER_LOGE("Active reminder not exist"); + ANSR_LOGE("Active reminder not exist"); return; } sptr reminder = FindReminderRequestLocked(activeReminderId_); @@ -320,14 +321,14 @@ void ReminderDataManager::ShowDesignatedReminderLocked(sptr &re sptr bundleOption = FindNotificationBundleOption(reminderId); sptr notificationRequest = (*it)->GetNotificationRequest(); if (bundleOption == nullptr) { - REMINDER_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); + ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); continue; } if (advancedNotificationService_ == nullptr) { - REMINDER_LOGE("ShowReminder fail"); + ANSR_LOGE("ShowReminder fail"); (*it)->OnShow(isSysTimeChanged, false); } else { - REMINDER_LOGD("publish notification.(reminderId=%{public}d)", reminderId); + ANSR_LOGD("publish notification.(reminderId=%{public}d)", reminderId); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); advancedNotificationService_->PublishSavedNotification(notificationRequest, bundleOption); @@ -341,22 +342,22 @@ void ReminderDataManager::StartRecentReminder() { sptr reminder = GetRecentReminderLocked(); if (reminder == nullptr) { - REMINDER_LOGI("No reminder need to start"); + ANSR_LOGI("No reminder need to start"); return; } bool toStart = true; if (activeReminderId_ != -1) { if (activeReminderId_ != reminder->GetReminderId()) { - REMINDER_LOGI("Stop active reminder"); + ANSR_LOGI("Stop active reminder"); StopTimerLocked(); } else { - REMINDER_LOGI("Recent reminder has already run, no need to start again."); + ANSR_LOGI("Recent reminder has already run, no need to start again."); toStart = false; } } if (toStart) { - REMINDER_LOGI("Start recent reminder"); + ANSR_LOGI("Start recent reminder"); StartTimerLocked(reminder); } } @@ -364,10 +365,10 @@ void ReminderDataManager::StartRecentReminder() void ReminderDataManager::StopTimer() { if (timerId_ == 0) { - REMINDER_LOGD("Timer is not running"); + ANSR_LOGD("Timer is not running"); return; } - REMINDER_LOGD("Stop timer id=%{public}llu", timerId_); + ANSR_LOGD("Stop timer id=%{public}llu", timerId_); sptr timer = MiscServices::TimeServiceClient::GetInstance(); timer->StopTimer(timerId_); ResetStates(); @@ -381,7 +382,6 @@ void ReminderDataManager::StopTimerLocked() std::string ReminderDataManager::Dump() const { - REMINDER_LOGD("Enter"); std::lock_guard lock(ReminderDataManager::MUTEX); std::map>> bundleNameMap; for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { @@ -391,7 +391,7 @@ std::string ReminderDataManager::Dump() const int32_t reminderId = (*it)->GetReminderId(); auto mit = notificationBundleOptionMap_.find(reminderId); if (mit == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Dump get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + ANSR_LOGE("Dump get notificationBundleOption(reminderId=%{public}d) fail", reminderId); continue; } std::string bundleName = mit->second->GetBundleName(); @@ -436,22 +436,22 @@ sptr ReminderDataManager::GetRecentReminderLocked() sort(reminderVector_.begin(), reminderVector_.end(), cmp); for (auto reminder = reminderVector_.begin(); reminder != reminderVector_.end();) { if (!(*reminder)->IsExpired()) { - REMINDER_LOGD("GetRecentReminderLocked: %{public}s", (*reminder)->Dump().c_str()); + ANSR_LOGD("GetRecentReminderLocked: %{public}s", (*reminder)->Dump().c_str()); return *reminder; } if (!(*reminder)->CanRemove()) { - REMINDER_LOGD("Reminder has been expired: %{public}s", (*reminder)->Dump().c_str()); + ANSR_LOGD("Reminder has been expired: %{public}s", (*reminder)->Dump().c_str()); reminder++; continue; } int32_t reminderId = (*reminder)->GetReminderId(); - REMINDER_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); auto it = notificationBundleOptionMap_.find((*reminder)->GetReminderId()); if (it == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", + ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", (*reminder)->GetReminderId()); } else { - REMINDER_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); notificationBundleOptionMap_.erase(it); } reminder = reminderVector_.erase(reminder); @@ -467,7 +467,7 @@ std::vector> ReminderDataManager::GetSameBundleRemindersLo for (auto it = reminderVector_.begin(); it != reminderVector_.end(); ++it) { sptr bundleOption = FindNotificationBundleOption((*it)->GetReminderId()); if (bundleOption == nullptr) { - REMINDER_LOGW("GetSameBundleRemindersLocked get notificationBundleOption(reminderId=%{public}d) fail", + ANSR_LOGW("GetSameBundleRemindersLocked get notificationBundleOption(reminderId=%{public}d) fail", (*it)->GetReminderId()); continue; } @@ -478,7 +478,8 @@ std::vector> ReminderDataManager::GetSameBundleRemindersLo return reminders; } -void ReminderDataManager::HandleImmediatelyShow(std::vector> &showImmediately, bool isSysTimeChanged) +void ReminderDataManager::HandleImmediatelyShow( + std::vector> &showImmediately, bool isSysTimeChanged) { for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { ShowDesignatedReminderLocked((*it), isSysTimeChanged); @@ -505,7 +506,7 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrGetNotificationId(); - REMINDER_LOGD("HandleSameNotificationIdShowing notificationId=%{public}d", notificationId); + 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(); @@ -517,7 +518,7 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptr bundleOption = FindNotificationBundleOption(tmpId); if (bundleOption == nullptr) { - REMINDER_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); + ANSR_LOGW("Get notificationBundleOption(reminderId=%{public}d) fail", tmpId); continue; } if (notificationId == (*it)->GetNotificationId() && @@ -530,11 +531,11 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder, const std::string otherPkgName, const int otherUserId) { - REMINDER_LOGD("otherUserId=%{public}d, (currently, userId not support)", otherUserId); + ANSR_LOGD("otherUserId=%{public}d, (currently, userId not support)", otherUserId); int32_t reminderId = reminder->GetReminderId(); sptr bundleOption = FindNotificationBundleOption(reminderId); if (bundleOption == nullptr) { - REMINDER_LOGW("IsBelongToSameApp get notificationBundleOption(reminderId=%{public}d) fail", reminderId); + ANSR_LOGW("IsBelongToSameApp get notificationBundleOption(reminderId=%{public}d) fail", reminderId); return false; } if (bundleOption->GetBundleName() == otherPkgName) { @@ -561,10 +562,10 @@ 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()) { - REMINDER_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); it = reminderVector_.erase(it); totalCount_--; - REMINDER_LOGD("Remove reminder(id=%{public}d) success", reminderId); + ANSR_LOGD("Remove reminder(id=%{public}d) success", reminderId); break; } else { ++it; @@ -572,23 +573,23 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) } auto it = notificationBundleOptionMap_.find(reminderId); if (it == notificationBundleOptionMap_.end()) { - REMINDER_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); + ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); } else { - REMINDER_LOGD("Containers(map) remove: reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(map) remove: reminderId=%{public}d", reminderId); notificationBundleOptionMap_.erase(it); } } void ReminderDataManager::ResetStates() { - REMINDER_LOGD("ResetStates"); + ANSR_LOGD("ResetStates"); timerId_ = 0; activeReminderId_ = -1; } void ReminderDataManager::StartTimerLocked(sptr &reminderRequest) { - REMINDER_LOGD("Start timer: millSeconds=%{public}llu", reminderRequest->GetTriggerTimeInMilli()); + ANSR_LOGD("Start timer: millSeconds=%{public}llu", reminderRequest->GetTriggerTimeInMilli()); std::lock_guard lock(ReminderDataManager::MUTEX); sptr timer = MiscServices::TimeServiceClient::GetInstance(); timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo()); diff --git a/services/ans/src/reminder_event_manager.cpp b/services/ans/src/reminder_event_manager.cpp index d3d98b3..117c831 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -16,9 +16,10 @@ #include "ans_log_wrapper.h" #include "common_event_manager.h" #include "common_event_support.h" -#include "reminder_event_manager.h" #include "bundle_constants.h" +#include "reminder_event_manager.h" + using namespace OHOS::EventFwk; namespace OHOS { namespace Notification { @@ -40,9 +41,9 @@ void ReminderEventManager::init(std::shared_ptr &reminderDa CommonEventSubscribeInfo subscriberInfo(matchingSkills); auto subscriber = std::make_shared(subscriberInfo, reminderDataManager); if (CommonEventManager::SubscribeCommonEvent(subscriber)) { - REMINDER_LOGD("SubscribeCommonEvent ok"); + ANSR_LOGD("SubscribeCommonEvent ok"); } else { - REMINDER_LOGD("SubscribeCommonEvent fail"); + ANSR_LOGD("SubscribeCommonEvent fail"); } } @@ -57,7 +58,7 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw { Want want = data.GetWant(); std::string action = want.GetAction(); - REMINDER_LOGD("Recieved common event:%{public}s", action.c_str()); + ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { reminderDataManager_->ShowReminder(false); return; @@ -74,7 +75,7 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw OHOS::AppExecFwk::ElementName ele = want.GetElement(); std::string bundleName = ele.GetBundleName(); int uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); - REMINDER_LOGD("bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); + ANSR_LOGD("bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); sptr bundleOption = new NotificationBundleOption(bundleName, uid); reminderDataManager_->CancelAllReminders(bundleOption); return; diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp index a649651..3c7c39c 100644 --- a/services/ans/src/reminder_timer_info.cpp +++ b/services/ans/src/reminder_timer_info.cpp @@ -14,9 +14,10 @@ */ #include "ans_log_wrapper.h" -#include "reminder_timer_info.h" -#include "reminder_request.h" #include "common_event_manager.h" +#include "reminder_request.h" + +#include "reminder_timer_info.h" using namespace OHOS::EventFwk; namespace OHOS { @@ -43,7 +44,7 @@ void ReminderTimerInfo::SetWantAgent(std::shared_ptr Date: Mon, 27 Dec 2021 11:45:23 +0800 Subject: [PATCH 062/131] fix codeCheck Signed-off-by: derek Change-Id: Ib997eb93ac221cd9b82ea11fc618c10274fb50d4 --- frameworks/ans/native/src/reminder_request_alarm.cpp | 4 ++-- .../ans/native/test/unittest/reminder_request_test.cpp | 8 ++++---- .../innerkits/ans/native/include/reminder_request_alarm.h | 1 - services/ans/include/reminder_timer_info.h | 2 +- services/ans/src/advanced_notification_service.cpp | 1 - services/test/moduletest/BUILD.gn | 1 + 6 files changed, 8 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index 185be05..3561b3d 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -26,8 +26,8 @@ const uint16_t ReminderRequestAlarm::SECONDS_PER_HOUR = 3600; const uint8_t ReminderRequestAlarm::MINUTES_PER_HOUR = 60; const int8_t ReminderRequestAlarm::INVALID_INT_VALUE = -1; -ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) : - ReminderRequest(ReminderRequest::ReminderType::ALARM) +ReminderRequestAlarm::ReminderRequestAlarm(uint8_t hour, uint8_t minute, const std::vector daysOfWeek) + : ReminderRequest(ReminderRequest::ReminderType::ALARM) { hour_ = hour; minute_ = minute; diff --git a/frameworks/ans/native/test/unittest/reminder_request_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_test.cpp index f85933a..0be99c9 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_test.cpp @@ -27,10 +27,10 @@ public: class ReminderRequestTest : public testing::Test { public: - static void SetUpTestCase(){}; - static void TearDownTestCase(){}; - void SetUp(){}; - void TearDown(){}; + static void SetUpTestCase() {} + static void TearDownTestCase() {} + void SetUp() {} + void TearDown() {} static const uint8_t REMINDER_STATUS_SHOWING; }; diff --git a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h index 1c6f50c..e05550d 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h @@ -18,7 +18,6 @@ #include "reminder_request.h" -#include #include namespace OHOS { diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h index c680cfe..0bc1e89 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -16,8 +16,8 @@ #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 "itimer_info.h" #include "advanced_notification_service.h" +#include "itimer_info.h" #include "notification_request.h" #include "reminder_request.h" diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index d0a6283..2394ecb 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -31,7 +31,6 @@ #include "notification_slot_filter.h" #include "notification_subscriber_manager.h" #include "permission_filter.h" - #include "reminder_data_manager.h" namespace OHOS { diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 0440b8b..89f1657 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -21,6 +21,7 @@ ohos_moduletest("ans_module_test") { module_out_path = module_output_path include_dirs = [ "include", + "//base/miscservices/time/interfaces/innerkits/include", "//foundation/appexecfwk/standard/libs/libeventhandler/src", "//utils/native/base/include", "//utils/system/safwk/native/include", -- Gitee From 0c398cd0ca5953ee333b02cf9eebe9a8093f4a6c Mon Sep 17 00:00:00 2001 From: zhongjianfei Date: Sat, 18 Dec 2021 10:42:42 +0800 Subject: [PATCH 063/131] fixed cb581fc from https://gitee.com/zhongjianfei/notification_ans_standard/pulls/102 zhongjianfei@huawei.com Signed-off-by: zhongjianfei Change-Id: I7f2aa297e80e8d40836e7cdcf40310ef39b400ce --- interfaces/kits/napi/ans/BUILD.gn | 2 -- 1 file changed, 2 deletions(-) diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 66da342..2d7176e 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -61,8 +61,6 @@ 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", -- Gitee From c96407f7bde25e798f9f829919479bd20587eeb2 Mon Sep 17 00:00:00 2001 From: derek Date: Mon, 27 Dec 2021 20:40:48 +0800 Subject: [PATCH 064/131] fix codeCheck Signed-off-by: derek Change-Id: If3bb4e514b49f4148e8c79bfe5e8b603d8ee42af --- .../ans/core/include/ans_notification.h | 16 ++++++++-------- .../ans/native/src/reminder_request_timer.cpp | 4 ++-- .../ans/native/include/reminder_helper.h | 19 +++++++++---------- services/test/moduletest/BUILD.gn | 6 ++++++ 4 files changed, 25 insertions(+), 20 deletions(-) diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index 0c4e152..bb54802 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -641,31 +641,31 @@ public: /** * Publishes a scheduled reminder. - * + * * @param reminder Indicates a reminder. - * @return Returns publish result. + * @return Returns publish result. */ ErrCode PublishReminder(ReminderRequest &reminder); /** * Cancels a specified reminder. - * - * @return Returns cancel result. + * + * @return Returns cancel result. */ ErrCode CancelReminder(const int32_t reminderId); /** * Cancels all reminders of current third part application. - * - * @return Returns cancel result. + * + * @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. + * @return Returns get valid reminders result. */ ErrCode GetValidReminders(std::vector> &validReminders); diff --git a/frameworks/ans/native/src/reminder_request_timer.cpp b/frameworks/ans/native/src/reminder_request_timer.cpp index 8e44f16..00b975c 100644 --- a/frameworks/ans/native/src/reminder_request_timer.cpp +++ b/frameworks/ans/native/src/reminder_request_timer.cpp @@ -23,8 +23,8 @@ namespace OHOS { namespace Notification { -ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) : - ReminderRequest(ReminderRequest::ReminderType::TIMER) +ReminderRequestTimer::ReminderRequestTimer(uint64_t countDownTimeInSeconds) + : ReminderRequest(ReminderRequest::ReminderType::TIMER) { CheckParamsValid(countDownTimeInSeconds); countDownTimeInSeconds_ = countDownTimeInSeconds; diff --git a/interfaces/innerkits/ans/native/include/reminder_helper.h b/interfaces/innerkits/ans/native/include/reminder_helper.h index 3f4877e..0d7f34d 100644 --- a/interfaces/innerkits/ans/native/include/reminder_helper.h +++ b/interfaces/innerkits/ans/native/include/reminder_helper.h @@ -27,7 +27,7 @@ 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 @@ -41,19 +41,18 @@ public: * * @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. */ @@ -61,7 +60,7 @@ public: /** * Cancels all reminders of current third part application. - * + * * @return Returns cancel all reminders result. */ static ErrCode CancelAllReminders(); @@ -69,7 +68,7 @@ public: /** * 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. */ @@ -77,14 +76,14 @@ public: /** * 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. */ @@ -92,7 +91,7 @@ public: /** * 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. */ diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 89f1657..f33bd20 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -47,6 +47,9 @@ ohos_moduletest("ans_module_test") { "${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", @@ -66,11 +69,14 @@ ohos_moduletest("ans_module_test") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/miscservices/time/services:time_service", "//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/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//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", -- Gitee From 3a6b20c97a8d631ea9cd48d1e82423f45b592f0c Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Dec 2021 10:44:22 +0800 Subject: [PATCH 065/131] fix js interface of parsing reminderType Signed-off-by: derek Change-Id: I8add50f7a5c1316b65ef828ca50cb3f955855aae --- .../kits/napi/ans/src/reminder/publish.cpp | 28 +++++++++---------- .../napi/ans/src/reminder/reminder_common.cpp | 20 ++++--------- 2 files changed, 19 insertions(+), 29 deletions(-) diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 431f736..28d2761 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -47,7 +47,7 @@ napi_value GetCallback(const napi_env &env, const napi_value &value, Parameters napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); if (valuetype != napi_function) { - ANSR_LOGE("Wrong argument type. Function expected."); + ANSR_LOGW("Wrong argument type. Function expected."); return nullptr; } napi_create_reference(env, value, 1, ¶ms.callback); @@ -72,20 +72,20 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, 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_LOGE("Wrong number of arguments"); + ANSR_LOGW("Wrong number of arguments"); return nullptr; } // argv[0] : reminderRequest if (ReminderCommon::GetReminderRequest(env, argv[0], params.reminder) == nullptr) { - ANSR_LOGE("[reminderAgent]CreateReminder returns 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_LOGE("[reminderAgent]GetCallbak returns nullptr"); + ANSR_LOGW("[reminderAgent]GetCallbak returns nullptr"); return nullptr; } } @@ -99,18 +99,18 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i 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_LOGE("Wrong number of arguments"); + ANSR_LOGW("Wrong number of arguments"); return nullptr; } // argv[0]: reminder id int32_t reminderId = -1; if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId)) { - ANSR_LOGE("Param id of cancels Reminder should be a number."); + ANSR_LOGW("Param id of cancels Reminder should be a number."); return nullptr; } if (reminderId < 0) { - ANSR_LOGE("Param id of cancels Reminder is illegal."); + ANSR_LOGW("Param id of cancels Reminder is illegal."); return nullptr; } params.reminderId = reminderId; @@ -118,7 +118,7 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i // argv[1]: callback if (argc >= CANCEL_PARAM_LEN) { if (GetCallback(env, argv[1], params) == nullptr) { - ANSR_LOGE("GetCallbak is nullptr"); + ANSR_LOGW("GetCallbak is nullptr"); return nullptr; } } @@ -132,14 +132,14 @@ napi_value ParseCanCelAllParameter(const napi_env &env, const napi_callback_info 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_LOGE("Wrong number of arguments"); + 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_LOGE("getCallbak is nullptr"); + ANSR_LOGW("getCallbak is nullptr"); return nullptr; } } @@ -152,14 +152,14 @@ napi_value ParseGetValidParameter(const napi_env &env, const napi_callback_info 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_LOGE("Wrong number of arguments"); + 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_LOGI("getCallbak is nullptr"); + ANSR_LOGW("getCallbak is nullptr"); return nullptr; } } @@ -415,7 +415,7 @@ void GetValidRemindersInner(napi_env env, std::vector>& va napi_create_array(env, &arr); for (auto reminder : validReminders) { if (reminder == nullptr) { - ANSR_LOGE("reminder is null"); + ANSR_LOGW("reminder is null"); continue; } napi_value result = nullptr; @@ -499,7 +499,7 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) // param Parameters params; if (ParseParameters(env, info, params) == nullptr) { - ANSR_LOGE("Parse params error"); + ANSR_LOGW("Parse params error"); return NotificationNapi::Common::JSParaError(env, params.callback); } diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index bc186d7..c408b18 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -105,19 +105,11 @@ void ReminderCommon::GenWantAgent( napi_value ReminderCommon::GenReminder( const napi_env &env, const napi_value &value, std::shared_ptr& reminder) { - bool hasProperty = false; - // reminderType - NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); - if (!hasProperty) { - ANSR_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); - return nullptr; + int32_t propertyVal = -1; + if (!GetInt32(env, value, ReminderAgentNapi::REMINDER_TYPE, propertyVal)) { + ANSR_LOGW("Reminder type must be setted, please check the reminderType"); } - napi_value result = nullptr; - napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); - int32_t propertyVal = 0; - napi_get_value_int32(env, result, &propertyVal); - switch (ReminderRequest::ReminderType(propertyVal)) { case ReminderRequest::ReminderType::TIMER: CreateReminderTimer(env, value, reminder); @@ -126,14 +118,13 @@ napi_value ReminderCommon::GenReminder( CreateReminderAlarm(env, value, reminder); break; default: + ANSR_LOGW("Reminder type is not support."); break; } - if (reminder == nullptr) { - ANSR_LOGE("Instance of reminder error."); + ANSR_LOGW("Instance of reminder error."); return nullptr; } - char str[NotificationNapi::STR_MAX_SIZE] = {0}; // title @@ -173,7 +164,6 @@ napi_value ReminderCommon::GenReminder( if (!GenActionButtons(env, value, reminder)) { return nullptr; } - return NotificationNapi::Common::NapiGetNull(env); } -- Gitee From 10eb55e85fbe8f2163933beac3618a2eff5d96e8 Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Dec 2021 12:21:55 +0800 Subject: [PATCH 066/131] fix js interface of parsing reminder type and action button type Signed-off-by: derek Change-Id: Ia11eda3f6bd911dd2a356726af04a54afc94b6da --- .../napi/ans/src/reminder/reminder_common.cpp | 23 ++++++++++++++----- 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index c408b18..d306b2f 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -73,12 +73,15 @@ bool ReminderCommon::GenActionButtons( ReminderAgentNapi::ACTION_BUTTON_TITLE, str, NotificationNapi::STR_MAX_SIZE) && GetInt32(env, actionButton, ReminderAgentNapi::ACTION_BUTTON_TYPE, buttonType)) { if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE) { - ANSR_LOGE("Wrong argument type:%{public}s. buttonType not support.", ACTION_BUTTON); + 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; @@ -106,10 +109,18 @@ napi_value ReminderCommon::GenReminder( const napi_env &env, const napi_value &value, std::shared_ptr& reminder) { // reminderType - int32_t propertyVal = -1; - if (!GetInt32(env, value, ReminderAgentNapi::REMINDER_TYPE, propertyVal)) { - ANSR_LOGW("Reminder type must be setted, please check the reminderType"); + bool hasProperty = false; + + // reminderType + NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); + if (!hasProperty) { + ANSR_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); + return nullptr; } + napi_value result = nullptr; + napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); + int32_t propertyVal = -1; + napi_get_value_int32(env, result, &propertyVal); switch (ReminderRequest::ReminderType(propertyVal)) { case ReminderRequest::ReminderType::TIMER: CreateReminderTimer(env, value, reminder); @@ -227,9 +238,9 @@ bool ReminderCommon::GetPropertyValIfExist(const napi_env &env, const napi_value NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); if (valuetype != napi_number) { if (propertyName == nullptr) { - ANSR_LOGE("Wrong argument type. number expected."); + ANSR_LOGW("Wrong argument type. number expected."); } else { - ANSR_LOGE("Wrong argument type:%{public}s. number expected.", propertyName); + ANSR_LOGW("Wrong argument type:%{public}s, number expected.", propertyName); } return false; } -- Gitee From 0b9b49331d6b1d5abf4b8c39874dc35d5806fabe Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Dec 2021 16:17:46 +0800 Subject: [PATCH 067/131] fix hilog(zu, uint64) Signed-off-by: derek Change-Id: Ied9607cc8843033013de722ffeaa2ff866a647b0 --- frameworks/ans/core/src/ans_manager_proxy.cpp | 2 +- frameworks/ans/core/src/ans_manager_stub.cpp | 2 +- frameworks/ans/native/src/reminder_request.cpp | 2 +- frameworks/ans/native/src/reminder_request_alarm.cpp | 7 ++++--- interfaces/kits/napi/ans/src/reminder/reminder_common.cpp | 2 +- services/ans/src/advanced_notification_service.cpp | 2 +- services/ans/src/reminder_data_manager.cpp | 4 ++-- 7 files changed, 11 insertions(+), 10 deletions(-) diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 18d9c68..5c4dd03 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -2051,7 +2051,7 @@ ErrCode AnsManagerProxy::GetValidReminders(std::vector> &r if (result != ERR_OK) { ANSR_LOGE("[GetValidReminders] fail: ReadReminders ErrCode=%{public}d", result); } else { - ANSR_LOGD("[GetValidReminders], size=%{public}d", reminders.size()); + ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); } } return result; diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 16032b5..b635224 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -1323,7 +1323,7 @@ ErrCode AnsManagerStub::HandleGetValidReminders(MessageParcel &data, MessageParc std::vector> validReminders; ErrCode result = GetValidReminders(validReminders); - ANSR_LOGD("Write back size=%{public}d", validReminders.size()); + 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; diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index a3296a6..1d97e66 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -196,7 +196,7 @@ bool ReminderRequest::HandleTimeZoneChange( return false; } ANSR_LOGD("Handle timezone change, oldZoneTriggerTime:%{public}llu, newZoneTriggerTime:%{public}llu", - oldZoneTriggerTime, newZoneTriggerTime); + (unsigned long long)oldZoneTriggerTime, (unsigned long long)newZoneTriggerTime); bool showImmediately = false; if (optTriggerTime != INVALID_LONG_VALUE && oldZoneTriggerTime < newZoneTriggerTime) { // case1. timezone change to smaller diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index 3561b3d..79cd990 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -121,8 +121,9 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const struct tm *test; test = localtime(&nextTriggerTime); 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", test->tm_year, - test->tm_mon, test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, test->tm_wday, nextTriggerTime); + "min=%{public}d, sec=%{public}d, week=%{public}d, nextTriggerTime=%{public}lld", + test->tm_year, test->tm_mon, test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, + test->tm_wday, (long long)nextTriggerTime); if (static_cast(nextTriggerTime) <= 0) { return 0; @@ -200,7 +201,7 @@ bool ReminderRequestAlarm::UpdateNextReminder() } uint64_t nextTriggerTime = GetNextTriggerTime(true); if (nextTriggerTime != 0) { - ANSR_LOGI("Set next trigger time=%{public}llu", nextTriggerTime); + ANSR_LOGI("Set next trigger time=%{public}llu", (unsigned long long)nextTriggerTime); SetTriggerTimeInMilli(nextTriggerTime); return true; } else { diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index d306b2f..1f4dcec 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -278,7 +278,7 @@ napi_value ReminderCommon::CreateReminderTimer( if (propertyCountDownTime <= 0 || propertyCountDownTime > static_cast((UINT64_MAX / ReminderRequest::MILLI_SECONDS))) { ANSR_LOGE("Property %{public}s must between (0, %{public}llu).", - ReminderAgentNapi::ALARM_MINUTE, (UINT64_MAX / ReminderRequest::MILLI_SECONDS)); + ReminderAgentNapi::ALARM_MINUTE, (unsigned long long)(UINT64_MAX / ReminderRequest::MILLI_SECONDS)); return nullptr; } diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 2394ecb..37c4f54 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1487,7 +1487,7 @@ ErrCode AdvancedNotificationService::GetValidReminders(std::vectorGetValidReminders(bundleOption, reminders); - ANSR_LOGD("Valid reminders size=%{public}d", reminders.size()); + ANSR_LOGD("Valid reminders size=%{public}zu", reminders.size()); return ERR_OK; } diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 61e5bf3..2990a2c 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -368,7 +368,7 @@ void ReminderDataManager::StopTimer() ANSR_LOGD("Timer is not running"); return; } - ANSR_LOGD("Stop timer id=%{public}llu", timerId_); + ANSR_LOGD("Stop timer id=%{public}llu", (unsigned long long)timerId_); sptr timer = MiscServices::TimeServiceClient::GetInstance(); timer->StopTimer(timerId_); ResetStates(); @@ -589,7 +589,7 @@ void ReminderDataManager::ResetStates() void ReminderDataManager::StartTimerLocked(sptr &reminderRequest) { - ANSR_LOGD("Start timer: millSeconds=%{public}llu", reminderRequest->GetTriggerTimeInMilli()); + ANSR_LOGD("Start timer: millSeconds=%{public}llu", (unsigned long long)(reminderRequest->GetTriggerTimeInMilli())); std::lock_guard lock(ReminderDataManager::MUTEX); sptr timer = MiscServices::TimeServiceClient::GetInstance(); timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo()); -- Gitee From f93d06d787838f64dcd1cea5e23321142c3a36c8 Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Dec 2021 16:42:31 +0800 Subject: [PATCH 068/131] fix compile error Signed-off-by: derek Change-Id: I8a3f43aa980ffc295463bcd1ecca2e0103248883 --- interfaces/kits/napi/ans/src/reminder/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/interfaces/kits/napi/ans/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn index ca0f48b..4b94bd3 100644 --- a/interfaces/kits/napi/ans/src/reminder/BUILD.gn +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -63,7 +63,7 @@ ohos_shared_library("reminderagent") { "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common:napi_common", "//foundation/ace/napi:ace_napi", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", + "//foundation/multimedia/image_standard/interfaces/innerkits:image", "//third_party/jsoncpp:jsoncpp", "//third_party/libuv:uv_static", "//utils/native/base:utils", -- Gitee From 2c3b17e303fdf66793979b83c09fdf866d8cdeef Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 28 Dec 2021 17:30:03 +0800 Subject: [PATCH 069/131] fix gn format Signed-off-by: derek Change-Id: I906810578a5741a80ff77b2f7b62c1d48077a540 --- frameworks/ans/core/BUILD.gn | 2 +- frameworks/ans/native/test/unittest/BUILD.gn | 92 +++++++++---------- interfaces/BUILD.gn | 2 +- .../kits/napi/ans/src/reminder/BUILD.gn | 4 +- services/ans/BUILD.gn | 6 +- services/ans/test/unittest/BUILD.gn | 2 +- 6 files changed, 54 insertions(+), 54 deletions(-) diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 4f03215..e2ba429 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -70,8 +70,8 @@ ohos_shared_library("ans_core") { "${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_timer.cpp", "${frameworks_path}/ans/native/src/reminder_request_alarm.cpp", + "${frameworks_path}/ans/native/src/reminder_request_timer.cpp", ] configs = [ ":private_config" ] diff --git a/frameworks/ans/native/test/unittest/BUILD.gn b/frameworks/ans/native/test/unittest/BUILD.gn index 2b7d71c..573e116 100644 --- a/frameworks/ans/native/test/unittest/BUILD.gn +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -18,58 +18,58 @@ import("//build/test.gni") module_output_path = "ans_reminder/unittest" ohos_unittest("ans_reminder_unit_test") { - module_out_path = module_output_path + module_out_path = module_output_path - 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", - ] + 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", + ] - sources = [ - "${native_path}/test/unittest/reminder_request_test.cpp", - "${native_path}/test/unittest/reminder_request_alarm_test.cpp", - ] + sources = [ + "${native_path}/test/unittest/reminder_request_alarm_test.cpp", + "${native_path}/test/unittest/reminder_request_test.cpp", + ] - configs = [ "//utils/native/base:utils_config" ] + configs = [ "//utils/native/base:utils_config" ] - deps = [ - "${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", - ] + deps = [ + "${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", + ] - external_deps = [ - "aafwk_standard:want", - "appexecfwk_standard:appexecfwk_base", - "appexecfwk_standard:appexecfwk_core", - "appexecfwk_standard:libeventhandler", - "ces_standard:cesfwk_innerkits", - "hiviewdfx_hilog_native:libhilog", - "ipc:ipc_core", - "safwk:system_ability_fwk", - "samgr_standard:samgr_proxy", - ] + external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", + "appexecfwk_standard:libeventhandler", + "ces_standard:cesfwk_innerkits", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "safwk:system_ability_fwk", + "samgr_standard:samgr_proxy", + ] - subsystem_name = "notification" - part_name = "ans_standard" + subsystem_name = "notification" + part_name = "ans_standard" } group("unittest") { diff --git a/interfaces/BUILD.gn b/interfaces/BUILD.gn index 848eae1..d5d1732 100644 --- a/interfaces/BUILD.gn +++ b/interfaces/BUILD.gn @@ -14,7 +14,7 @@ group("interfaces_target") { deps = [ "kits/napi/ans:notification", - "kits/napi/wantagent:wantagent", "kits/napi/ans/src/reminder:reminderagent", + "kits/napi/wantagent:wantagent", ] } diff --git a/interfaces/kits/napi/ans/src/reminder/BUILD.gn b/interfaces/kits/napi/ans/src/reminder/BUILD.gn index 4b94bd3..19d5a8c 100644 --- a/interfaces/kits/napi/ans/src/reminder/BUILD.gn +++ b/interfaces/kits/napi/ans/src/reminder/BUILD.gn @@ -49,8 +49,8 @@ ohos_shared_library("reminderagent") { "../common.cpp", "../slot.cpp", "native_module.cpp", - "reminder_common.cpp", "publish.cpp", + "reminder_common.cpp", ] deps = [ @@ -78,4 +78,4 @@ ohos_shared_library("reminderagent") { relative_install_dir = "module" subsystem_name = "notification" part_name = "ans_standard" -} \ No newline at end of file +} diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index b45ae62..7261438 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -45,10 +45,10 @@ ohos_shared_library("libans") { "src/notification_slot_filter.cpp", "src/notification_subscriber_manager.cpp", "src/permission_filter.cpp", - "src/system_event_observer.cpp", - "src/reminder_timer_info.cpp", "src/reminder_data_manager.cpp", "src/reminder_event_manager.cpp", + "src/reminder_timer_info.cpp", + "src/system_event_observer.cpp", ] configs = [ @@ -60,12 +60,12 @@ ohos_shared_library("libans") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/miscservices/time/services:time_service", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", - "//base/miscservices/time/services:time_service", ] if (is_double_framework) { diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 508d221..8069034 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -74,10 +74,10 @@ ohos_unittest("ans_unit_test") { configs = [ "//utils/native/base:utils_config" ] deps = [ - "//base/miscservices/time/services:time_service", "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/miscservices/time/services:time_service", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", -- Gitee From b1cb5b07e8cf00cdf6c4049b3f5c42f901fd9e66 Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 29 Dec 2021 14:10:49 +0800 Subject: [PATCH 070/131] fix deliveryTime Signed-off-by: derek Change-Id: I8ee7bc86b707fa9aeaadac0dec184650d38d3b0c --- frameworks/ans/native/src/reminder_request.cpp | 12 ++++++++++++ .../innerkits/ans/native/include/reminder_request.h | 2 ++ services/ans/src/reminder_data_manager.cpp | 1 + 3 files changed, 15 insertions(+) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 1d97e66..0949005 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -346,6 +346,10 @@ void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std { ANSR_LOGI("UpdateNotification type=%{public}d", static_cast(type)); switch (type) { + case UpdateNotificationType::COMMON: { + UpdateNotificationCommon(); + break; + } case UpdateNotificationType::ACTION_BUTTON: { AddActionButtons(); break; @@ -528,6 +532,7 @@ void ReminderRequest::InitNotificationRequest() auto notificationContent = std::make_shared(notificationNormalContent); notificationRequest_ = new NotificationRequest(notificationId_); notificationRequest_->SetLabel(NOTIFICATION_LABEL); + notificationRequest_->SetShowDeliveryTime(true); notificationRequest_->SetSlotType(slotType_); notificationRequest_->SetContent(notificationContent); SetWantAgent(); // todo move to updateNotification @@ -630,5 +635,12 @@ void ReminderRequest::SetState(bool deSet, const uint8_t newState, std::string f ANSR_LOGI("Switch the reminder(id=%{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::UpdateNotificationCommon() +{ + time_t now; + (void)time(&now); // unit is seconds. + notificationRequest_->SetDeliveryTime(static_cast(now * MILLI_SECONDS)); +} } } \ 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 index f20b4a0..87445ac 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request.h +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -71,6 +71,7 @@ public: * @brief Supported notification update type. */ enum class UpdateNotificationType : uint8_t { + COMMON, ACTION_BUTTON, REMOVAL_WANT_AGENT, CONTENT @@ -418,6 +419,7 @@ private: void InitNotificationRequest(); void SetState(bool deSet, const uint8_t newState, std::string function); void SetWantAgent(); + void UpdateNotificationCommon(); static const uint8_t REMINDER_STATUS_INACTIVE; static const uint8_t REMINDER_STATUS_SHOWING; diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 2990a2c..5df280a 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -329,6 +329,7 @@ void ReminderDataManager::ShowDesignatedReminderLocked(sptr &re (*it)->OnShow(isSysTimeChanged, false); } else { ANSR_LOGD("publish notification.(reminderId=%{public}d)", reminderId); + (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); advancedNotificationService_->PublishSavedNotification(notificationRequest, bundleOption); -- Gitee From cc9b62c237767710b75a3b6040b3d9782f757628 Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 29 Dec 2021 14:16:04 +0800 Subject: [PATCH 071/131] fix review issue Signed-off-by: derek Change-Id: I94b994872b1f377fa4eab2ccecda5d22d271a57d --- frameworks/ans/core/src/ans_manager_proxy.cpp | 40 +++++++++---------- 1 file changed, 19 insertions(+), 21 deletions(-) diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 5c4dd03..9614eb9 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1970,15 +1970,14 @@ ErrCode AnsManagerProxy::PublishReminder(sptr &reminder) if (result != ERR_OK) { ANSR_LOGE("[PublishReminder] fail: transact ErrCode=%{public}d", result); return ERR_ANS_TRANSACT_FAILED; - } else { - 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()); } + 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; } @@ -2039,20 +2038,19 @@ ErrCode AnsManagerProxy::GetValidReminders(std::vector> &r 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 { - 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()); - } + ANSR_LOGD("[GetValidReminders], size=%{public}zu", reminders.size()); } return result; } -- Gitee From b7552fdce89bd337d053e9131068769ea14ab9b2 Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 30 Dec 2021 11:06:46 +0800 Subject: [PATCH 072/131] add tdd case Signed-off-by: derek Change-Id: I35ca7799fc1d3041612e1697109e9b9a0abd63d4 --- frameworks/ans/native/test/unittest/BUILD.gn | 1 + .../test/unittest/reminder_request_timer_test.cpp | 4 ++-- services/ans/src/reminder_data_manager.cpp | 14 +++++++------- 3 files changed, 10 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/native/test/unittest/BUILD.gn b/frameworks/ans/native/test/unittest/BUILD.gn index 573e116..734390a 100644 --- a/frameworks/ans/native/test/unittest/BUILD.gn +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -42,6 +42,7 @@ ohos_unittest("ans_reminder_unit_test") { sources = [ "${native_path}/test/unittest/reminder_request_alarm_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" ] diff --git a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp index 161cb30..3bd1e48 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_timer_test.cpp @@ -78,10 +78,10 @@ HWTEST_F(ReminderRequestTimerTest, initCountDownTime_00300, Function | SmallTest EXPECT_TRUE(rrc->GetInitInfo() == 1) << "countDownTime is not 1"; auto rrc2 = std::make_shared(10); - EXPECT_TRUE(rrc2->GetInitInfo() == 1) << "countDownTime is not 10"; + EXPECT_TRUE(rrc2->GetInitInfo() == 10) << "countDownTime is not 10"; auto rrc3 = std::make_shared(100); - EXPECT_TRUE(rrc3->GetInitInfo() == 1) << "countDownTime is not 1"; + EXPECT_TRUE(rrc3->GetInitInfo() == 100) << "countDownTime is not 1"; } } } \ No newline at end of file diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 5df280a..0cf683c 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -68,14 +68,14 @@ void ReminderDataManager::CancelNotification(sptr &reminder) co sptr notification = reminder->GetNotificationRequest(); if (notification == nullptr) { ANSR_LOGW("Cancel notification fail"); - } else { - ANSR_LOGD("Cancel notification"); - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("Cancel notification fail"); - return; - } - advancedNotificationService_->Cancel(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL); + return; + } + ANSR_LOGD("Cancel notification"); + if (advancedNotificationService_ == nullptr) { + ANSR_LOGE("Cancel notification fail"); + return; } + advancedNotificationService_->Cancel(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL); } bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bundleName) const -- Gitee From 8d8169df854378a2d1231b2b2cd5a516e2f4839f Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 30 Dec 2021 12:13:29 +0800 Subject: [PATCH 073/131] rebuild publishSavedNotification Signed-off-by: derek Change-Id: Ib8a335ab4d565f6b60182385a2d4087ce04b5220 --- .../include/advanced_notification_service.h | 7 +- .../ans/src/advanced_notification_service.cpp | 85 +++++-------------- services/ans/src/reminder_data_manager.cpp | 4 +- 3 files changed, 25 insertions(+), 71 deletions(-) diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 55b751e..8479421 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -118,9 +118,10 @@ public: // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); - void SaveNotificationInfo(sptr &request, sptr &bundleOption); - ErrCode PublishSavedNotification( - sptr &request, sptr &bundleOption); + ErrCode PrepareNotificationInfo( + const sptr &request, sptr &bundleOption); + ErrCode PublishPreparedNotification( + const sptr &request, const sptr &bundleOption); private: struct RecentInfo; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 37c4f54..1a1652f 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -228,34 +228,34 @@ sptr AdvancedNotificationService::GenerateValidBundleO return validBundleOption; } -void AdvancedNotificationService::SaveNotificationInfo( - sptr &request, sptr &bundleOption) +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) { - ANSR_LOGE("SaveNotificationInfo fail"); - return; + return result; } bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { - ANSR_LOGE("SaveNotificationInfo fail."); - return; + return ERR_ANS_INVALID_BUNDLE; } - ANSR_LOGI( + ANS_LOGI( "bundleName=%{public}s, uid=%{public}d", (bundleOption->GetBundleName()).c_str(), bundleOption->GetUid()); + return ERR_OK; } -ErrCode AdvancedNotificationService::PublishSavedNotification( - sptr &request, sptr &bundleOption) +ErrCode AdvancedNotificationService::PublishPreparedNotification( + const sptr &request, const sptr &bundleOption) { - ANSR_LOGI("PublishSavedNotification"); + ANS_LOGI("PublishPreparedNotification"); auto record = std::make_shared(); record->request = request; record->notification = new Notification(request); record->bundleOption = bundleOption; - ErrCode result = ERR_OK; - handler_->PostSyncTask(std::bind([&]() { result = AssignValidNotificationSlot(record); if (result != ERR_OK) { @@ -282,7 +282,6 @@ ErrCode AdvancedNotificationService::PublishSavedNotification( } UpdateInNotificationList(record); } - UpdateRecentNotification(record->notification, false, 0); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); @@ -293,59 +292,12 @@ ErrCode AdvancedNotificationService::PublishSavedNotification( ErrCode AdvancedNotificationService::Publish(const std::string &label, const sptr &request) { ANS_LOGD("%{public}s", __FUNCTION__); - - if ((request->GetSlotType() == NotificationConstant::SlotType::CUSTOM) && !IsSystemApp()) { - return ERR_ANS_NON_SYSTEM_APP; - } - - ErrCode result = PrepereNotificationRequest(request); + sptr bundleOption; + ErrCode result = PrepareNotificationInfo(request, bundleOption); if (result != ERR_OK) { return result; } - - sptr bundleOption = GenerateBundleOption(); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; - } - - std::shared_ptr record = std::make_shared(); - record->request = request; - record->notification = new Notification(request); - record->bundleOption = bundleOption; - - handler_->PostSyncTask(std::bind([&]() { - result = AssignValidNotificationSlot(record); - 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())) { - 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); - } - - UpdateRecentNotification(record->notification, false, 0); - sptr sortingMap = GenerateSortingMap(); - NotificationSubscriberManager::GetInstance()->NotifyConsumed(record->notification, sortingMap); - })); - - return result; + return PublishPreparedNotification(request, bundleOption); } bool AdvancedNotificationService::IsNotificationExists(const std::string &key) @@ -1445,9 +1397,10 @@ ErrCode AdvancedNotificationService::PublishReminder(sptr &remi ReminderDataManager::GetInstance()->SetService(this); sptr notificationRequest = reminder->GetNotificationRequest(); sptr bundleOption = nullptr; - SaveNotificationInfo(notificationRequest, bundleOption); - if (bundleOption == nullptr) { - return ERR_ANS_INVALID_BUNDLE; + ErrCode result = PrepareNotificationInfo(notificationRequest, bundleOption); + if (result != ERR_OK) { + ANSR_LOGW("PrepareNotificationInfo fail"); + return result; } ReminderDataManager::GetInstance()->PublishReminder(reminder, bundleOption); return ERR_OK; diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 0cf683c..c89e937 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -102,7 +102,7 @@ bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bu } 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_SYSTEM); + reminder can not be published", MAX_NUM_REMINDER_LIMIT_APP); return true; } return false; @@ -332,7 +332,7 @@ void ReminderDataManager::ShowDesignatedReminderLocked(sptr &re (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); - advancedNotificationService_->PublishSavedNotification(notificationRequest, bundleOption); + advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); (*it)->OnShow(isSysTimeChanged, true); HandleSameNotificationIdShowing((*it)); } -- Gitee From f99fce5979324844946f61737ca31a266dc78ddc Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 30 Dec 2021 16:01:14 +0800 Subject: [PATCH 074/131] fix slotType Signed-off-by: derek Change-Id: I3cb6ed143fcaf3f69189401537157b467f6caaee --- .../ans/include/reminder/reminder_common.h | 3 ++ .../kits/napi/ans/src/reminder/publish.cpp | 4 +- .../napi/ans/src/reminder/reminder_common.cpp | 40 ++++++++++++------- 3 files changed, 31 insertions(+), 16 deletions(-) diff --git a/interfaces/kits/napi/ans/include/reminder/reminder_common.h b/interfaces/kits/napi/ans/include/reminder/reminder_common.h index 9d0eaa8..0f9b9e0 100644 --- a/interfaces/kits/napi/ans/include/reminder/reminder_common.h +++ b/interfaces/kits/napi/ans/include/reminder/reminder_common.h @@ -67,6 +67,9 @@ public: const char* propertyName, napi_value& propertyVal); private: + static bool CreateReminder(const napi_env &env, const napi_value &value, + const int32_t &reminderType, std::shared_ptr& reminder); + static bool GetPropertyValIfExist(const napi_env &env, const napi_value &value, const char* propertyName, napi_value& propertyVal); diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 28d2761..699925f 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -397,7 +397,9 @@ napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi napi_set_named_property(env, result, NOTIFICATION_ID, value); // slotType - napi_create_int32(env, static_cast(reminder.GetSlotType()), &value); + 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 diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index 1f4dcec..7b60e47 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -105,13 +105,32 @@ void ReminderCommon::GenWantAgent( } } +bool ReminderCommon::CreateReminder(const napi_env &env, const napi_value &value, + const int32_t &reminderType, std::shared_ptr& reminder) +{ + switch (ReminderRequest::ReminderType(reminderType)) { + case ReminderRequest::ReminderType::TIMER: + CreateReminderTimer(env, value, reminder); + break; + case ReminderRequest::ReminderType::ALARM: + CreateReminderAlarm(env, value, reminder); + break; + default: + ANSR_LOGW("Reminder type is not support."); + 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; - - // reminderType NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); if (!hasProperty) { ANSR_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); @@ -121,19 +140,9 @@ napi_value ReminderCommon::GenReminder( napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); int32_t propertyVal = -1; napi_get_value_int32(env, result, &propertyVal); - switch (ReminderRequest::ReminderType(propertyVal)) { - case ReminderRequest::ReminderType::TIMER: - CreateReminderTimer(env, value, reminder); - break; - case ReminderRequest::ReminderType::ALARM: - CreateReminderAlarm(env, value, reminder); - break; - default: - ANSR_LOGW("Reminder type is not support."); - break; - } - if (reminder == nullptr) { - ANSR_LOGW("Instance of reminder error."); + + // createReminder + if (!CreateReminder(env, value, propertyVal, reminder)) { return nullptr; } char str[NotificationNapi::STR_MAX_SIZE] = {0}; @@ -163,6 +172,7 @@ napi_value ReminderCommon::GenReminder( if (GetInt32(env, value, ReminderAgentNapi::SLOT_TYPE, slotType)) { 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); -- Gitee From b9ea4b747070447fbe2c69d7ec8eb1c133005ab2 Mon Sep 17 00:00:00 2001 From: derek Date: Fri, 31 Dec 2021 11:00:19 +0800 Subject: [PATCH 075/131] fix codeCheck Signed-off-by: derek Change-Id: Id33739d327b4e365de62c87711f51884d13e3ae1 --- frameworks/ans/native/src/reminder_request.cpp | 3 +-- frameworks/ans/native/src/reminder_request_alarm.cpp | 6 ++---- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 0949005..1f7f16d 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -235,8 +235,7 @@ void ReminderRequest::OnShow(bool isSysTimeChanged, bool allowToNotify) bool ReminderRequest::OnTimeZoneChange() { time_t oldZoneTriggerTime = static_cast(triggerTimeInMilli_ / MILLI_SECONDS); - struct tm *oriTime; - oriTime = gmtime(&oldZoneTriggerTime); + struct tm *oriTime = gmtime(&oldZoneTriggerTime); time_t newZoneTriggerTime = mktime(oriTime); uint64_t nextTriggerTime = PreGetNextTriggerTimeIgnoreSnooze(false); return HandleTimeZoneChange(oldZoneTriggerTime, newZoneTriggerTime, nextTriggerTime); diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index 79cd990..7cbc226 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -86,8 +86,7 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const { time_t now; (void)time(&now); // unit is seconds. - struct tm *nowTime; - nowTime = localtime(&now); + struct tm *nowTime = localtime(&now); struct tm tar; tar.tm_year = nowTime->tm_year; @@ -118,8 +117,7 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const } else { nextTriggerTime = target + nextDayInterval * HOURS_PER_DAY * SECONDS_PER_HOUR; } - struct tm *test; - test = localtime(&nextTriggerTime); + struct tm *test = localtime(&nextTriggerTime); 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", test->tm_year, test->tm_mon, test->tm_mday, test->tm_hour, test->tm_min, test->tm_sec, -- Gitee From 8f3e8de17af3df0125b599ed2a72a62b5c35d1a9 Mon Sep 17 00:00:00 2001 From: zengsiyu Date: Fri, 31 Dec 2021 19:03:02 +0800 Subject: [PATCH 076/131] add hitrace external_deps Signed-off-by: zengsiyu Change-Id: I42cb284fda072b832de2d6d1f7ee44bb314d6c2b --- services/ans/test/unittest/BUILD.gn | 1 + services/test/moduletest/BUILD.gn | 1 + 2 files changed, 2 insertions(+) diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index b404f89..7fae3b4 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -83,6 +83,7 @@ ohos_unittest("ans_unit_test") { "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_innerkits", + "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 0440b8b..6491b66 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -83,6 +83,7 @@ ohos_moduletest("ans_module_test") { "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_innerkits", + "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", -- Gitee From d6fe3a59f2713cafafcaa9e0e1680ce113cb2953 Mon Sep 17 00:00:00 2001 From: dy_study Date: Tue, 4 Jan 2022 14:32:34 +0800 Subject: [PATCH 077/131] Update Notification ans code. Signed-off-by: dy_study --- frameworks/ans/core/BUILD.gn | 1 + .../core/common/include/ans_const_define.h | 3 + .../core/common/include/ans_inner_errors.h | 1 + .../ans/core/include/ans_manager_interface.h | 2 + .../ans/core/include/ans_manager_proxy.h | 1 + .../ans/core/include/ans_manager_stub.h | 2 + .../ans/core/include/ans_notification.h | 8 ++ frameworks/ans/core/src/ans_manager_proxy.cpp | 34 +++++ frameworks/ans/core/src/ans_manager_stub.cpp | 34 +++++ frameworks/ans/core/src/ans_notification.cpp | 10 ++ frameworks/ans/native/BUILD.gn | 1 + .../ans/native/src/notification_helper.cpp | 5 + .../src/notification_long_text_content.cpp | 3 +- .../native/src/notification_media_content.cpp | 3 +- .../src/notification_multiline_content.cpp | 4 +- .../ans/native/src/notification_request.cpp | 40 +++++- .../ans/native/src/notification_template.cpp | 93 +++++++++++++ frameworks/ans/test/moduletest/BUILD.gn | 1 + .../ans_innerkits_module_publish_test.cpp | 61 +++++++++ .../ans_innerkits_module_setting_test.cpp | 43 ++++++ .../wantagent/src/want_agent_helper.cpp | 3 +- .../ans/native/include/notification_helper.h | 10 +- .../ans/native/include/notification_request.h | 14 ++ .../native/include/notification_template.h | 95 +++++++++++++ interfaces/kits/js/@ohos.notification.d.ts | 23 ++++ .../notificationActionButton.d.ts | 2 + .../js/notification/notificationRequest.d.ts | 13 ++ .../notification/notificationSubscriber.d.ts | 6 + .../js/notification/notificationTemplate.d.ts | 35 +++++ interfaces/kits/napi/ans/BUILD.gn | 1 + .../kits/napi/ans/include/ans_template.h | 29 ++++ interfaces/kits/napi/ans/include/common.h | 9 ++ interfaces/kits/napi/ans/src/ans_template.cpp | 125 ++++++++++++++++++ interfaces/kits/napi/ans/src/common.cpp | 114 +++++++++++++++- interfaces/kits/napi/ans/src/init.cpp | 2 + interfaces/kits/napi/ans/src/subscribe.cpp | 3 +- .../kits/napi/wantagent/napi_want_agent.h | 17 ++- mgit.info | 1 + .../include/advanced_notification_service.h | 3 +- .../ans/include/notification_preferences.h | 1 + .../ans/src/advanced_notification_service.cpp | 11 ++ services/ans/src/notification_preferences.cpp | 34 +++++ services/ans/test/unittest/BUILD.gn | 1 + services/test/moduletest/BUILD.gn | 1 + test/BUILD.gn | 6 +- tools/dump/src/main.cpp | 2 +- 46 files changed, 888 insertions(+), 23 deletions(-) create mode 100644 frameworks/ans/native/src/notification_template.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_template.h create mode 100644 interfaces/kits/js/notification/notificationTemplate.d.ts create mode 100644 interfaces/kits/napi/ans/include/ans_template.h create mode 100644 interfaces/kits/napi/ans/src/ans_template.cpp create mode 100644 mgit.info diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index e2ba429..4b035ea 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -68,6 +68,7 @@ ohos_shared_library("ans_core") { "${frameworks_path}/ans/native/src/notification_subscribe_info.cpp", "${frameworks_path}/ans/native/src/notification_subscriber.cpp", "${frameworks_path}/ans/native/src/notification_user_input.cpp", + "${frameworks_path}/ans/native/src/notification_template.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", diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 8568a2b..e066999 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -37,6 +37,9 @@ constexpr uint32_t SYSTEM_SERVICE_UID = 1000; 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/external.json"); + } // 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 8e59ee7..63d35c8 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -69,6 +69,7 @@ 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, }; } // 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 9657c2b..c8d126c 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -118,6 +118,7 @@ public: 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 { @@ -181,6 +182,7 @@ protected: 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 d5bd993..0c58d0b 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -101,6 +101,7 @@ public: 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; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index 5366ed9..0316ea1 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -110,6 +110,7 @@ public: 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> @@ -175,6 +176,7 @@ private: 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 bb54802..7ea2f0d 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -629,6 +629,14 @@ public: */ 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 IsSupportTemplate(const std::string &templateName, bool &support); + /** * Reset ans manager proxy when OnRemoteDied called. */ diff --git a/frameworks/ans/core/src/ans_manager_proxy.cpp b/frameworks/ans/core/src/ans_manager_proxy.cpp index 9614eb9..e06b9e2 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -2151,5 +2151,39 @@ 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 b635224..5344287 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -210,6 +210,10 @@ const std::map> &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!"); @@ -1733,6 +1760,7 @@ ErrCode AnsManagerStub::CancelContinuousTaskNotification(const std::string &labe ANS_LOGW("AnsManagerStub::CancelContinuousTaskNotification called!"); return ERR_INVALID_OPERATION; } + ErrCode AnsManagerStub::PublishReminder(sptr &reminder) { ANS_LOGW("AnsManagerStub::PublishReminder called!"); @@ -1756,5 +1784,11 @@ 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 9f2214e..8087f3b 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -1099,5 +1099,15 @@ ErrCode AnsNotification::CheckImageSize(const NotificationRequest &request) 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); +} } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index f83983b..3a3de9d 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -63,6 +63,7 @@ ohos_shared_library("ans_innerkits") { "src/notification_subscribe_info.cpp", "src/notification_subscriber.cpp", "src/notification_user_input.cpp", + "src/notification_template.cpp", ] configs = [ diff --git a/frameworks/ans/native/src/notification_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 038e5f9..7f0bc36 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -331,5 +331,10 @@ ErrCode NotificationHelper::CancelContinuousTaskNotification(const std::string & { 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 fb30530..0e242fe 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -13,9 +13,10 @@ * limitations under the License. */ -#include "ans_log_wrapper.h" #include "notification_long_text_content.h" +#include "ans_log_wrapper.h" + namespace OHOS { namespace Notification { const std::size_t NotificationLongTextContent::MAX_LONGTEXT_LENGTH {1024}; diff --git a/frameworks/ans/native/src/notification_media_content.cpp b/frameworks/ans/native/src/notification_media_content.cpp index e1c303d..6c3862c 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -13,9 +13,10 @@ * limitations under the License. */ -#include "ans_log_wrapper.h" #include "notification_media_content.h" +#include "ans_log_wrapper.h" + namespace OHOS { namespace Notification { void NotificationMediaContent::SetAVToken(const std::shared_ptr &avToken) diff --git a/frameworks/ans/native/src/notification_multiline_content.cpp b/frameworks/ans/native/src/notification_multiline_content.cpp index 320c23b..299ac90 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -13,9 +13,11 @@ * limitations under the License. */ +#include "notification_multiline_content.h" + #include + #include "ans_log_wrapper.h" -#include "notification_multiline_content.h" namespace OHOS { namespace Notification { diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index bbf4e13..0bce17e 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -13,9 +13,10 @@ * limitations under the License. */ -#include "ans_log_wrapper.h" #include "notification_request.h" +#include "ans_log_wrapper.h" + namespace OHOS { namespace Notification { const std::string NotificationRequest::CLASSIFICATION_ALARM {"alarm"}; @@ -111,6 +112,8 @@ NotificationRequest::NotificationRequest(const NotificationRequest &other) this->actionButtons_ = other.actionButtons_; this->messageUsers_ = other.messageUsers_; this->userInputHistory_ = other.userInputHistory_; + + this->notificationTemplate_ = other.notificationTemplate_; } NotificationRequest &NotificationRequest::operator=(const NotificationRequest &other) @@ -171,6 +174,8 @@ NotificationRequest &NotificationRequest::operator=(const NotificationRequest &o this->messageUsers_ = other.messageUsers_; this->userInputHistory_ = other.userInputHistory_; + this->notificationTemplate_ = other.notificationTemplate_; + return *this; } @@ -754,6 +759,7 @@ std::string NotificationRequest::Dump() ", 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") + @@ -1089,6 +1095,19 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const 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; + } + } + return true; } @@ -1283,6 +1302,15 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) return false; } + valid = parcel.ReadBool(); + if (valid) { + notificationTemplate_ = std::shared_ptr(parcel.ReadParcelable()); + if (!notificationTemplate_) { + ANS_LOGE("Failed to read notificationTemplate"); + return false; + } + } + return true; } @@ -1294,5 +1322,15 @@ 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_; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_template.cpp b/frameworks/ans/native/src/notification_template.cpp new file mode 100644 index 0000000..6bc3b1e --- /dev/null +++ b/frameworks/ans/native/src/notification_template.cpp @@ -0,0 +1,93 @@ +/* + * 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; + } + + 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/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index f2edf40..7c5a0ec 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -173,6 +173,7 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "${frameworks_path}/wantagent:wantagent_innerkits", "${services_path}/ans:libans", "//foundation/aafwk/standard/frameworks/kits/ability/native:abilitykit_native", + "//foundation/aafwk/standard/interfaces/innerkits/base:base", "//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", 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 2c14f23..5f3f342 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -28,6 +28,8 @@ #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 { @@ -52,6 +54,7 @@ const int32_t CASE_TEN = 10; const int32_t CASE_ELEVEN = 11; const int32_t CASE_TWELVE = 12; const int32_t CASE_THIRTEEN = 13; +const int32_t CASE_FOURTEEN = 14; const int32_t CALLING_UID = 9999; const int32_t PIXEL_MAP_TEST_WIDTH = 32; @@ -131,6 +134,8 @@ public: } else if (CASE_THIRTEEN == notificationRequest.GetNotificationId()) { EXPECT_EQ(NotificationRequest::GroupAlertType::ALL, notificationRequest.GetGroupAlertType()); EXPECT_EQ(true, notificationRequest.IsGroupOverview()); + } else if (CASE_FOURTEEN == notificationRequest.GetNotificationId()) { + CheckCaseFourteenResult(notificationRequest); } else { GTEST_LOG_(INFO) << "ANS_Interface_MT_Publish::OnConsumed do nothing!!!!!"; } @@ -352,6 +357,18 @@ 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()); + } }; class CompletedCallbackTest : public WantAgent::CompletedCallback { @@ -1159,5 +1176,49 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_CancelGroup_10100, Func EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); } + +/** + * @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_04000, 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 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.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, info)); + WaitOnUnsubscribeResult(); +} } // 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 4a16ba6..a34cdb2 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_setting_test.cpp @@ -134,5 +134,48 @@ HWTEST_F(AnsInterfaceModuleSettingTest, ANS_Interface_MT_NotificationSetting_004 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/wantagent/src/want_agent_helper.cpp b/frameworks/wantagent/src/want_agent_helper.cpp index 33135ef..ba70251 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -14,12 +14,13 @@ */ #include "want_agent_helper.h" + #include "ability_manager_client.h" #include "hilog_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; diff --git a/interfaces/innerkits/ans/native/include/notification_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index a5d94f4..fcf2459 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -524,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); @@ -629,6 +629,14 @@ public: * @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_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 1e8a22b..74b2695 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -20,6 +20,7 @@ #include "message_user.h" #include "notification_action_button.h" #include "notification_content.h" +#include "notification_template.h" #include "ohos/aafwk/content/want_params.h" #include "parcel.h" #include "pixel_map.h" @@ -860,6 +861,18 @@ public: */ 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; + private: /** * Indicates the color mask, used for calculation with the ARGB value set by setColor(int32_t). @@ -945,6 +958,7 @@ private: std::vector> actionButtons_ {}; std::vector> messageUsers_ {}; std::vector userInputHistory_ {}; + std::shared_ptr notificationTemplate_ {}; }; } // namespace Notification } // namespace OHOS 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 0000000..0b56be3 --- /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/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index aed5952..79467c4 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -497,6 +497,8 @@ declare namespace notification { /** * Cancel the notification of a specified group for this application. + * + * @since 8 */ function cancelGroup(groupName: string, callback: AsyncCallback): void; function cancelGroup(groupName: string): Promise; @@ -504,6 +506,7 @@ declare namespace notification { /** * Delete the notification of a specified group for this application. * + * @since 8 * @systemapi Hide this for inner system use. * @permission ohos.permission.NOTIFICATION_CONTROLLER */ @@ -513,6 +516,7 @@ declare namespace notification { /** * Set the Do Not Disturb date. * + * @since 8 * @systemapi Hide this for inner system use. * @permission ohos.permission.NOTIFICATION_CONTROLLER */ @@ -522,6 +526,7 @@ declare namespace notification { /** * Obtains the Do Not Disturb date. * + * @since 8 * @systemapi Hide this for inner system use. * @permission ohos.permission.NOTIFICATION_CONTROLLER */ @@ -531,12 +536,22 @@ declare namespace notification { /** * 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 plateName Name of template to be Obtained + */ + function isSupportTemplate(plateName: string, callback: AsyncCallback): void; + function isSupportTemplate(plateName: string): Promise; + /** * Describes a BundleOption. */ @@ -587,6 +602,7 @@ declare namespace notification { /** * The type of the Do Not Disturb. * + * @since 8 * @systemapi Hide this for inner system use. */ export enum DoNotDisturbType { @@ -619,16 +635,22 @@ declare namespace notification { 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; } @@ -636,6 +658,7 @@ declare namespace notification { /** * Notification source type * + * @since 8 * @systemapi Hide this for inner system use. */ export enum SourceType { diff --git a/interfaces/kits/js/notification/notificationActionButton.d.ts b/interfaces/kits/js/notification/notificationActionButton.d.ts index b2967c4..9428cc4 100644 --- a/interfaces/kits/js/notification/notificationActionButton.d.ts +++ b/interfaces/kits/js/notification/notificationActionButton.d.ts @@ -42,6 +42,8 @@ export interface NotificationActionButton { /** * User input + * + * @since 8 */ userInput?: NotificationUserInput; } diff --git a/interfaces/kits/js/notification/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index 6cefef3..6525bf1 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -18,6 +18,7 @@ import image from '../@ohos.multimedia.image'; import { WantAgent } from '../@ohos.wantAgent'; import { NotificationContent } from './notificationContent'; import { NotificationActionButton } from './notificationActionButton'; +import { NotificationTemplate } from './notificationTemplate'; /** * Defines a NotificationRequest instance. @@ -141,6 +142,8 @@ export interface NotificationRequest { /** * The group information for this notification. + * + * @since 8 */ groupName?: string; @@ -174,6 +177,8 @@ export interface NotificationRequest { /** * Whether the notification can be remove. * + * @default true + * @since 8 * @systemapi Hide this for inner system use. */ readonly isRemoveAllowed?: boolean; @@ -181,7 +186,15 @@ export interface NotificationRequest { /** * 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; } diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts index 2b3f57e..d8e2277 100644 --- a/interfaces/kits/js/notification/notificationSubscriber.d.ts +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -36,6 +36,12 @@ export interface NotificationSubscriber { 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 0000000..d131ed5 --- /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/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 2d7176e..dde4e0b 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -59,6 +59,7 @@ ohos_shared_library("notification") { "src/slot.cpp", "src/subscribe.cpp", "src/unsubscribe.cpp", + "src/ans_template.cpp", ] deps = [ diff --git a/interfaces/kits/napi/ans/include/ans_template.h b/interfaces/kits/napi/ans/include/ans_template.h new file mode 100644 index 0000000..2919b62 --- /dev/null +++ b/interfaces/kits/napi/ans/include/ans_template.h @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H +#define BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H + +#include "common.h" + +namespace OHOS { +namespace NotificationNapi { +using namespace OHOS::Notification; + +napi_value IsSupportTemplate(napi_env env, napi_callback_info info); +} // namespace NotificationNapi +} // namespace OHOS + +#endif // BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_TEMPLATE_H \ No newline at end of file diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index ca2751f..4f202eb 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -404,6 +404,15 @@ public: 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); + private: static const int ARGS_ONE = 1; static const int ARGS_TWO = 2; 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 0000000..1efa212 --- /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::CancelNotification( + 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) { + 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 c995c0e..2864281 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -400,7 +400,7 @@ napi_value Common::SetNotificationRequestByPixelMap( return NapiGetBoolean(env, false); } - // smallIcon?: image.PixelMap + // smallIcon?: image.PixelMap std::shared_ptr littleIcon = request->GetLittleIcon(); if (littleIcon) { napi_value smallIconResult = nullptr; @@ -482,6 +482,18 @@ napi_value Common::SetNotificationRequestByCustom( } 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); + } + return NapiGetBoolean(env, true); } @@ -1408,6 +1420,10 @@ napi_value Common::GetNotificationRequestByCustom( if (GetNotificationLargeIcon(env, value, request) == nullptr) { return nullptr; } + // template?: NotificationTemplate + if (GetNotificationTemplate(env, value, request) == nullptr) { + return nullptr; + } return NapiGetNull(env); } @@ -2823,7 +2839,7 @@ napi_value Common::GetNotificationConversationalContentMessages( napi_value conversationalContentResult = nullptr; bool hasProperty = false; - // messages: Array + // 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); @@ -3751,5 +3767,99 @@ 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, value, 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); +} } // namespace NotificationNapi } // namespace OHOS \ No newline at end of file diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index 2a27497..c3cfdbb 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -14,6 +14,7 @@ */ #include "init.h" +#include "ans_template.h" #include "cancel.h" #include "constant.h" #include "display_badge.h" @@ -66,6 +67,7 @@ napi_value NotificationInit(napi_env env, napi_value exports) DECLARE_NAPI_FUNCTION("setDoNotDisturbDate", SetDoNotDisturbDate), DECLARE_NAPI_FUNCTION("getDoNotDisturbDate", GetDoNotDisturbDate), DECLARE_NAPI_FUNCTION("supportDoNotDisturbMode", SupportDoNotDisturbMode), + DECLARE_NAPI_FUNCTION("isSupportTemplate", IsSupportTemplate), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index 8573dcb..e0083a4 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -13,9 +13,10 @@ * limitations under the License. */ +#include "subscribe.h" + #include #include -#include "subscribe.h" namespace OHOS { namespace NotificationNapi { diff --git a/interfaces/kits/napi/wantagent/napi_want_agent.h b/interfaces/kits/napi/wantagent/napi_want_agent.h index e79f2e9..6a33753 100644 --- a/interfaces/kits/napi/wantagent/napi_want_agent.h +++ b/interfaces/kits/napi/wantagent/napi_want_agent.h @@ -16,22 +16,21 @@ #ifndef NAPI_WANT_AGENT_H #define NAPI_WANT_AGENT_H -#include -#include #include +#include +#include #include -#include "napi/native_common.h" -#include "napi/native_node_api.h" - -#include "want_agent_constant.h" +#include "ability.h" #include "completed_callback.h" #include "context.h" +#include "napi/native_common.h" +#include "napi/native_node_api.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; diff --git a/mgit.info b/mgit.info new file mode 100644 index 0000000..bba4d81 --- /dev/null +++ b/mgit.info @@ -0,0 +1 @@ +hmf/notification/ans_standard diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 8479421..b53211b 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -112,6 +112,7 @@ public: 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); @@ -175,4 +176,4 @@ private: } // 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/notification_preferences.h b/services/ans/include/notification_preferences.h index 3104edf..ef0af0a 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -68,6 +68,7 @@ public: ErrCode SetNotificationsEnabled(const bool &enabled); ErrCode GetDoNotDisturbDate(sptr &date); ErrCode SetDoNotDisturbDate(const sptr date); + ErrCode GetTemplateSupported(const std::string& templateName, bool &support); ErrCode ClearNotificationInRestoreFactorySettings(); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 1a1652f..b29831f 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -2088,5 +2088,16 @@ ErrCode AdvancedNotificationService::PrepereContinuousTaskNotificationRequest( 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; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index 04c2ce8..a8fcbaf 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -15,9 +15,12 @@ #include "notification_preferences.h" +#include + #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_log_wrapper.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace Notification { @@ -773,5 +776,36 @@ 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/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index 8069034..fbb6437 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -92,6 +92,7 @@ ohos_unittest("ans_unit_test") { "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_innerkits", + "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index f33bd20..93dbc3c 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -90,6 +90,7 @@ ohos_moduletest("ans_module_test") { "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard:libeventhandler", "ces_standard:cesfwk_innerkits", + "hitrace_native:libhitrace", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "safwk:system_ability_fwk", diff --git a/test/BUILD.gn b/test/BUILD.gn index 1cd6c47..9692d01 100644 --- a/test/BUILD.gn +++ b/test/BUILD.gn @@ -25,8 +25,8 @@ group("systemtest") { testonly = true deps = [ - "common\acts:actsnotificationtest", - "resource\ansSTSlotGroupTest:ansSTSlotGroupTest", - "systemtest\acts\ansDump:ansDumpTest", + #"common\acts:actsnotificationtest", + #"resource\ansSTSlotGroupTest:ansSTSlotGroupTest", + #"systemtest\acts\ansDump:ansDumpTest", ] } diff --git a/tools/dump/src/main.cpp b/tools/dump/src/main.cpp index b5ea105..668d391 100644 --- a/tools/dump/src/main.cpp +++ b/tools/dump/src/main.cpp @@ -20,4 +20,4 @@ int main(int argc, char *argv[]) OHOS::Notification::NotificationShellCommand cmd(argc, argv); std::cout << cmd.ExecCommand(); return 0; -} \ No newline at end of file +} -- Gitee From e6177853b2488a0e97afc2bf52e1231e879fb491 Mon Sep 17 00:00:00 2001 From: dy_study Date: Tue, 4 Jan 2022 14:46:24 +0800 Subject: [PATCH 078/131] Fix the compile error. Signed-off-by: dy_study --- frameworks/ans/core/include/ans_manager_interface.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/frameworks/ans/core/include/ans_manager_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index c8d126c..f43d0df 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -181,8 +181,8 @@ protected: PUBLISH_REMINDER, CANCEL_REMINDER, CANCEL_ALL_REMINDERS, - GET_ALL_VALID_REMINDERS - IS_SUPPORT_TEMPLATE, + GET_ALL_VALID_REMINDERS, + IS_SUPPORT_TEMPLATE }; }; } // namespace Notification -- Gitee From a3155d39b133446130ff2a1606c1be60ac0d40ca Mon Sep 17 00:00:00 2001 From: dujingcheng Date: Tue, 4 Jan 2022 06:26:32 +0000 Subject: [PATCH 079/131] bms ut Signed-off-by: dujingcheng --- .../mock/include/mock_bundle_manager.h | 20 ++++++++++++++++--- .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 9 ++++++--- .../mock/include/mock_bundle_manager.h | 20 ++++++++++++++++--- .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 9 ++++++--- 4 files changed, 46 insertions(+), 12 deletions(-) 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 cc102a7..da5c071 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; }; @@ -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/mock_bundle_mgr_proxy.cpp b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 5f16742..ba85231 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -44,13 +44,15 @@ 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; } @@ -203,7 +205,8 @@ 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; } diff --git a/services/test/moduletest/mock/include/mock_bundle_manager.h b/services/test/moduletest/mock/include/mock_bundle_manager.h index 6a550d6..47b0164 100644 --- a/services/test/moduletest/mock/include/mock_bundle_manager.h +++ b/services/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; }; @@ -365,10 +369,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; } @@ -400,6 +406,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/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp index 232efcf..b80d03d 100644 --- a/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/services/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -42,12 +42,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) { 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; } @@ -200,7 +202,8 @@ 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; } -- Gitee From f7679107907883cbcd63e237f25d5a4ef8fb6ce5 Mon Sep 17 00:00:00 2001 From: dy_study Date: Tue, 4 Jan 2022 15:35:53 +0800 Subject: [PATCH 080/131] Fix gn format error. Signed-off-by: dy_study Change-Id: Id1db6c59c49d99207114add3586d8af487bec252 --- frameworks/ans/core/BUILD.gn | 2 +- frameworks/ans/native/BUILD.gn | 2 +- interfaces/kits/napi/ans/BUILD.gn | 2 +- mgit.info | 1 - 4 files changed, 3 insertions(+), 4 deletions(-) delete mode 100644 mgit.info diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 4b035ea..cf94521 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -67,8 +67,8 @@ 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_user_input.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", diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 3a3de9d..3909036 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -62,8 +62,8 @@ ohos_shared_library("ans_innerkits") { "src/notification_sorting_map.cpp", "src/notification_subscribe_info.cpp", "src/notification_subscriber.cpp", - "src/notification_user_input.cpp", "src/notification_template.cpp", + "src/notification_user_input.cpp", ] configs = [ diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index dde4e0b..01c5cfa 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -46,6 +46,7 @@ ohos_shared_library("notification") { configs = [ ":native_module_config" ] sources = [ + "src/ans_template.cpp", "src/cancel.cpp", "src/common.cpp", "src/constant.cpp", @@ -59,7 +60,6 @@ ohos_shared_library("notification") { "src/slot.cpp", "src/subscribe.cpp", "src/unsubscribe.cpp", - "src/ans_template.cpp", ] deps = [ diff --git a/mgit.info b/mgit.info deleted file mode 100644 index bba4d81..0000000 --- a/mgit.info +++ /dev/null @@ -1 +0,0 @@ -hmf/notification/ans_standard -- Gitee From 626c9f2f5fc551b0d30bb73fae031c7437973c9b Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 5 Jan 2022 15:02:29 +0800 Subject: [PATCH 081/131] add js tdd cases Signed-off-by: derek Change-Id: If8a89fd3ed35cc246313f2caf20f239a2c9261ad --- frameworks/ans/test/moduletest/BUILD.gn | 8 + .../moduletest/ReminderHelperTest.test.js | 645 ++++++++++++++++++ frameworks/ans/test/moduletest/config.json | 61 ++ 3 files changed, 714 insertions(+) create mode 100644 frameworks/ans/test/moduletest/ReminderHelperTest.test.js create mode 100644 frameworks/ans/test/moduletest/config.json diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index f2edf40..dea3ad7 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -357,6 +357,13 @@ ohos_moduletest("ans_innerkits_module_setting_test") { part_name = "ans_standard" } +ohos_js_unittest("ReminderAgentTest") { + module_out_path = module_output_path + + hap_profile = "./config.json" + certificate_profile = "//test/developertest/signature/openharmony_sx.p7b" +} + group("moduletest") { testonly = true deps = [] @@ -366,5 +373,6 @@ group("moduletest") { ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", + ":ReminderAgentTest", ] } diff --git a/frameworks/ans/test/moduletest/ReminderHelperTest.test.js b/frameworks/ans/test/moduletest/ReminderHelperTest.test.js new file mode 100644 index 0000000..d4b0c18 --- /dev/null +++ b/frameworks/ans/test/moduletest/ReminderHelperTest.test.js @@ -0,0 +1,645 @@ +/* + * 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: 3 + } + reminderAgent.addNotificationSlot(mySlot).then(() => { + expect(true).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }, (error) => { + expect(false).assertTrue(); + setTimeout(() => { + done(); + }, 500); + }); + }) + + /* + * @tc.name: testReminderHelper006 + * @tc.desc: test addNotificationSlot with normal value + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper006", 0, async function (done) { + let mySlot0 = { + type: 0 + } + let mySlot1 = { + type: 1 + } + let mySlot2 = { + type: 2 + } + let mySlot3 = { + type: 3 + } + let mySlot4 = { + type: 4 + } + function reminderCallback(err, data){ + if (err) { + expect(true).assertTrue(); + } else { + expect(false).assertTrue(); + } + setTimeout(() => { + done(); + }, 500); + } + reminderAgent.addNotificationSlot(mySlot0, reminderCallback); + reminderAgent.addNotificationSlot(mySlot1, reminderCallback); + reminderAgent.addNotificationSlot(mySlot2, reminderCallback); + reminderAgent.addNotificationSlot(mySlot3, reminderCallback); + reminderAgent.addNotificationSlot(mySlot4, reminderCallback); + }) + + /* + * @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 + } + reminderAgent.publishReminder(timer).then((reminderId) => { + reminderAgent.getValidReminders().then((reminders) => {}); + setTimeout(() => { + reminderAgent.cancelAllReminders().then(() => { + reminderAgent.getValidReminders().then((reminders) => { + expect(0).assertEqual(reminders.length); + }); + }); + }, 1000); + }); + 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 + } + reminderAgent.publishReminder(timer, (error, reminderId) => { + reminderAgent.getValidReminders((err, reminders) => {}); + setTimeout(() => { + reminderAgent.cancelAllReminders((err, data) => { + reminderAgent.getValidReminders().then((reminders) => { + expect(0).assertEqual(reminders.length); + }); + }); + }, 1000); + }); + 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: 100 + } + let id = 1; + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(timer).then(() => { + reminderAgent.getValidReminders().then((reminders) => { + publishlength=reminders.length + }); + setTimeout(() => { + reminderAgent.cancelReminder(id).then(() => { + reminderAgent.getValidReminders().then((reminders) => { + cancellength = reminders.length + firstdiff = publishlength-cancellength; + if (firstdiff === 0) { + expect(0).assertEqual(firstdiff); + } + }); + }); + }, 1000); + }); + 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: 100 + } + let id = 1; + let publishlength = -1; + let cancellength = -1; + let firstdiff = -1; + reminderAgent.publishReminder(timer).then(() => { + reminderAgent.getValidReminders((err, reminders) => { + publishlength = reminders.length; + }); + setTimeout(() => { + reminderAgent.cancelReminder(id,(err,data)=>{ + reminderAgent.getValidReminders((err, reminders) => { + cancellength = reminders.length; + firstdiff = publishlength-cancellength; + if (firstdiff === 0) { + expect(0).assertEqual(firstdiff); + } + }); + }); + }, 1000); + }); + 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.publishReminder(timer, (error, reminderId) => {}); + reminderAgent.publishReminder(alarm, (error, reminderId) => {}); + setTimeout(() => { + reminderAgent.getValidReminders().then((reminders) => { + if (reminders.length >= 2) { + let i = 0; + expect(0).assertEqual(i); + } + }); + }, 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.publishReminder(timer, (error, reminderId) => {}); + reminderAgent.publishReminder(alarm, (error, reminderId) => {}); + setTimeout(() => { + reminderAgent.getValidReminders((err, reminders) => { + if (reminders.length >= 2) { + let i = 0; + expect(0).assertEqual(i); + } + }); + }, 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(() => { + expect(0).assertEqual(err.code); + }); + }); + 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(0).assertEqual(reminders.length); + }); + }, 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).then((reminderId) => {}); + setTimeout(() => { + reminderAgent.getValidReminders((err, reminders) => { + expect(0).assertEqual(reminders.length); + }); + }, 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 + } + reminderAgent.publishReminder(alarm).then((reminderId) => { + if (reminderId) { + let i = 0; + expect(0).assertEqual(i); + } + }); + 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 + } + function reminderCallback (err, reminderId) { + if (reminderId) { + let i = 0; + expect(0).assertEqual(i); + } + } + reminderAgent.publishReminder(alarm, reminderCallback); + done(); + }) + + /* + * @tc.name: testReminderHelper023 + * @tc.desc: test publishReminder (max number limit of each application) + * @tc.type: FUNC + * @tc.require: + */ + it("testReminderHelper023", 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) { + setTimeout(function () { + reminderAgent.publishReminder(timer).then((reminderId) => { + if (i === 0) { + firstId = reminderId + } + if (i === 29) { + secondId = reminderId + diffId = secondId - firstId + expect(29).assertEqual(diffId); + } + }); + }, 500 * i); + })(i); + } + done(); + }) +}) \ No newline at end of file diff --git a/frameworks/ans/test/moduletest/config.json b/frameworks/ans/test/moduletest/config.json new file mode 100644 index 0000000..d779db8 --- /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": 5 + } + }, + "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 -- Gitee From 7888ba32abdf7cb1032a1aaf8790fe869c395c38 Mon Sep 17 00:00:00 2001 From: derek Date: Thu, 6 Jan 2022 11:58:30 +0800 Subject: [PATCH 082/131] fix gn format Signed-off-by: derek Change-Id: I082a5cbb35b2b53f7bdeb5c00aaccd9d0d81ba88 --- frameworks/ans/test/moduletest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index dea3ad7..7f33b41 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -369,10 +369,10 @@ group("moduletest") { deps = [] deps += [ + ":ReminderAgentTest", ":ans_fw_module_test", ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", - ":ReminderAgentTest", ] } -- Gitee From 86452167c130ebf6665c7d7cc593a46f0da77899 Mon Sep 17 00:00:00 2001 From: fangjinliang1 Date: Tue, 11 Jan 2022 20:46:50 +0800 Subject: [PATCH 083/131] Support multiple users Signed-off-by: fangjinliang1 Change-Id: Id3af01b44e6d5a9dd596ff52fbd74c8af3415125 --- .../core/common/include/ans_const_define.h | 2 + frameworks/ans/native/src/notification.cpp | 8 + .../ans/native/src/notification_request.cpp | 10 + .../src/notification_subscribe_info.cpp | 10 + .../ans/native/include/notification.h | 7 + .../ans/native/include/notification_request.h | 13 + .../include/notification_subscribe_info.h | 15 + interfaces/kits/napi/ans/src/subscribe.cpp | 1 + services/ans/BUILD.gn | 5 + .../include/advanced_notification_service.h | 1 + .../ans/include/notification_preferences.h | 17 +- .../notification_preferences_database.h | 41 ++- .../include/notification_preferences_info.h | 14 +- .../include/notification_subscriber_manager.h | 4 +- services/ans/include/preferences_constant.h | 1 + .../ans/src/advanced_notification_service.cpp | 56 +++- services/ans/src/notification_preferences.cpp | 101 ++++-- .../src/notification_preferences_database.cpp | 302 ++++++++++++------ .../ans/src/notification_preferences_info.cpp | 54 ++-- .../src/notification_subscriber_manager.cpp | 29 +- services/ans/test/unittest/BUILD.gn | 5 + ...notification_preferences_database_test.cpp | 116 ++++--- .../notification_preferences_test.cpp | 57 +++- services/test/moduletest/BUILD.gn | 5 + 24 files changed, 654 insertions(+), 220 deletions(-) diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index e066999..c498d2b 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -32,6 +32,8 @@ 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; // Default sound for notification const static Uri DEFAULT_NOTIFICATION_SOUND("file://system/etc/Light.ogg"); diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 40636e8..e0ab103 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -182,6 +182,14 @@ NotificationConstant::SourceType Notification::GetSourceType() const return sourceType_; } +int32_t Notification::GetUserId() const +{ + if (request_ == nullptr) { + return 0; + } + return request_->GetCreatorUserId(); +} + bool Notification::MarshallingBool(Parcel &parcel) const { if (!parcel.WriteBool(enableLight_)) { diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 0bce17e..10343c0 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -719,6 +719,16 @@ std::string NotificationRequest::GetLabel() const return label_; } +void NotificationRequest::SetCreatorUserId(int32_t userId) +{ + creatorUserId_ = userId; +} + +int32_t NotificationRequest::GetCreatorUserId() const +{ + return creatorUserId_; +} + std::string NotificationRequest::Dump() { return "NotificationRequest{ " diff --git a/frameworks/ans/native/src/notification_subscribe_info.cpp b/frameworks/ans/native/src/notification_subscribe_info.cpp index 0f70d04..50cd3a9 100644 --- a/frameworks/ans/native/src/notification_subscribe_info.cpp +++ b/frameworks/ans/native/src/notification_subscribe_info.cpp @@ -45,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_ diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index e2e71ea..1d40d79 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -189,6 +189,13 @@ public: */ NotificationConstant::SourceType GetSourceType() 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. * diff --git a/interfaces/innerkits/ans/native/include/notification_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 74b2695..f5efaff 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -843,6 +843,18 @@ public: */ std::string GetLabel() 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. @@ -914,6 +926,7 @@ private: pid_t creatorPid_ {0}; pid_t creatorUid_ {0}; + int32_t creatorUserId_ {-1}; std::string settingsText_ {}; std::string creatorBundleName_ {}; diff --git a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h index 7043ae6..7da904f 100644 --- a/interfaces/innerkits/ans/native/include/notification_subscribe_info.h +++ b/interfaces/innerkits/ans/native/include/notification_subscribe_info.h @@ -64,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. * @@ -90,6 +104,7 @@ private: private: std::vector appNames_ {}; + int32_t userId_ {-1}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index e0083a4..a0a5b2c 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -1050,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 { diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index 7261438..3af7750 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -25,6 +25,10 @@ config("public_ans_config") { "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/account/os_account/frameworks/common/database/include/", + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/log/include", ] defines = [ "APP_LOG_TAG = \"Ans\"", @@ -60,6 +64,7 @@ ohos_shared_library("libans") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/miscservices/time/services:time_service", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index b53211b..6d03972 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -159,6 +159,7 @@ private: 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); private: static sptr instance_; diff --git a/services/ans/include/notification_preferences.h b/services/ans/include/notification_preferences.h index ef0af0a..04ef923 100644 --- a/services/ans/include/notification_preferences.h +++ b/services/ans/include/notification_preferences.h @@ -64,10 +64,12 @@ 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 GetDoNotDisturbDate(sptr &date); - ErrCode SetDoNotDisturbDate(const sptr date); + 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(); @@ -87,16 +89,17 @@ private: const sptr &slot, NotificationPreferencesInfo &preferencesInfo) const; ErrCode CheckGroupForUpdateSlotGroup(const sptr &bundleOption, const sptr &group, NotificationPreferencesInfo &preferencesInfo) const; - template + template ErrCode SetBundleProperty(NotificationPreferencesInfo &preferencesInfo, const sptr &bundleOption, const BundleType &type, const T &value); - template + template ErrCode SaveBundleProperty(NotificationPreferencesInfo::BundleInfo &bundleInfo, const sptr &bundleOption, const BundleType &type, const T &value); - template + template ErrCode GetBundleProperty( const sptr &bundleOption, const BundleType &type, T &value) const; std::string GenerateBundleKey(const sptr &bundleOption) const; + bool GetActiveUserId(int& userId); private: NotificationPreferencesInfo preferencesInfo_ {}; diff --git a/services/ans/include/notification_preferences_database.h b/services/ans/include/notification_preferences_database.h index 0787c62..6b531e4 100644 --- a/services/ans/include/notification_preferences_database.h +++ b/services/ans/include/notification_preferences_database.h @@ -28,17 +28,20 @@ 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 PutDoNotDisturbDate(const sptr &date); + 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); @@ -56,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( @@ -70,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; @@ -112,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; @@ -129,6 +134,12 @@ private: 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_; @@ -143,4 +154,4 @@ private: }; } // 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 ac53056..943252d 100644 --- a/services/ans/include/notification_preferences_info.h +++ b/services/ans/include/notification_preferences_info.h @@ -80,19 +80,21 @@ public: {} ~NotificationPreferencesInfo() {} - void SetEnabledAllNotification(const bool &value); - bool GetEnabledAllNotification() const; - void SetDoNotDisturbDate(const sptr &date); - sptr GetDoNotDisturbDate() 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; - sptr doNotDisturbDate_ = new NotificationDoNotDisturbDate(); + std::map isEnabledAllNotification_; + std::map> doNotDisturbDate_; std::map infos_; }; } // namespace Notification diff --git a/services/ans/include/notification_subscriber_manager.h b/services/ans/include/notification_subscriber_manager.h index 477acb7..f6e2ae6 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" @@ -54,7 +55,8 @@ 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); ErrCode AddSubscriberInner( diff --git a/services/ans/include/preferences_constant.h b/services/ans/include/preferences_constant.h index 64419b6..b5430c6 100644 --- a/services/ans/include/preferences_constant.h +++ b/services/ans/include/preferences_constant.h @@ -32,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"; diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index b29831f..2110f89 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -30,6 +30,7 @@ #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" @@ -157,6 +158,10 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque int pid = IPCSkeleton::GetCallingPid(); request->SetCreatorUid(uid); request->SetCreatorPid(pid); + + int userId = SUBSCRIBE_USER_INIT; + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + request->SetCreatorUserId(userId); ErrCode result = CheckPictureSize(request); @@ -1136,11 +1141,16 @@ 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; @@ -1191,10 +1201,15 @@ ErrCode AdvancedNotificationService::SetNotificationsEnabledForAllBundles(const } 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 } @@ -1241,9 +1256,14 @@ ErrCode AdvancedNotificationService::IsAllowedNotify(bool &allowed) } 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; } @@ -1280,7 +1300,7 @@ 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) { @@ -2019,8 +2039,13 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + handler_->PostSyncTask(std::bind([&]() { - result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(newConfig); + result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, newConfig); if (result == ERR_OK) { NotificationSubscriberManager::GetInstance()->NotifyDoNotDisturbDateChanged(newConfig); } @@ -2034,10 +2059,14 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr bundleOption = GenerateBundleOption(); + if (bundleOption == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } handler_->PostSyncTask(std::bind([&]() { sptr currentConfig = nullptr; - result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(currentConfig); + result = NotificationPreferences::GetInstance().GetDoNotDisturbDate(bundleOption, currentConfig); if (result == ERR_OK) { int64_t now = GetCurrentTime(); switch (currentConfig->GetDoNotDisturbType()) { @@ -2045,7 +2074,7 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptr= currentConfig->GetEndDate()) { date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - NotificationPreferences::GetInstance().SetDoNotDisturbDate(date); + NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, date); } else { date = currentConfig; } @@ -2099,5 +2128,18 @@ ErrCode AdvancedNotificationService::IsSupportTemplate(const std::string& templa })); 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; +} } // namespace Notification } // namespace OHOS diff --git a/services/ans/src/notification_preferences.cpp b/services/ans/src/notification_preferences.cpp index a8fcbaf..4dd6b40 100644 --- a/services/ans/src/notification_preferences.cpp +++ b/services/ans/src/notification_preferences.cpp @@ -21,6 +21,7 @@ #include "ans_inner_errors.h" #include "ans_log_wrapper.h" #include "nlohmann/json.hpp" +#include "os_account_manager.h" namespace OHOS { namespace Notification { @@ -54,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; } @@ -81,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; } @@ -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; } @@ -251,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; } @@ -489,18 +494,51 @@ ErrCode NotificationPreferences::SetNotificationsEnabledForBundle( return result; } -ErrCode NotificationPreferences::GetNotificationsEnabled(bool &enabled) +bool NotificationPreferences::GetActiveUserId(int& userId) { - enabled = preferencesInfo_.GetEnabledAllNotification(); - return ERR_OK; + std::vector osAccountInfos; + OHOS::AccountSA::OsAccountManager::QueryAllCreatedOsAccounts(osAccountInfos); + + for (auto iter : osAccountInfos) { + if (iter.GetIsActived()) { + userId = iter.GetLocalId(); + return true; + } + } + return false; +} + +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 bool &enabled) +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; } @@ -510,18 +548,39 @@ ErrCode NotificationPreferences::SetNotificationsEnabled(const bool &enabled) return result; } -ErrCode NotificationPreferences::GetDoNotDisturbDate(sptr &date) +ErrCode NotificationPreferences::GetDoNotDisturbDate( + const sptr &bundleOption, sptr &date) { - date = preferencesInfo_.GetDoNotDisturbDate(); - 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::SetDoNotDisturbDate(const sptr date) +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.SetDoNotDisturbDate(date); + preferencesInfo.SetDoNotDisturbDate(userId, date); + ErrCode result = ERR_OK; - if (!preferncesDB_->PutDoNotDisturbDate(date)) { + if (!preferncesDB_->PutDoNotDisturbDate(userId, date)) { result = ERR_ANS_PREFERENCES_NOTIFICATION_DB_OPERATION_FAILED; } @@ -706,23 +765,23 @@ ErrCode NotificationPreferences::SaveBundleProperty(NotificationPreferencesInfo: switch (type) { case BundleType::BUNDLE_IMPORTANCE_TYPE: bundleInfo.SetImportance(value); - storeDBResult = preferncesDB_->PutImportance(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; diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 809f7f7..8d40c0e 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -14,7 +14,9 @@ */ #include "notification_preferences_database.h" +#include "ans_const_define.h" #include "ans_log_wrapper.h" +#include "os_account_manager.h" #include "uri.h" namespace OHOS { @@ -112,6 +114,11 @@ const std::map> &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; } @@ -181,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; } @@ -196,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; } @@ -211,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; } @@ -238,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: { @@ -257,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); @@ -320,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); @@ -354,7 +373,8 @@ bool NotificationPreferencesDatabase::PutNotificationsEnabled(const bool &enable return true; } -bool NotificationPreferencesDatabase::PutDoNotDisturbDate(const sptr &date) +bool NotificationPreferencesDatabase::PutDoNotDisturbDate( + const int32_t &userId, const sptr &date) { if (date == nullptr) { ANS_LOGE("Invalid date."); @@ -367,15 +387,21 @@ bool NotificationPreferencesDatabase::PutDoNotDisturbDate(const sptrGetDoNotDisturbType())); OHOS::DistributedKv::Entry beginDate; - beginDate.key = OHOS::DistributedKv::Key(KEY_DO_NOT_DISTURB_BEGIN_DATE); + 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; - endDate.key = OHOS::DistributedKv::Key(KEY_DO_NOT_DISTURB_END_DATE); + 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 = { @@ -432,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: { @@ -460,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); @@ -475,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; @@ -727,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; @@ -752,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; } @@ -799,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) { @@ -808,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; } @@ -1087,69 +1118,46 @@ std::string NotificationPreferencesDatabase::SubUniqueIdentifyFromString( void NotificationPreferencesDatabase::ParseDoNotDisturbType(NotificationPreferencesInfo &info) { - GetValueFromDisturbeDB( - KEY_DO_NOT_DISTURB_TYPE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDoNotDisturbDate(info.GetDoNotDisturbDate()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - auto date = info.GetDoNotDisturbDate(); - date->SetDoNotDisturbType((NotificationConstant::DoNotDisturbType)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) { - GetValueFromDisturbeDB( - KEY_DO_NOT_DISTURB_BEGIN_DATE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDoNotDisturbDate(info.GetDoNotDisturbDate()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - auto date = info.GetDoNotDisturbDate(); - date->SetBeginDate(StringToInt64(value.ToString())); - } - } else { - ANS_LOGW("Parse disturbe start time failed, use defalut value."); - } - }); + 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) { - GetValueFromDisturbeDB( - KEY_DO_NOT_DISTURB_END_DATE, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { - if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { - PutDoNotDisturbDate(info.GetDoNotDisturbDate()); - } else if (status == OHOS::DistributedKv::Status::SUCCESS) { - if (!value.ToString().empty()) { - auto date = info.GetDoNotDisturbDate(); - date->SetEndDate(StringToInt64(value.ToString())); - } - } else { - ANS_LOGW("Parse disturbe end time failed, use defalut value."); - } - }); + 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( @@ -1206,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()); @@ -1291,5 +1306,104 @@ 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; + info.GetEnabledAllNotification(userId, enable); + 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 f58a968..586288a 100644 --- a/services/ans/src/notification_preferences_info.cpp +++ b/services/ans/src/notification_preferences_info.cpp @@ -227,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::SetDoNotDisturbDate(const sptr &date) -{ - doNotDisturbDate_ = date; -} - -sptr NotificationPreferencesInfo::GetDoNotDisturbDate() const -{ - return doNotDisturbDate_; -} - void NotificationPreferencesInfo::SetBundleInfo(const BundleInfo &info) { std::string bundleKey = info.GetBundleName().append(std::to_string(info.GetBundleUid())); @@ -290,5 +270,37 @@ 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_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index a37ece9..86d467f 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -19,8 +19,11 @@ #include #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 { @@ -29,6 +32,7 @@ struct NotificationSubscriberManager::SubscriberRecord { sptr subscriber {nullptr}; std::set bundleList_ {}; bool subscribedAll {false}; + int32_t userId {SUBSCRIBE_USER_INIT}; }; NotificationSubscriberManager::NotificationSubscriberManager() @@ -52,9 +56,23 @@ ErrCode NotificationSubscriberManager::AddSubscriber( return ERR_ANS_INVALID_PARAM; } + 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; + } + + int userId = SUBSCRIBE_USER_INIT; + int uid = IPCSkeleton::GetCallingUid(); + OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + subInfo->AddAppUserId(userId); + } + ErrCode result = ERR_ANS_TASK_ERR; - handler_->PostSyncTask(std::bind([this, &subscriber, &subscribeInfo, &result]() { - result = this->AddSubscriberInner(subscriber, subscribeInfo); + handler_->PostSyncTask(std::bind([this, &subscriber, &subInfo, &result]() { + result = this->AddSubscriberInner(subscriber, subInfo); }), AppExecFwk::EventQueue::Priority::HIGH); return result; @@ -188,6 +206,7 @@ void NotificationSubscriberManager::AddRecordInfo( for (auto bundle : subscribeInfo->GetAppNames()) { record->bundleList_.insert(bundle); } + record->userId = subscribeInfo->GetAppUserId(); } else { record->bundleList_.clear(); record->subscribedAll = true; @@ -266,7 +285,8 @@ void NotificationSubscriberManager::NotifyConsumedInner( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); - if (!record->subscribedAll == (iter != record->bundleList_.end())) { + if (!record->subscribedAll == (iter != record->bundleList_.end()) && + (notification->GetUserId() == record->userId || notification->GetUserId() == SUBSCRIBE_USER_ALL)) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } @@ -280,7 +300,8 @@ void NotificationSubscriberManager::NotifyCanceledInner( 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); } diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index fbb6437..d29b10e 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -31,6 +31,10 @@ ohos_unittest("ans_unit_test") { "//utils/system/safwk/native/include", "/${services_path}/ans/include", "${services_path}/ans/test/unittest/mock/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/account/os_account/frameworks/common/database/include/", + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/log/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", @@ -77,6 +81,7 @@ ohos_unittest("ans_unit_test") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/miscservices/time/services:time_service", "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", diff --git a/services/ans/test/unittest/notification_preferences_database_test.cpp b/services/ans/test/unittest/notification_preferences_database_test.cpp index b294f18..e4857df 100644 --- a/services/ans/test/unittest/notification_preferences_database_test.cpp +++ b/services/ans/test/unittest/notification_preferences_database_test.cpp @@ -29,6 +29,8 @@ public: void TearDown() {}; const std::string bundleName_ = "bundleName"; + const int bundleUid_ = 2001; + int32_t userId = 100; std::unique_ptr preferncesDB_ = std::make_unique(); }; @@ -45,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)); } /** @@ -60,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)); } /** @@ -71,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)); } /** @@ -85,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)); } /** @@ -98,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)); } /** @@ -109,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)); } /** @@ -119,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)); } /** @@ -130,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)); } /** @@ -140,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)); } /** @@ -161,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)); } /** @@ -172,7 +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)); } /** @@ -182,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)); } /** @@ -192,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)); } /** @@ -203,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)); } /** @@ -213,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)); } /** @@ -224,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)); } /** @@ -234,8 +267,8 @@ 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)); } /** @@ -247,7 +280,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00100, Functio { sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::NONE, 0, 0); - EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(date)); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** @@ -265,7 +298,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00200, Functio int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(date)); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** @@ -284,7 +317,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00300, Functio sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(date)); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** @@ -303,7 +336,7 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00400, Functio sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::CLEARLY, beginDate, endDate); - EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(date)); + EXPECT_TRUE(preferncesDB_->PutDoNotDisturbDate(userId, date)); } /** @@ -313,7 +346,10 @@ HWTEST_F(NotificationPreferencesDatabaseTest, PutDoNotDisturbDate_00400, Functio */ 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)); } @@ -335,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_)); } @@ -359,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)); @@ -386,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)); @@ -467,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)); } /** @@ -479,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)); } /** @@ -489,7 +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 f1ec114..c909c9b 100644 --- a/services/ans/test/unittest/notification_preferences_test.cpp +++ b/services/ans/test/unittest/notification_preferences_test.cpp @@ -1017,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); } /** @@ -1027,9 +1027,9 @@ 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); } @@ -1049,7 +1049,7 @@ HWTEST_F(NotificationPreferencesTest, SetDoNotDisturbDate_00100, Function | Smal sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::ONCE, beginDate, endDate); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(date), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); } /** @@ -1067,13 +1067,58 @@ HWTEST_F(NotificationPreferencesTest, GetDoNotDisturbDate_00100, Function | Smal int64_t endDate = endDuration.count(); sptr date = new NotificationDoNotDisturbDate(NotificationConstant::DoNotDisturbType::DAILY, beginDate, endDate); - EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(date), (int)ERR_OK); + EXPECT_EQ((int)NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption_, date), (int)ERR_OK); sptr getDate; - EXPECT_EQ((int)NotificationPreferences::GetInstance().GetDoNotDisturbDate(getDate), (int)ERR_OK); + 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/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 93dbc3c..217cb3f 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -27,6 +27,10 @@ ohos_moduletest("ans_module_test") { "//utils/system/safwk/native/include", "${services_path}/ans/include", "${services_path}/test/moduletest/mock/include", + "//base/account/os_account/interfaces/innerkits/osaccount/native/include", + "//base/account/os_account/frameworks/common/database/include/", + "//base/account/os_account/frameworks/common/account_error/include", + "//base/account/os_account/frameworks/common/log/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils", "//foundation/distributeddatamgr/distributeddatamgr/frameworks/innerkitsimpl/distributeddatafwk/include", "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log", @@ -69,6 +73,7 @@ ohos_moduletest("ans_module_test") { "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", "${frameworks_path}/wantagent:wantagent_innerkits", + "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/miscservices/time/services:time_service", "//foundation/aafwk/standard/services/abilitymgr:abilityms", "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", -- Gitee From 902be5ce36072ad2e70fcf52bb97e56ea62d9968 Mon Sep 17 00:00:00 2001 From: njupthan Date: Tue, 11 Jan 2022 17:08:05 +0000 Subject: [PATCH 084/131] Update all dts to master branch of ANS and SDK repositories Signed-off-by: njupthan --- interfaces/kits/js/@ohos.notification.d.ts | 82 +++++++++++++++---- interfaces/kits/js/@ohos.wantAgent.d.ts | 27 +----- .../notification/notificationSubscriber.d.ts | 1 - 3 files changed, 66 insertions(+), 44 deletions(-) diff --git a/interfaces/kits/js/@ohos.notification.d.ts b/interfaces/kits/js/@ohos.notification.d.ts index 79467c4..edbbd33 100644 --- a/interfaces/kits/js/@ohos.notification.d.ts +++ b/interfaces/kits/js/@ohos.notification.d.ts @@ -547,11 +547,11 @@ declare namespace notification { * Obtains whether the template is supported by the system. * * @since 8 - * @param plateName Name of template to be Obtained + * @param templateName Name of template to be Obtained */ - function isSupportTemplate(plateName: string, callback: AsyncCallback): void; - function isSupportTemplate(plateName: string): Promise; - + function isSupportTemplate(templateName: string, callback: AsyncCallback): void; + function isSupportTemplate(templateName: string): Promise; + /** * Describes a BundleOption. */ @@ -569,34 +569,82 @@ declare namespace notification { } /** - * DisturbMode + * The type of the Do Not Disturb. * + * @since 8 * @systemapi Hide this for inner system use. */ - export enum DoNotDisturbMode { - ALLOW_UNKNOWN, + export enum DoNotDisturbType { + /** + * Non do not disturb type notification + */ + TYPE_NONE = 0, /** - * Indicates that all notifications are allowed to interrupt the user in Do Not Disturb mode. + * Execute do not disturb once in the set time period (only watch hours and minutes) */ - ALLOW_ALL, + TYPE_ONCE = 1, /** - * Indicates that only notifications meeting the specified priority criteria are allowed to interrupt - * the user in Do Not Disturb mode. + * Execute do not disturb every day with a set time period (only watch hours and minutes) */ - ALLOW_PRIORITY, + TYPE_DAILY = 2, /** - * Indicates that no notifications are allowed to interrupt the user in Do Not Disturb mode. + * Execute in the set time period (specify the time, month, day and hour) */ - ALLOW_NONE, + TYPE_CLEARLY = 3, + } + /** + * Describes a DoNotDisturbDate instance. + * + * @systemapi Hide this for inner system use. + */ + export interface DoNotDisturbDate { /** - * Indicates that only notifications of the {@link NotificationRequest#CLASSIFICATION_ALARM} category - * are allowed to interrupt the user in Do Not Disturb mode. + * the type of the Do Not Disturb. + * + * @since 8 */ - ALLOW_ALARMS + 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 { + /** + * General notification + */ + TYPE_NORMAL = 0x00000000, + + /** + * Continuous notification + */ + TYPE_CONTINUOUS = 0x00000001, + + /** + * Scheduled notification + */ + TYPE_TIMER = 0x00000002, } /** diff --git a/interfaces/kits/js/@ohos.wantAgent.d.ts b/interfaces/kits/js/@ohos.wantAgent.d.ts index 17dd1c8..e5de044 100644 --- a/interfaces/kits/js/@ohos.wantAgent.d.ts +++ b/interfaces/kits/js/@ohos.wantAgent.d.ts @@ -132,32 +132,7 @@ declare namespace wantAgent { /** * Indicates that the created WantAgent should be immutable. */ - CONSTANT_FLAG, - - /** - * Indicates that the current value of element can be replaced when the WantAgent is triggered. - */ - REPLACE_ELEMENT, - - /** - * Indicates that the current value of action can be replaced when the WantAgent is triggered. - */ - REPLACE_ACTION, - - /** - * Indicates that the current value of uri can be replaced when the WantAgent is triggered. - */ - REPLACE_URI, - - /** - * Indicates that the current value of entities can be replaced when the WantAgent is triggered. - */ - REPLACE_ENTITIES, - - /** - * Indicates that the current value of packageName can be replaced when the WantAgent is triggered. - */ - REPLACE_BUNDLE + CONSTANT_FLAG } /** diff --git a/interfaces/kits/js/notification/notificationSubscriber.d.ts b/interfaces/kits/js/notification/notificationSubscriber.d.ts index d8e2277..3ae8787 100644 --- a/interfaces/kits/js/notification/notificationSubscriber.d.ts +++ b/interfaces/kits/js/notification/notificationSubscriber.d.ts @@ -35,7 +35,6 @@ export interface NotificationSubscriber { onConnect?:() => void; onDisconnect?:() => void; onDestroy?:() => void; - onDisturbModeChange?:(mode: notification.DoNotDisturbMode) => void; /** * Callback when the Do Not Disturb setting changed. -- Gitee From 1f862cef075bef380b4f6558d38a02de5858ee72 Mon Sep 17 00:00:00 2001 From: fangjinliang1 Date: Wed, 12 Jan 2022 16:37:57 +0800 Subject: [PATCH 085/131] Support multiple users Signed-off-by: fangjinliang1 Change-Id: Ie9f595d8e3a7ace3b0e770e5f7e0ae2e27d5e2a2 --- services/ans/src/notification_preferences_database.cpp | 5 ++++- services/ans/src/notification_subscriber_manager.cpp | 8 +++----- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 8d40c0e..3359c9c 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -1393,7 +1393,10 @@ void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPrefe key, [&](OHOS::DistributedKv::Status &status, OHOS::DistributedKv::Value &value) { if (status == OHOS::DistributedKv::Status::KEY_NOT_FOUND) { bool enable = true; - info.GetEnabledAllNotification(userId, enable); + 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()) { diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 86d467f..9b7d7e2 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -64,9 +64,7 @@ ErrCode NotificationSubscriberManager::AddSubscriber( return ERR_ANS_NO_MEMORY; } - int userId = SUBSCRIBE_USER_INIT; - int uid = IPCSkeleton::GetCallingUid(); - OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); + int userId = SUBSCRIBE_USER_ALL; subInfo->AddAppUserId(userId); } @@ -101,7 +99,6 @@ void NotificationSubscriberManager::NotifyConsumed( ANS_LOGE("handler is nullptr"); return; } - AppExecFwk::EventHandler::Callback NotifyConsumedFunc = std::bind(&NotificationSubscriberManager::NotifyConsumedInner, this, notification, notificationMap); @@ -202,9 +199,10 @@ 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(); } else { -- Gitee From 8c39c4892885008001cf148e6fa1095b8ca7e757 Mon Sep 17 00:00:00 2001 From: fangjinliang1 Date: Wed, 12 Jan 2022 17:40:47 +0800 Subject: [PATCH 086/131] Support multiple users Signed-off-by: fangjinliang1 Change-Id: I9dd27d36fdab7d405d6748cff765cbcfffaa7e03 --- services/ans/src/advanced_notification_service.cpp | 1 - services/ans/src/notification_subscriber_manager.cpp | 8 +++++--- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 2110f89..f936f46 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -162,7 +162,6 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque int userId = SUBSCRIBE_USER_INIT; OHOS::AccountSA::OsAccountManager::GetOsAccountLocalIdFromUid(uid, userId); request->SetCreatorUserId(userId); - ErrCode result = CheckPictureSize(request); return result; diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 9b7d7e2..8485bea 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -99,6 +99,7 @@ void NotificationSubscriberManager::NotifyConsumed( ANS_LOGE("handler is nullptr"); return; } + AppExecFwk::EventHandler::Callback NotifyConsumedFunc = std::bind(&NotificationSubscriberManager::NotifyConsumedInner, this, notification, notificationMap); @@ -205,6 +206,9 @@ void NotificationSubscriberManager::AddRecordInfo( record->subscribedAll = false; } record->userId = subscribeInfo->GetAppUserId(); + if (record->userId == SUBSCRIBE_USER_INIT) { + record->userId = SUBSCRIBE_USER_ALL; + } } else { record->bundleList_.clear(); record->subscribedAll = true; @@ -232,7 +236,6 @@ ErrCode NotificationSubscriberManager::AddSubscriberInner( const sptr &subscriber, const sptr &subscribeInfo) { std::shared_ptr record = FindSubscriberRecord(subscriber); - if (record == nullptr) { record = CreateSubscriberRecord(subscriber); if (record == nullptr) { @@ -281,10 +284,9 @@ void NotificationSubscriberManager::NotifyConsumedInner( { for (auto record : subscriberRecordList_) { auto BundleNames = notification->GetBundleName(); - auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); if (!record->subscribedAll == (iter != record->bundleList_.end()) && - (notification->GetUserId() == record->userId || notification->GetUserId() == SUBSCRIBE_USER_ALL)) { + (notification->GetUserId() == record->userId || record->userId == SUBSCRIBE_USER_ALL)) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } -- Gitee From ae238f22ab8cfe2c4d252a99b3d33d9a2b64f214 Mon Sep 17 00:00:00 2001 From: fangjinliang1 Date: Fri, 14 Jan 2022 12:04:21 +0800 Subject: [PATCH 087/131] Multi users modify Signed-off-by: fangjinliang1 Change-Id: I0ed2f845206b7a4362a7bbaafe0ad5488e9c049a --- frameworks/ans/core/common/include/ans_const_define.h | 3 +++ services/ans/src/advanced_notification_service.cpp | 5 ++++- services/ans/src/notification_subscriber_manager.cpp | 7 +++++-- 3 files changed, 12 insertions(+), 3 deletions(-) diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index c498d2b..bda3a1f 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -32,8 +32,11 @@ 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"); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index f936f46..953a519 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -144,7 +144,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()) { @@ -161,6 +161,9 @@ inline ErrCode PrepereNotificationRequest(const sptr &reque 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); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 8485bea..1e850b7 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -206,7 +206,8 @@ void NotificationSubscriberManager::AddRecordInfo( record->subscribedAll = false; } record->userId = subscribeInfo->GetAppUserId(); - if (record->userId == SUBSCRIBE_USER_INIT) { + if (record->userId == SUBSCRIBE_USER_INIT || + (record->userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && record->userId <= SUBSCRIBE_USER_SYSTEM_END)) { record->userId = SUBSCRIBE_USER_ALL; } } else { @@ -286,7 +287,9 @@ void NotificationSubscriberManager::NotifyConsumedInner( auto BundleNames = notification->GetBundleName(); auto iter = std::find(record->bundleList_.begin(), record->bundleList_.end(), BundleNames); if (!record->subscribedAll == (iter != record->bundleList_.end()) && - (notification->GetUserId() == record->userId || record->userId == SUBSCRIBE_USER_ALL)) { + (notification->GetUserId() == record->userId || + notification->GetUserId() == SUBSCRIBE_USER_ALL || + record->userId == SUBSCRIBE_USER_ALL)) { record->subscriber->OnConsumed(notification, notificationMap); record->subscriber->OnConsumed(notification); } -- Gitee From f4e2951311b42f1c004e3450a95c3bb44beb7795 Mon Sep 17 00:00:00 2001 From: zero-cyc Date: Sat, 15 Jan 2022 17:30:51 +0800 Subject: [PATCH 088/131] chenlien@huawei.com Signed-off-by: zero-cyc Change-Id: I980e220bb69acfca9e0b4291aba45e16784e19e6 --- ohos.build => bundle.json | 84 ++++++++++++++++++++++--- frameworks/ans/core/BUILD.gn | 8 +-- frameworks/ans/native/BUILD.gn | 7 +-- frameworks/wantagent/BUILD.gn | 9 ++- interfaces/kits/napi/ans/BUILD.gn | 9 ++- interfaces/kits/napi/wantagent/BUILD.gn | 13 ++-- services/ans/BUILD.gn | 10 ++- 7 files changed, 99 insertions(+), 41 deletions(-) rename ohos.build => bundle.json (36%) diff --git a/ohos.build b/bundle.json similarity index 36% rename from ohos.build rename to bundle.json index 96a234c..0319b7b 100644 --- a/ohos.build +++ b/bundle.json @@ -1,16 +1,85 @@ { - "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": "", + "ram": "", + "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/test/moduletest:ans_module_test", "//base/notification/ans_standard/frameworks/ans/test/moduletest:moduletest", @@ -19,6 +88,5 @@ "//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 cf94521..8ea2b3b 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -82,19 +82,19 @@ ohos_shared_library("ans_core") { deps = [ "${frameworks_path}/wantagent:wantagent_innerkits", "//base/miscservices/time/services:time_service", - "//foundation/aafwk/standard/interfaces/innerkits/want:want", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base:appexecfwk_base", "//foundation/appexecfwk/standard/kits:appkit_native", - "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/jsoncpp:jsoncpp", "//utils/native/base:utils", ] external_deps = [ + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "samgr_standard:samgr_proxy", ] diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 3909036..7ee1712 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -32,7 +32,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", @@ -76,16 +75,16 @@ 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 = [ + "aafwk_standard:want", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "multimedia_image_standard:image_native", "samgr_standard:samgr_proxy", ] diff --git a/frameworks/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn index 7121bed..8ca3077 100644 --- a/frameworks/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -60,17 +60,16 @@ ohos_shared_library("wantagent_innerkits") { 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/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 = [ + "aafwk_standard:ability_manager", + "aafwk_standard:want", + "appexecfwk_standard:appexecfwk_base", + "appexecfwk_standard:appexecfwk_core", "ces_standard:cesfwk_core", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 01c5cfa..3bd0904 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -35,7 +35,6 @@ 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", @@ -67,11 +66,7 @@ ohos_shared_library("notification") { "${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", @@ -79,9 +74,13 @@ ohos_shared_library("notification") { ] external_deps = [ + "aafwk_standard:base", + "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", + "dmsfwk_standard:zuri", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", + "napi:ace_napi", ] relative_install_dir = "module" diff --git a/interfaces/kits/napi/wantagent/BUILD.gn b/interfaces/kits/napi/wantagent/BUILD.gn index 8e9f83c..fee5ef1 100644 --- a/interfaces/kits/napi/wantagent/BUILD.gn +++ b/interfaces/kits/napi/wantagent/BUILD.gn @@ -20,12 +20,8 @@ ohos_shared_library("wantagent") { "//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/services/abilitymgr/include", "//foundation/aafwk/standard/interfaces/kits/napi/aafwk/inner/napi_common", "//foundation/aafwk/standard/services/common/include", @@ -40,22 +36,21 @@ 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/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:base", "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", "appexecfwk_standard:appexecfwk_core", "appexecfwk_standard: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/services/ans/BUILD.gn b/services/ans/BUILD.gn index 3af7750..e38cb70 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -21,9 +21,6 @@ group("ans_targets") { config("public_ans_config") { include_dirs = [ "${services_path}/ans/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", - "//foundation/appexecfwk/standard/interfaces/innerkits/libeventhandler/include", - "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", "//base/account/os_account/interfaces/innerkits/osaccount/native/include", "//base/account/os_account/frameworks/common/database/include/", @@ -67,9 +64,7 @@ ohos_shared_library("libans") { "//base/account/os_account/frameworks/osaccount/native:os_account_innerkits", "//base/miscservices/time/services:time_service", "//foundation/aafwk/standard/services/abilitymgr:abilityms", - "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata:distributeddata_inner", "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr:distributedschedsvr", - "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//utils/native/base:utils", ] @@ -77,7 +72,10 @@ ohos_shared_library("libans") { cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] } - external_deps = [] + external_deps = [ + "distributeddatamgr:distributeddata_inner", + "multimedia_image_standard:image_native", + ] external_deps += ans_standard_external_deps subsystem_name = "notification" -- Gitee From 1153faa7ee2619607299490493be0ae9056f92f9 Mon Sep 17 00:00:00 2001 From: fangjinliang1 Date: Mon, 17 Jan 2022 11:57:29 +0800 Subject: [PATCH 089/131] modify multi users Signed-off-by: fangjinliang1 Change-Id: I932664d90f9a1e75f421b9380ab9b6d66487f1d7 --- services/ans/src/advanced_notification_service.cpp | 6 ++++-- services/ans/src/notification_subscriber_manager.cpp | 3 +-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 953a519..8f2af8f 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -798,16 +798,18 @@ ErrCode AdvancedNotificationService::DeleteAll() 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) { sptr notification = nullptr; result = RemoveFromNotificationListForDeleteAll(key, notification); - if (result != ERR_OK) { + 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(); diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 1e850b7..f6a4e94 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -206,8 +206,7 @@ void NotificationSubscriberManager::AddRecordInfo( record->subscribedAll = false; } record->userId = subscribeInfo->GetAppUserId(); - if (record->userId == SUBSCRIBE_USER_INIT || - (record->userId >= SUBSCRIBE_USER_SYSTEM_BEGIN && record->userId <= SUBSCRIBE_USER_SYSTEM_END)) { + if (record->userId == SUBSCRIBE_USER_INIT) { record->userId = SUBSCRIBE_USER_ALL; } } else { -- Gitee From 96347e94f485a82932607dbd6a651a4544a186fc Mon Sep 17 00:00:00 2001 From: njupthan Date: Mon, 17 Jan 2022 22:36:20 +0800 Subject: [PATCH 090/131] Distributed notification Signed-off-by: njupthan --- bundle.json | 1 + frameworks/ans/core/BUILD.gn | 4 + .../core/common/include/ans_const_define.h | 3 +- .../core/common/include/ans_inner_errors.h | 2 + frameworks/ans/core/include/ans_image_util.h | 52 ++ .../ans/core/include/ans_manager_interface.h | 11 + .../ans/core/include/ans_manager_proxy.h | 6 + .../ans/core/include/ans_manager_stub.h | 13 + .../ans/core/include/ans_notification.h | 54 +- frameworks/ans/core/src/ans_image_util.cpp | 215 +++++++ frameworks/ans/core/src/ans_manager_proxy.cpp | 165 +++++ frameworks/ans/core/src/ans_manager_stub.cpp | 142 +++++ frameworks/ans/core/src/ans_notification.cpp | 90 ++- frameworks/ans/native/BUILD.gn | 7 + frameworks/ans/native/src/message_user.cpp | 59 +- frameworks/ans/native/src/notification.cpp | 61 +- .../native/src/notification_action_button.cpp | 63 ++ .../native/src/notification_basic_content.cpp | 30 + .../native/src/notification_bundle_option.cpp | 2 +- .../ans/native/src/notification_content.cpp | 93 +++ .../notification_conversational_content.cpp | 81 +++ .../notification_conversational_message.cpp | 65 ++ .../src/notification_distributed_options.cpp | 163 +++++ .../ans/native/src/notification_helper.cpp | 29 +- .../src/notification_long_text_content.cpp | 45 ++ .../native/src/notification_media_content.cpp | 35 ++ .../src/notification_multiline_content.cpp | 45 ++ .../src/notification_normal_content.cpp | 24 + .../src/notification_picture_content.cpp | 47 ++ .../ans/native/src/notification_request.cpp | 587 +++++++++++++---- .../ans/native/src/notification_sorting.cpp | 2 +- .../native/src/notification_subscriber.cpp | 4 +- .../native/src/notification_user_input.cpp | 71 ++- frameworks/ans/test/moduletest/BUILD.gn | 116 ++-- .../test/moduletest/ans_fw_module_test.cpp | 462 +++++++++++++- .../ans_innerkits_module_publish_test.cpp | 109 ++++ .../mock/distributed_kv_data_manager.cpp | 23 + .../mock/include/mock_single_kv_store.h | 23 + .../mock/mock_change_notification.cpp | 62 ++ .../mock/mock_common_event_data.cpp | 36 ++ .../mock/mock_common_event_manager.cpp | 61 ++ .../moduletest/mock/mock_single_kv_store.cpp | 124 +++- frameworks/wantagent/BUILD.gn | 1 + frameworks/wantagent/src/pending_want.cpp | 7 + .../wantagent/src/want_agent_helper.cpp | 98 +++ .../ans/native/include/message_user.h | 17 +- .../ans/native/include/notification.h | 19 +- .../include/notification_action_button.h | 16 +- .../include/notification_basic_content.h | 16 +- .../ans/native/include/notification_content.h | 18 +- .../notification_conversational_content.h | 14 + .../notification_conversational_message.h | 16 +- .../notification_distributed_options.h | 127 ++++ .../ans/native/include/notification_helper.h | 54 +- .../include/notification_json_convert.h | 97 +++ .../include/notification_long_text_content.h | 13 + .../include/notification_media_content.h | 13 + .../include/notification_multiline_content.h | 13 + .../include/notification_normal_content.h | 13 + .../include/notification_picture_content.h | 13 + .../ans/native/include/notification_request.h | 59 +- .../ans/native/include/notification_sorting.h | 2 +- .../native/include/notification_user_input.h | 16 +- .../wantagent/include/pending_want.h | 2 + .../wantagent/include/want_agent_helper.h | 19 +- interfaces/kits/napi/ans/BUILD.gn | 2 + interfaces/kits/napi/ans/include/common.h | 17 +- .../kits/napi/ans/include/distributed.h | 33 + interfaces/kits/napi/ans/src/common.cpp | 183 ++++++ .../kits/napi/ans/src/display_badge.cpp | 6 +- interfaces/kits/napi/ans/src/distributed.cpp | 489 +++++++++++++++ interfaces/kits/napi/ans/src/disturb_mode.cpp | 14 +- interfaces/kits/napi/ans/src/init.cpp | 6 + notification.gni | 2 + services/BUILD.gn | 6 + services/ans/BUILD.gn | 8 + .../include/advanced_notification_service.h | 26 + services/ans/include/bundle_manager_helper.h | 2 +- services/ans/include/notification_record.h | 5 + services/ans/include/system_event_observer.h | 2 +- .../ans/src/advanced_notification_service.cpp | 592 +++++++++++++++++- services/ans/src/bundle_manager_helper.cpp | 2 +- .../src/notification_preferences_database.cpp | 4 +- .../src/notification_subscriber_manager.cpp | 1 - services/ans/test/unittest/BUILD.gn | 8 + .../advanced_notification_service_test.cpp | 1 - services/distributed/BUILD.gn | 58 ++ .../include/distributed_database.h | 71 +++ .../include/distributed_database_callback.h | 45 ++ .../include/distributed_device_callback.h | 45 ++ .../include/distributed_flow_control.h | 52 ++ .../distributed_notification_manager.h | 104 +++ .../include/distributed_preferences.h | 60 ++ .../distributed_preferences_database.h | 60 ++ .../include/distributed_preferences_info.h | 40 ++ .../distributed/src/distributed_database.cpp | 322 ++++++++++ .../src/distributed_database_callback.cpp | 64 ++ .../src/distributed_device_callback.cpp | 50 ++ .../src/distributed_flow_control.cpp | 94 +++ .../src/distributed_notification_manager.cpp | 424 +++++++++++++ .../src/distributed_preferences.cpp | 195 ++++++ .../src/distributed_preferences_database.cpp | 192 ++++++ .../src/distributed_preferences_info.cpp | 54 ++ services/distributed/test/unittest/BUILD.gn | 79 +++ .../unittest/distributed_database_test.cpp | 193 ++++++ .../distributed_notification_manager_test.cpp | 184 ++++++ .../unittest/distributed_preferences_test.cpp | 105 ++++ .../mock/ans_test_single_kv_store.cpp | 208 ++++++ .../unittest/mock/ans_test_single_kv_store.h | 117 ++++ .../test/unittest/mock/mock_blob.cpp | 107 ++++ .../unittest/mock/mock_changeNotification.cpp | 57 ++ .../mock/mock_change_notification.cpp | 57 ++ .../mock/mock_distributed_kv_data_manager.cpp | 88 +++ .../test/unittest/mock/mock_event_handler.cpp | 109 ++++ .../test/unittest/mock/mock_event_runner.cpp | 30 + .../test/unittest/mock/mock_inner_event.cpp | 28 + services/test/moduletest/ans_module_test.cpp | 54 +- tools/dump/src/notification_shell_command.cpp | 1 - 118 files changed, 8416 insertions(+), 290 deletions(-) create mode 100644 frameworks/ans/core/include/ans_image_util.h create mode 100644 frameworks/ans/core/src/ans_image_util.cpp create mode 100644 frameworks/ans/native/src/notification_distributed_options.cpp create mode 100644 frameworks/ans/test/moduletest/mock/mock_change_notification.cpp create mode 100644 frameworks/ans/test/moduletest/mock/mock_common_event_data.cpp create mode 100644 frameworks/ans/test/moduletest/mock/mock_common_event_manager.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_distributed_options.h create mode 100644 interfaces/innerkits/ans/native/include/notification_json_convert.h create mode 100644 interfaces/kits/napi/ans/include/distributed.h create mode 100644 interfaces/kits/napi/ans/src/distributed.cpp create mode 100644 services/distributed/BUILD.gn create mode 100644 services/distributed/include/distributed_database.h create mode 100644 services/distributed/include/distributed_database_callback.h create mode 100644 services/distributed/include/distributed_device_callback.h create mode 100644 services/distributed/include/distributed_flow_control.h create mode 100644 services/distributed/include/distributed_notification_manager.h create mode 100644 services/distributed/include/distributed_preferences.h create mode 100644 services/distributed/include/distributed_preferences_database.h create mode 100644 services/distributed/include/distributed_preferences_info.h create mode 100644 services/distributed/src/distributed_database.cpp create mode 100644 services/distributed/src/distributed_database_callback.cpp create mode 100644 services/distributed/src/distributed_device_callback.cpp create mode 100644 services/distributed/src/distributed_flow_control.cpp create mode 100644 services/distributed/src/distributed_notification_manager.cpp create mode 100644 services/distributed/src/distributed_preferences.cpp create mode 100644 services/distributed/src/distributed_preferences_database.cpp create mode 100644 services/distributed/src/distributed_preferences_info.cpp create mode 100644 services/distributed/test/unittest/BUILD.gn create mode 100644 services/distributed/test/unittest/distributed_database_test.cpp create mode 100644 services/distributed/test/unittest/distributed_notification_manager_test.cpp create mode 100644 services/distributed/test/unittest/distributed_preferences_test.cpp create mode 100644 services/distributed/test/unittest/mock/ans_test_single_kv_store.cpp create mode 100644 services/distributed/test/unittest/mock/ans_test_single_kv_store.h create mode 100644 services/distributed/test/unittest/mock/mock_blob.cpp create mode 100644 services/distributed/test/unittest/mock/mock_changeNotification.cpp create mode 100644 services/distributed/test/unittest/mock/mock_change_notification.cpp create mode 100644 services/distributed/test/unittest/mock/mock_distributed_kv_data_manager.cpp create mode 100644 services/distributed/test/unittest/mock/mock_event_handler.cpp create mode 100644 services/distributed/test/unittest/mock/mock_event_runner.cpp create mode 100644 services/distributed/test/unittest/mock/mock_inner_event.cpp diff --git a/bundle.json b/bundle.json index 0319b7b..9dab743 100644 --- a/bundle.json +++ b/bundle.json @@ -81,6 +81,7 @@ "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", diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 8ea2b3b..ca0915a 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -27,8 +27,10 @@ config("public_ans_core_config") { "${core_path}/include", "${interfaces_path}/innerkits/ans/native/include", "${interfaces_path}/innerkits/wantAgent/include", + "//foundation/aafwk/standard/frameworks/kits/content/cpp/src/ohos/aafwk/content/", "//foundation/multimedia/image_standard/interfaces/innerkits/include", "//utils/native/base/include", + "//third_party/json/single_include", "//third_party/jsoncpp/include", ] @@ -38,6 +40,7 @@ config("public_ans_core_config") { 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", @@ -53,6 +56,7 @@ 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_helper.cpp", "${frameworks_path}/ans/native/src/notification_long_text_content.cpp", diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index bda3a1f..a38245a 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -20,6 +20,8 @@ #include "uri.h" +#include "notification_constant.h" + namespace OHOS { namespace Notification { // Max active notification number @@ -44,7 +46,6 @@ const static std::vector DEFAULT_NOTIFICATION_VIBRATION = {200}; // Default path for template const static std::string DEFAULT_TEMPLATE_PATH("/system/etc/external.json"); - } // 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 63d35c8..c205fea 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -70,6 +70,8 @@ enum ErrorCode : uint32_t { 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, }; } // 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 0000000..57a5de9 --- /dev/null +++ b/frameworks/ans/core/include/ans_image_util.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_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_interface.h b/frameworks/ans/core/include/ans_manager_interface.h index f43d0df..76a9ebc 100644 --- a/frameworks/ans/core/include/ans_manager_interface.h +++ b/frameworks/ans/core/include/ans_manager_interface.h @@ -111,6 +111,12 @@ public: 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 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; @@ -175,6 +181,11 @@ protected: 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, SHELL_DUMP, PUBLISH_CONTINUOUS_TASK_NOTIFICATION, CANCEL_CONTINUOUS_TASK_NOTIFICATION, diff --git a/frameworks/ans/core/include/ans_manager_proxy.h b/frameworks/ans/core/include/ans_manager_proxy.h index 0c58d0b..0f590eb 100644 --- a/frameworks/ans/core/include/ans_manager_proxy.h +++ b/frameworks/ans/core/include/ans_manager_proxy.h @@ -98,6 +98,12 @@ public: 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 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; diff --git a/frameworks/ans/core/include/ans_manager_stub.h b/frameworks/ans/core/include/ans_manager_stub.h index 0316ea1..ce61b64 100644 --- a/frameworks/ans/core/include/ans_manager_stub.h +++ b/frameworks/ans/core/include/ans_manager_stub.h @@ -103,6 +103,14 @@ public: 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 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; @@ -164,6 +172,11 @@ 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); diff --git a/frameworks/ans/core/include/ans_notification.h b/frameworks/ans/core/include/ans_notification.h index 7ea2f0d..afd9e53 100644 --- a/frameworks/ans/core/include/ans_notification.h +++ b/frameworks/ans/core/include/ans_notification.h @@ -593,7 +593,7 @@ public: * @param doNotDisturbDate Indicates the do not disturb time to set. * @return Returns set do not disturb time result. */ - ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate & doNotDisturbDate); + ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate); /** * Obtains the do not disturb time. @@ -602,7 +602,7 @@ public: * @param doNotDisturbDate Indicates the do not disturb time to get. * @return Returns set do not disturb time result. */ - ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate & doNotDisturbDate); + ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); /** * Obtains the flag that whether to support do not disturb mode. @@ -612,6 +612,56 @@ public: */ 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); + /** * Publishes a continuous task notification. * @param request Indicates the NotificationRequest object for setting the notification content. 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 0000000..d58b015 --- /dev/null +++ b/frameworks/ans/core/src/ans_image_util.cpp @@ -0,0 +1,215 @@ +/* + * 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_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 e06b9e2..9090eff 100644 --- a/frameworks/ans/core/src/ans_manager_proxy.cpp +++ b/frameworks/ans/core/src/ans_manager_proxy.cpp @@ -1842,6 +1842,171 @@ ErrCode AnsManagerProxy::DoesSupportDoNotDisturbMode(bool &doesSupport) 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::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { MessageParcel data; diff --git a/frameworks/ans/core/src/ans_manager_stub.cpp b/frameworks/ans/core/src/ans_manager_stub.cpp index 5344287..2c37310 100644 --- a/frameworks/ans/core/src/ans_manager_stub.cpp +++ b/frameworks/ans/core/src/ans_manager_stub.cpp @@ -186,6 +186,21 @@ const std::map 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::HandleShellDump(MessageParcel &data, MessageParcel &reply) { std::string dumpOption; @@ -1743,6 +1855,36 @@ ErrCode AnsManagerStub::DoesSupportDoNotDisturbMode(bool &doesSupport) 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::ShellDump(const std::string &dumpOption, std::vector &dumpInfo) { ANS_LOGW("AnsManagerStub::ShellDump called!"); diff --git a/frameworks/ans/core/src/ans_notification.cpp b/frameworks/ans/core/src/ans_notification.cpp index 8087f3b..ea4fc3c 100644 --- a/frameworks/ans/core/src/ans_notification.cpp +++ b/frameworks/ans/core/src/ans_notification.cpp @@ -210,6 +210,10 @@ ErrCode AnsNotification::PublishNotification(const std::string &label, const Not ANS_LOGE("Failed to create NotificationRequest ptr"); return ERR_ANS_NO_MEMORY; } + if ((reqPtr->GetNotificationType() == NotificationContent::Type::CONVERSATION) || + (reqPtr->GetNotificationType() == NotificationContent::Type::PICTURE)) { + reqPtr->SetDistributed(false); + } return ansManagerProxy_->Publish(label, reqPtr); } @@ -220,6 +224,13 @@ ErrCode AnsNotification::PublishNotification(const NotificationRequest &request, return ERR_ANS_INVALID_PARAM; } + if (!deviceId.empty() && + ((request.GetNotificationType() == NotificationContent::Type::CONVERSATION) || + (request.GetNotificationType() == NotificationContent::Type::PICTURE))) { + 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."); @@ -362,6 +373,10 @@ ErrCode AnsNotification::PublishNotificationAsBundle( ANS_LOGE("Failed to create NotificationRequest ptr"); return ERR_ANS_NO_MEMORY; } + if ((reqPtr->GetNotificationType() == NotificationContent::Type::CONVERSATION) || + (reqPtr->GetNotificationType() == NotificationContent::Type::PICTURE)) { + reqPtr->SetDistributed(false); + } return ansManagerProxy_->PublishAsBundle(reqPtr, representativeBundle); } @@ -820,6 +835,23 @@ ErrCode AnsNotification::DoesSupportDoNotDisturbMode(bool &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; @@ -827,11 +859,15 @@ ErrCode AnsNotification::PublishContinuousTaskNotification(const NotificationReq auto pReq = new (std::nothrow) NotificationRequest(request); if (pReq == nullptr) { - ANS_LOGE("create NotificationRequest failed."); + ANS_LOGE("Failed to create NotificationRequest ptr."); return ERR_ANS_NO_MEMORY; } sptr sptrReq(pReq); + if ((sptrReq->GetNotificationType() == NotificationContent::Type::CONVERSATION) || + (sptrReq->GetNotificationType() == NotificationContent::Type::PICTURE)) { + sptrReq->SetDistributed(false); + } return ansManagerProxy_->PublishContinuousTaskNotification(sptrReq); } @@ -845,6 +881,58 @@ ErrCode AnsNotification::CancelContinuousTaskNotification(const std::string &lab 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); +} + void AnsNotification::ResetAnsManagerProxy() { ANS_LOGI("enter"); diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 7ee1712..04783c8 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -25,6 +25,12 @@ config("ans_innerkits_public_config") { "${interfaces_path}/ans/native/include", "${frameworks_path}/ans/core/common/include", "${frameworks_path}/ans/core/include", + "//foundation/aafwk/standard/frameworks/kits/content/cpp/src/ohos/aafwk/content/", + "//foundation/aafwk/standard/interfaces/innerkits/want/include/ohos/aafwk/content", + "//foundation/multimedia/image_standard/interfaces/innerkits/include", + "//third_party/json/single_include", + "//third_party/jsoncpp/include", + "//utils/system/safwk/native/include", ] configs = [ "${frameworks_path}/wantagent:wantagent_innerkits_public_config" ] } @@ -47,6 +53,7 @@ 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_helper.cpp", "src/notification_long_text_content.cpp", diff --git a/frameworks/ans/native/src/message_user.cpp b/frameworks/ans/native/src/message_user.cpp index 82a6425..385eafd 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() @@ -98,6 +97,60 @@ std::string MessageUser::Dump() const " }"; } +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 { if (!parcel.WriteString(key_)) { diff --git a/frameworks/ans/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index e0ab103..c146e54 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -25,7 +25,14 @@ 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) @@ -42,6 +49,7 @@ Notification::Notification(const Notification &other) vibrationStyle_ = other.vibrationStyle_; isRemoveAllowed_ = other.isRemoveAllowed_; sourceType_ = other.sourceType_; + deviceId_ = other.deviceId_; } Notification::~Notification() @@ -182,6 +190,11 @@ NotificationConstant::SourceType Notification::GetSourceType() const return sourceType_; } +std::string Notification::GetDeviceId() const +{ + return deviceId_; +} + int32_t Notification::GetUserId() const { if (request_ == nullptr) { @@ -229,6 +242,11 @@ bool Notification::MarshallingString(Parcel &parcel) const } } + if (!parcel.WriteString(deviceId_)) { + ANS_LOGE("Can't wirte deviceId"); + return false; + } + return true; } @@ -322,6 +340,9 @@ void Notification::ReadFromParcelString(Parcel &parcel) if (enableSound_) { sound_ = std::make_shared(parcel.ReadString()); } + + // Read deviceId_ + deviceId_ = parcel.ReadString(); } void Notification::ReadFromParcelInt32(Parcel &parcel) @@ -364,7 +385,7 @@ bool Notification::ReadFromParcel(Parcel &parcel) 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; @@ -413,12 +434,13 @@ void Notification::SetVibrationStyle(const std::vector &style) vibrationStyle_ = style; } -std::string Notification::GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id) +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(); } @@ -435,22 +457,23 @@ void Notification::SetSourceType(NotificationConstant::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_)) + - ", isRemoveAllowed = " + (isRemoveAllowed_ ? "true" : "false") + - ", sourceType = " + std::to_string(static_cast(sourceType_)) + - ",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 += ","; - } - return dump; + vibrationStyle += std::to_string(style); + vibrationStyle += ", "; + } + return "Notification{ " + "key = " + key_ + + ", ledLightColor = " + std::to_string(ledLightColor_) + + ", lockscreenVisbleness = " + std::to_string(static_cast(lockscreenVisibleness_)) + + ", 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 b129a54..ebe29e8 100644 --- a/frameworks/ans/native/src/notification_action_button.cpp +++ b/frameworks/ans/native/src/notification_action_button.cpp @@ -15,7 +15,10 @@ #include "notification_action_button.h" +#include "ans_image_util.h" #include "ans_log_wrapper.h" +#include "want_agent_helper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -73,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(), @@ -224,6 +232,61 @@ std::string NotificationActionButton::Dump() " }"; } +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 { if (!parcel.WriteString(title_)) { diff --git a/frameworks/ans/native/src/notification_basic_content.cpp b/frameworks/ans/native/src/notification_basic_content.cpp index 4942104..0ab51a5 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 402d186..7e83ebb 100644 --- a/frameworks/ans/native/src/notification_bundle_option.cpp +++ b/frameworks/ans/native/src/notification_bundle_option.cpp @@ -70,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_content.cpp b/frameworks/ans/native/src/notification_content.cpp index f76e41e..4ece6f6 100644 --- a/frameworks/ans/native/src/notification_content.cpp +++ b/frameworks/ans/native/src/notification_content.cpp @@ -112,6 +112,53 @@ std::string NotificationContent::Dump() " }"; } +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 { if (!parcel.WriteInt32(static_cast(contentType_))) { @@ -192,5 +239,51 @@ bool NotificationContent::ReadFromParcel(Parcel &parcel) 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; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_conversational_content.cpp b/frameworks/ans/native/src/notification_conversational_content.cpp index 1378513..08f3599 100644 --- a/frameworks/ans/native/src/notification_conversational_content.cpp +++ b/frameworks/ans/native/src/notification_conversational_content.cpp @@ -93,6 +93,87 @@ std::string NotificationConversationalContent::Dump() " }"; } +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 { if (!NotificationBasicContent::Marshalling(parcel)) { diff --git a/frameworks/ans/native/src/notification_conversational_message.cpp b/frameworks/ans/native/src/notification_conversational_message.cpp index 1f385c0..520a5fb 100644 --- a/frameworks/ans/native/src/notification_conversational_message.cpp +++ b/frameworks/ans/native/src/notification_conversational_message.cpp @@ -65,6 +65,71 @@ std::string NotificationConversationalMessage::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 { if (!parcel.WriteInt64(arrivedTime_)) { 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 0000000..dceabd5 --- /dev/null +++ b/frameworks/ans/native/src/notification_distributed_options.cpp @@ -0,0 +1,163 @@ +/* + * 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_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_helper.cpp b/frameworks/ans/native/src/notification_helper.cpp index 7f0bc36..4cf4afa 100644 --- a/frameworks/ans/native/src/notification_helper.cpp +++ b/frameworks/ans/native/src/notification_helper.cpp @@ -307,12 +307,12 @@ ErrCode NotificationHelper::RemoveGroupByBundle( return DelayedSingleton::GetInstance()->RemoveGroupByBundle(bundleOption, groupName); } -ErrCode NotificationHelper::SetDoNotDisturbDate(const NotificationDoNotDisturbDate & doNotDisturbDate) +ErrCode NotificationHelper::SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate) { return DelayedSingleton::GetInstance()->SetDoNotDisturbDate(doNotDisturbDate); } -ErrCode NotificationHelper::GetDoNotDisturbDate(NotificationDoNotDisturbDate & doNotDisturbDate) +ErrCode NotificationHelper::GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate) { return DelayedSingleton::GetInstance()->GetDoNotDisturbDate(doNotDisturbDate); } @@ -322,6 +322,31 @@ 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::PublishContinuousTaskNotification(const NotificationRequest &request) { return DelayedSingleton::GetInstance()->PublishContinuousTaskNotification(request); diff --git a/frameworks/ans/native/src/notification_long_text_content.cpp b/frameworks/ans/native/src/notification_long_text_content.cpp index 0e242fe..7abf074 100644 --- a/frameworks/ans/native/src/notification_long_text_content.cpp +++ b/frameworks/ans/native/src/notification_long_text_content.cpp @@ -71,6 +71,51 @@ std::string NotificationLongTextContent::Dump() " }"; } +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 { if (!NotificationBasicContent::Marshalling(parcel)) { diff --git a/frameworks/ans/native/src/notification_media_content.cpp b/frameworks/ans/native/src/notification_media_content.cpp index 6c3862c..d65672e 100644 --- a/frameworks/ans/native/src/notification_media_content.cpp +++ b/frameworks/ans/native/src/notification_media_content.cpp @@ -52,6 +52,41 @@ std::string NotificationMediaContent::Dump() " }"; } +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 { if (!NotificationBasicContent::Marshalling(parcel)) { diff --git a/frameworks/ans/native/src/notification_multiline_content.cpp b/frameworks/ans/native/src/notification_multiline_content.cpp index 299ac90..ef11f4f 100644 --- a/frameworks/ans/native/src/notification_multiline_content.cpp +++ b/frameworks/ans/native/src/notification_multiline_content.cpp @@ -72,6 +72,51 @@ std::string NotificationMultiLineContent::Dump() " }"; } +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 { if (!NotificationBasicContent::Marshalling(parcel)) { diff --git a/frameworks/ans/native/src/notification_normal_content.cpp b/frameworks/ans/native/src/notification_normal_content.cpp index d6743d1..a65c134 100644 --- a/frameworks/ans/native/src/notification_normal_content.cpp +++ b/frameworks/ans/native/src/notification_normal_content.cpp @@ -14,6 +14,7 @@ */ #include "notification_normal_content.h" +#include "ans_log_wrapper.h" namespace OHOS { namespace Notification { @@ -22,6 +23,29 @@ std::string NotificationNormalContent::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 { return NotificationBasicContent::Marshalling(parcel); diff --git a/frameworks/ans/native/src/notification_picture_content.cpp b/frameworks/ans/native/src/notification_picture_content.cpp index d7e65d4..e683c53 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 { @@ -57,6 +58,52 @@ std::string NotificationPictureContent::Dump() " }"; } +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 { if (!NotificationBasicContent::Marshalling(parcel)) { diff --git a/frameworks/ans/native/src/notification_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 10343c0..29d6657 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -15,7 +15,10 @@ #include "notification_request.h" +#include "ans_image_util.h" #include "ans_log_wrapper.h" +#include "want_agent_helper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -57,124 +60,14 @@ NotificationRequest::NotificationRequest(const std::shared_ptrnotificationId_ = 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_; - - 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_; - - this->notificationTemplate_ = other.notificationTemplate_; + 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->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_; - - 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_; - - this->notificationTemplate_ = other.notificationTemplate_; + CopyBase(other); + CopyOther(other); return *this; } @@ -719,6 +612,26 @@ 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; @@ -773,9 +686,108 @@ std::string NotificationRequest::Dump() ", 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() + " }"; } +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; + } + + return pRequest; +} + bool NotificationRequest::Marshalling(Parcel &parcel) const { // write int @@ -1105,6 +1117,11 @@ 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"); @@ -1312,6 +1329,13 @@ 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()); @@ -1342,5 +1366,340 @@ std::shared_ptr NotificationRequest::GetTemplate() const { return notificationTemplate_; } + +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->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_; + + this->distributedOptions_ = other.distributedOptions_; + + this->notificationTemplate_ = other.notificationTemplate_; +} + +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; + + 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; +} } // namespace Notification } // namespace OHOS diff --git a/frameworks/ans/native/src/notification_sorting.cpp b/frameworks/ans/native/src/notification_sorting.cpp index 4e0c410..575141d 100644 --- a/frameworks/ans/native/src/notification_sorting.cpp +++ b/frameworks/ans/native/src/notification_sorting.cpp @@ -40,7 +40,7 @@ NotificationSorting::NotificationSorting(const NotificationSorting &sorting) void NotificationSorting::SetSlot(const sptr &slot) { if (slot == nullptr) { - slot_ = new NotificationSlot(NotificationConstant::SlotType::OTHER); + slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); return; } slot_ = slot; diff --git a/frameworks/ans/native/src/notification_subscriber.cpp b/frameworks/ans/native/src/notification_subscriber.cpp index d1be623..291bc9a 100644 --- a/frameworks/ans/native/src/notification_subscriber.cpp +++ b/frameworks/ans/native/src/notification_subscriber.cpp @@ -22,7 +22,7 @@ namespace OHOS { namespace Notification { NotificationSubscriber::NotificationSubscriber() { - impl_ = new SubscriberImpl(*this); + impl_ = new (std::nothrow) SubscriberImpl(*this); }; NotificationSubscriber::~NotificationSubscriber() @@ -35,7 +35,7 @@ const sptr NotificationSubscriber::GetIm NotificationSubscriber::SubscriberImpl::SubscriberImpl(NotificationSubscriber &subscriber) : subscriber_(subscriber) { - recipient_ = new DeathRecipient(*this); + recipient_ = new (std::nothrow) DeathRecipient(*this); }; void NotificationSubscriber::SubscriberImpl::OnConnected() diff --git a/frameworks/ans/native/src/notification_user_input.cpp b/frameworks/ans/native/src/notification_user_input.cpp index eb0387f..335b874 100644 --- a/frameworks/ans/native/src/notification_user_input.cpp +++ b/frameworks/ans/native/src/notification_user_input.cpp @@ -16,6 +16,7 @@ #include "notification_user_input.h" #include "ans_log_wrapper.h" +#include "want_params_wrapper.h" namespace OHOS { namespace Notification { @@ -227,6 +228,74 @@ std::string NotificationUserInput::Dump() " }"; } +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 { if (!parcel.WriteString(inputKey_)) { @@ -337,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/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index ed922f4..a003ec2 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -53,7 +53,7 @@ ohos_moduletest("ans_fw_module_test") { "//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", @@ -69,17 +69,14 @@ ohos_moduletest("ans_fw_module_test") { ] 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", ] @@ -100,10 +97,15 @@ ohos_moduletest("ans_fw_module_test") { "//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", @@ -124,9 +126,14 @@ 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", + "//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", @@ -135,24 +142,22 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//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", "${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", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log/", ] sources = [ @@ -161,12 +166,17 @@ 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", @@ -186,6 +196,12 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "//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", @@ -206,9 +222,14 @@ 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", + "//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", @@ -217,23 +238,22 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "//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", "${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", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log/", ] sources = [ @@ -242,6 +262,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", ] @@ -260,10 +283,17 @@ ohos_moduletest("ans_innerkits_module_slot_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", @@ -284,9 +314,14 @@ 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", + "//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", @@ -295,23 +330,22 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "//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", "${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", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/autils/", + "//foundation/distributeddatamgr/distributeddatamgr/services/distributeddataservice/adapter/include/log/", ] sources = [ @@ -320,6 +354,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", ] @@ -338,10 +375,17 @@ ohos_moduletest("ans_innerkits_module_setting_test") { "//foundation/distributedschedule/dmsfwk/interfaces/innerkits/uri:zuri", "//foundation/distributedschedule/safwk/interfaces/innerkits/safwk:system_ability_fwk", "//foundation/distributedschedule/samgr/interfaces/innerkits/samgr_proxy:samgr_proxy", + "//foundation/multimedia/image_standard/interfaces/innerkits:image_native", "//third_party/googletest:gtest_main", "//utils/native/base:utils", ] + defines = [] + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + } + external_deps = [ "aafwk_standard:want", "appexecfwk_standard:appexecfwk_base", diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index 741f7d5..34930d2 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -26,9 +26,12 @@ #include "ans_const_define.h" #include "ans_inner_errors.h" #include "ans_manager_proxy.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" @@ -48,6 +51,11 @@ 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; @@ -326,6 +334,86 @@ 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_NOTIFICATION_STORE_ID}; + std::shared_ptr pointer = + DistributedKv::AnsTestSingleKvStore::GetMockKvStorePointer( + {KVSTORE_APP_ID}, {KVSTORE_SCREEN_STATUS_STORE_ID}); + DistributedKv::Key key("" + DELIMITER + "screen_status"); + DistributedKv::Value value(isScreenOn ? "on" : "off"); + pointer->Put(key, value); + } }; class EventParser { @@ -550,7 +638,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_FlowControl_00100, Function | MediumTest | L 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); @@ -606,7 +694,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_RemoveNotificaitonsByKey_00100, Function | M 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); @@ -879,7 +967,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelNotificationById_00100, Function | Med 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); @@ -974,7 +1062,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | Med 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); @@ -986,7 +1074,7 @@ HWTEST_F(AnsFWModuleTest, ANS_FW_MT_CancelAllNotifications_00100, Function | Med 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); @@ -1546,6 +1634,368 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_DoNotDisturb_07000, Function | Medium 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_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(); +} +#endif + HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07100, Function | MediumTest | Level1) { IPCSkeleton::SetCallingUid(SYSTEM_SERVICE_UID); @@ -1800,4 +2250,4 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07800, Function IPCSkeleton::SetCallingUid(1); } } // namespace Notification -} // namespace OHOS +} // 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 5f3f342..56cf177 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -23,6 +23,7 @@ #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" @@ -394,6 +395,7 @@ public: void WaitOnSubscribeResult(); void WaitOnConsumed(); void WaitOnUnsubscribeResult(); + void CheckJsonConverter(const NotificationRequest *request); }; void AnsInterfaceModulePublishTest::SetUpTestCase() @@ -470,6 +472,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 @@ -1220,5 +1258,76 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_04000, Function EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); WaitOnUnsubscribeResult(); } + +/** + * @tc.number : ANS_Interface_MT_Publish_08000 + * @tc.name : Publish_08000 + * @tc.desc : . + * @tc.expected : . + */ +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); +} } // namespace Notification } // namespace OHOS \ No newline at end of file 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 a223023..86852f1 100644 --- a/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp +++ b/frameworks/ans/test/moduletest/mock/distributed_kv_data_manager.cpp @@ -33,6 +33,7 @@ Status DistributedKvDataManager::GetSingleKvStore(const Options &options, const { std::string storeIdTmp = Constant::TrimCopy(storeId.storeId); kvStore = std::make_shared(); + AnsTestSingleKvStore::InsertMockKvStore(appId, storeId, kvStore); return Status::SUCCESS; } @@ -48,6 +49,28 @@ Status DistributedKvDataManager::CloseKvStore(const AppId &appId, std::shared_pt 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_single_kv_store.h b/frameworks/ans/test/moduletest/mock/include/mock_single_kv_store.h index 0194762..e71772f 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" @@ -106,8 +107,30 @@ public: 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, 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_change_notification.cpp b/frameworks/ans/test/moduletest/mock/mock_change_notification.cpp new file mode 100644 index 0000000..e076799 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_change_notification.cpp @@ -0,0 +1,62 @@ +/* + * 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 "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 0000000..335ae00 --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_common_event_data.cpp @@ -0,0 +1,36 @@ +/* + * 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 "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 0000000..590297e --- /dev/null +++ b/frameworks/ans/test/moduletest/mock/mock_common_event_manager.cpp @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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_single_kv_store.cpp b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp index 3f6d34b..d09801b 100644 --- a/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_single_kv_store.cpp @@ -14,12 +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; } @@ -38,14 +129,14 @@ Status AnsTestSingleKvStore::GetResultSet(const Key &prefixKey, std::shared_ptr< return Status::SUCCESS; } -Status AnsTestSingleKvStore::GetResultSetWithQuery(const std::string &query, - std::shared_ptr &resultSet) const +Status AnsTestSingleKvStore::GetResultSetWithQuery( + const std::string &query, std::shared_ptr &resultSet) const { return Status::SUCCESS; } -Status AnsTestSingleKvStore::GetResultSetWithQuery(const DataQuery &query, - std::shared_ptr &resultSet) const +Status AnsTestSingleKvStore::GetResultSetWithQuery( + const DataQuery &query, std::shared_ptr &resultSet) const { return Status::SUCCESS; } @@ -73,6 +164,8 @@ Status AnsTestSingleKvStore::Sync( Status AnsTestSingleKvStore::RemoveDeviceData(const std::string &device) { + kvstore_.clear(); + return Status::SUCCESS; } @@ -85,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; } @@ -190,8 +298,8 @@ Status AnsTestSingleKvStore::UnSubscribeWithQuery(const std::vector return Status::SUCCESS; } -Status AnsTestSingleKvStore::GetKvStoreSnapshot(std::shared_ptr observer, - std::shared_ptr &snapshot) const +Status AnsTestSingleKvStore::GetKvStoreSnapshot( + std::shared_ptr observer, std::shared_ptr &snapshot) const { return Status::NOT_SUPPORT; } diff --git a/frameworks/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn index 8ca3077..54be266 100644 --- a/frameworks/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -27,6 +27,7 @@ config("wantagent_innerkits_public_config") { "//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/frameworks/kits/content/cpp/src/ohos/aafwk/content/", "//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", diff --git a/frameworks/wantagent/src/pending_want.cpp b/frameworks/wantagent/src/pending_want.cpp index 56e1e4c..5781cde 100644 --- a/frameworks/wantagent/src/pending_want.cpp +++ b/frameworks/wantagent/src/pending_want.cpp @@ -408,4 +408,11 @@ 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 ba70251..7f3d0cb 100644 --- a/frameworks/wantagent/src/want_agent_helper.cpp +++ b/frameworks/wantagent/src/want_agent_helper.cpp @@ -19,6 +19,7 @@ #include "hilog_wrapper.h" #include "pending_want.h" #include "want_agent_log_wrapper.h" +#include "want_params_wrapper.h" #include "want_sender_info.h" #include "want_sender_interface.h" @@ -338,4 +339,101 @@ void WantAgentHelper::UnregisterCancelListener( 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/interfaces/innerkits/ans/native/include/message_user.h b/interfaces/innerkits/ans/native/include/message_user.h index 7c8dbda..93bb564 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. * diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index 1d40d79..5ad3ea0 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -31,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. * @@ -189,6 +197,13 @@ public: */ 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. * @@ -231,9 +246,10 @@ private: void SetPostTime(const int64_t &time); void SetSound(const Uri &sound); void SetVibrationStyle(const std::vector &style); + 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); - std::string GenerateNotificationKey(int32_t uid, const std::string &label, int32_t id); bool ReadFromParcel(Parcel &parcel); void ReadFromParcelBool(Parcel &parcel); void ReadFromParcelString(Parcel &parcel); @@ -252,6 +268,7 @@ private: bool enableViration_ {false}; bool isRemoveAllowed_ {true}; std::string key_ {""}; + std::string deviceId_ {""}; int32_t ledLightColor_ {0}; NotificationConstant::VisiblenessType lockscreenVisibleness_ {NotificationConstant::VisiblenessType::NO_OVERRIDE}; NotificationConstant::SourceType sourceType_ {NotificationConstant::SourceType::TYPE_NORMAL}; diff --git a/interfaces/innerkits/ans/native/include/notification_action_button.h b/interfaces/innerkits/ans/native/include/notification_action_button.h index a1a0f9a..1979223 100644 --- a/interfaces/innerkits/ans/native/include/notification_action_button.h +++ b/interfaces/innerkits/ans/native/include/notification_action_button.h @@ -17,6 +17,7 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_ACTION_BUTTON_H #include "notification_constant.h" +#include "notification_json_convert.h" #include "notification_user_input.h" #include "parcel.h" #include "pixel_map.h" @@ -24,7 +25,7 @@ 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. @@ -172,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 diff --git a/interfaces/innerkits/ans/native/include/notification_basic_content.h b/interfaces/innerkits/ans/native/include/notification_basic_content.h index c143154..65ccd08 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_content.h b/interfaces/innerkits/ans/native/include/notification_content.h index 9d5ebda..0923b9e 100644 --- a/interfaces/innerkits/ans/native/include/notification_content.h +++ b/interfaces/innerkits/ans/native/include/notification_content.h @@ -18,6 +18,7 @@ #include "notification_basic_content.h" #include "notification_conversational_content.h" +#include "notification_json_convert.h" #include "notification_long_text_content.h" #include "notification_media_content.h" #include "notification_multiline_content.h" @@ -27,7 +28,7 @@ namespace OHOS { namespace Notification { -class NotificationContent : public Parcelable { +class NotificationContent : public Parcelable, public NotificationJsonConvertionBase { public: enum class Type { /** @@ -145,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 @@ -170,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 e352651..9994974 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_content.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_content.h @@ -19,6 +19,7 @@ #include "message_user.h" #include "notification_basic_content.h" #include "notification_conversational_message.h" +#include "notification_json_convert.h" #include "parcel.h" namespace OHOS { @@ -104,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 d46aacc..b32fe9f 100644 --- a/interfaces/innerkits/ans/native/include/notification_conversational_message.h +++ b/interfaces/innerkits/ans/native/include/notification_conversational_message.h @@ -17,12 +17,13 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_CONVERSATIONAL_MESSAGE_H #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. @@ -81,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 0000000..132986c --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_distributed_options.h @@ -0,0 +1,127 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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_helper.h b/interfaces/innerkits/ans/native/include/notification_helper.h index fcf2459..28a20eb 100644 --- a/interfaces/innerkits/ans/native/include/notification_helper.h +++ b/interfaces/innerkits/ans/native/include/notification_helper.h @@ -594,7 +594,7 @@ public: * @param doNotDisturbDate Indicates the do not disturb time to set. * @return Returns set do not disturb time result. */ - static ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate & doNotDisturbDate); + static ErrCode SetDoNotDisturbDate(const NotificationDoNotDisturbDate &doNotDisturbDate); /** * Obtains the do not disturb time. @@ -603,7 +603,7 @@ public: * @param doNotDisturbDate Indicates the do not disturb time to get. * @return Returns set do not disturb time result. */ - static ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate & doNotDisturbDate); + static ErrCode GetDoNotDisturbDate(NotificationDoNotDisturbDate &doNotDisturbDate); /** * Obtains the flag that whether to support do not disturb mode. @@ -613,6 +613,56 @@ public: */ 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); + /** * Publishes a continuous task notification. * @param request Indicates the NotificationRequest object for setting the notification content. 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 0000000..0162f1b --- /dev/null +++ b/interfaces/innerkits/ans/native/include/notification_json_convert.h @@ -0,0 +1,97 @@ +/* + * 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_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 c6ffcb6..85d5001 100644 --- a/interfaces/innerkits/ans/native/include/notification_long_text_content.h +++ b/interfaces/innerkits/ans/native/include/notification_long_text_content.h @@ -86,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 54d90d2..5044fa8 100644 --- a/interfaces/innerkits/ans/native/include/notification_media_content.h +++ b/interfaces/innerkits/ans/native/include/notification_media_content.h @@ -76,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 a3d216f..7f0e916 100644 --- a/interfaces/innerkits/ans/native/include/notification_multiline_content.h +++ b/interfaces/innerkits/ans/native/include/notification_multiline_content.h @@ -83,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 cae7525..6bd04ae 100644 --- a/interfaces/innerkits/ans/native/include/notification_normal_content.h +++ b/interfaces/innerkits/ans/native/include/notification_normal_content.h @@ -39,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 df45286..8ed0dc5 100644 --- a/interfaces/innerkits/ans/native/include/notification_picture_content.h +++ b/interfaces/innerkits/ans/native/include/notification_picture_content.h @@ -82,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 f5efaff..c7f59f8 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -20,6 +20,8 @@ #include "message_user.h" #include "notification_action_button.h" #include "notification_content.h" +#include "notification_distributed_options.h" +#include "notification_json_convert.h" #include "notification_template.h" #include "ohos/aafwk/content/want_params.h" #include "parcel.h" @@ -28,7 +30,7 @@ namespace OHOS { namespace Notification { -class NotificationRequest : public Parcelable { +class NotificationRequest : public Parcelable, public NotificationJsonConvertionBase { public: enum class BadgeStyle { /** @@ -843,6 +845,30 @@ 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. @@ -861,6 +887,19 @@ public: */ 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 @@ -914,6 +953,21 @@ 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); + private: int32_t notificationId_ {0}; uint32_t color_ {NotificationRequest::COLOR_DEFAULT}; @@ -971,6 +1025,9 @@ private: std::vector> actionButtons_ {}; std::vector> messageUsers_ {}; std::vector userInputHistory_ {}; + + NotificationDistributedOptions distributedOptions_; + std::shared_ptr notificationTemplate_ {}; }; } // namespace Notification diff --git a/interfaces/innerkits/ans/native/include/notification_sorting.h b/interfaces/innerkits/ans/native/include/notification_sorting.h index cc02e74..ca38d5b 100644 --- a/interfaces/innerkits/ans/native/include/notification_sorting.h +++ b/interfaces/innerkits/ans/native/include/notification_sorting.h @@ -171,7 +171,7 @@ private: bool isHiddenNotification_ {}; std::string groupKeyOverride_ {}; int32_t visiblenessOverride_ {}; - sptr slot_ = new NotificationSlot(NotificationConstant::SlotType::OTHER); + sptr slot_ = new (std::nothrow) NotificationSlot(NotificationConstant::SlotType::OTHER); friend class AdvancedNotificationService; }; diff --git a/interfaces/innerkits/ans/native/include/notification_user_input.h b/interfaces/innerkits/ans/native/include/notification_user_input.h index e432cd2..2e68134 100644 --- a/interfaces/innerkits/ans/native/include/notification_user_input.h +++ b/interfaces/innerkits/ans/native/include/notification_user_input.h @@ -17,13 +17,14 @@ #define BASE_NOTIFICATION_ANS_STANDARD_KITS_NATIVE_INCLUDE_NOTIFICATION_USER_INPUT_H #include "notification_constant.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. @@ -213,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 diff --git a/interfaces/innerkits/wantagent/include/pending_want.h b/interfaces/innerkits/wantagent/include/pending_want.h index 1db00b7..4f03427 100644 --- a/interfaces/innerkits/wantagent/include/pending_want.h +++ b/interfaces/innerkits/wantagent/include/pending_want.h @@ -247,6 +247,8 @@ public: std::shared_ptr GetWant(const sptr &target); + std::shared_ptr GetWantSenderInfo(const sptr &target); + private: std::mutex lock_object; sptr target_; diff --git a/interfaces/innerkits/wantagent/include/want_agent_helper.h b/interfaces/innerkits/wantagent/include/want_agent_helper.h index 7f3027f..56e554f 100644 --- a/interfaces/innerkits/wantagent/include/want_agent_helper.h +++ b/interfaces/innerkits/wantagent/include/want_agent_helper.h @@ -22,6 +22,7 @@ #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" @@ -162,7 +163,23 @@ 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; diff --git a/interfaces/kits/napi/ans/BUILD.gn b/interfaces/kits/napi/ans/BUILD.gn index 3bd0904..90ada22 100644 --- a/interfaces/kits/napi/ans/BUILD.gn +++ b/interfaces/kits/napi/ans/BUILD.gn @@ -39,6 +39,7 @@ ohos_shared_library("notification") { "include", "//third_party/node/src", "//third_party/libuv/include", + "//third_party/json/single_include", "//third_party/jsoncpp/include", ] @@ -50,6 +51,7 @@ ohos_shared_library("notification") { "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", diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index 4f202eb..5cfe787 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -119,11 +119,6 @@ struct NotificationSubscribeInfo { bool hasSubscribeInfo = false; }; -struct BundleOption { - std::string bundle {}; - int uid {}; -}; - struct NotificationKey { int id {}; std::string label {}; @@ -186,6 +181,9 @@ public: 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); @@ -328,6 +326,15 @@ public: 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 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); diff --git a/interfaces/kits/napi/ans/include/distributed.h b/interfaces/kits/napi/ans/include/distributed.h new file mode 100644 index 0000000..02bb9d7 --- /dev/null +++ b/interfaces/kits/napi/ans/include/distributed.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_KITS_NAPI_INCLUDE_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); +} // 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/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 2864281..8849e7e 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -162,6 +162,52 @@ napi_value Common::ParseParaOnlyCallback(const napi_env &env, const napi_callbac 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); + + return NapiGetBoolean(env, true); +} + napi_value Common::SetNotification( const napi_env &env, const OHOS::Notification::Notification *notification, napi_value &result) { @@ -197,6 +243,14 @@ napi_value Common::SetNotification( napi_create_int32(env, notification->GetPid(), &value); napi_set_named_property(env, result, "creatorPid", value); + // 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); @@ -209,6 +263,10 @@ napi_value Common::SetNotification( 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); } @@ -1420,6 +1478,10 @@ napi_value Common::GetNotificationRequestByCustom( 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; @@ -2461,6 +2523,127 @@ napi_value Common::GetNotificationLargeIcon(const napi_env &env, const napi_valu 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; + napi_valuetype valuetype = napi_undefined; + napi_value supportDisplayDevices = nullptr; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + uint32_t length = 0; + + 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; + napi_valuetype valuetype = napi_undefined; + napi_value supportOperateDevices = nullptr; + char str[STR_MAX_SIZE] = {0}; + size_t strLen = 0; + uint32_t length = 0; + + 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"); diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 737e640..3484b24 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -20,6 +20,7 @@ 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 { NotificationBundleOption option; @@ -91,10 +92,7 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[IS_DISPLAY_BADGE_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - - if (argc == 0) { - return Common::NapiGetNull(env); - } + NAPI_ASSERT(env, argc >= IS_DISPLAY_BADGE_MIN_PARA, "Wrong number of arguments"); // argv[0]: bundle / callback napi_valuetype valuetype = napi_undefined; diff --git a/interfaces/kits/napi/ans/src/distributed.cpp b/interfaces/kits/napi/ans/src/distributed.cpp new file mode 100644 index 0000000..b002a11 --- /dev/null +++ b/interfaces/kits/napi/ans/src/distributed.cpp @@ -0,0 +1,489 @@ +/* + * 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.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; +}; + +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; + } +} +} // 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 a27ba19..8ad364e 100644 --- a/interfaces/kits/napi/ans/src/disturb_mode.cpp +++ b/interfaces/kits/napi/ans/src/disturb_mode.cpp @@ -44,7 +44,7 @@ struct AsyncCallbackInfoSupportDoNotDisturb { napi_env env = nullptr; napi_async_work asyncWork = nullptr; napi_ref callback = nullptr; - bool disturbMode = false; + bool isSupported = false; CallbackPromiseInfo info; }; @@ -155,6 +155,8 @@ napi_value SetDoNotDisturbDate(napi_env env, napi_callback_info info) 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("SetDoNotDisturbDate napi_create_async_work end"); @@ -240,6 +242,8 @@ napi_value GetDoNotDisturbDate(napi_env env, napi_callback_info info) 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, @@ -283,16 +287,16 @@ napi_value SupportDoNotDisturbMode(napi_env env, napi_callback_info info) ANS_LOGI("SupportDoNotDisturbMode napi_create_async_work start"); AsyncCallbackInfoSupportDoNotDisturb *asynccallbackinfo = (AsyncCallbackInfoSupportDoNotDisturb *)data; asynccallbackinfo->info.errorCode = - NotificationHelper::DoesSupportDoNotDisturbMode(asynccallbackinfo->disturbMode); - ANS_LOGI("asynccallbackinfo->disturbMode = %{public}d", asynccallbackinfo->disturbMode); - ANS_LOGI("asynccallbackinfo->info.errorCode = %{public}d", 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->disturbMode, &result); + napi_get_boolean(env, asynccallbackinfo->isSupported, &result); Common::ReturnCallbackPromise(env, asynccallbackinfo->info, result); if (asynccallbackinfo->info.callback != nullptr) { diff --git a/interfaces/kits/napi/ans/src/init.cpp b/interfaces/kits/napi/ans/src/init.cpp index c3cfdbb..fa8ed52 100644 --- a/interfaces/kits/napi/ans/src/init.cpp +++ b/interfaces/kits/napi/ans/src/init.cpp @@ -18,6 +18,7 @@ #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" @@ -68,6 +69,11 @@ napi_value NotificationInit(napi_env env, napi_value exports) 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), }; NAPI_CALL(env, napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc)); diff --git a/notification.gni b/notification.gni index 3039d02..efde1d9 100644 --- a/notification.gni +++ b/notification.gni @@ -42,3 +42,5 @@ ans_standard_external_deps = [ "safwk:system_ability_fwk", "samgr_standard:samgr_proxy", ] + +distributed_notification_supported = true diff --git a/services/BUILD.gn b/services/BUILD.gn index 14494d7..6f1abec 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 e38cb70..7694c78 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -57,6 +57,8 @@ ohos_shared_library("libans") { "//utils/native/base:utils_config", ] + defines = [] + deps = [ "${core_path}:ans_core", "${frameworks_path}/ans/native:ans_innerkits", @@ -72,6 +74,12 @@ ohos_shared_library("libans") { cflags = [ "-DCONFIG_DUAL_FRAMEWORK" ] } + if (distributed_notification_supported) { + defines += [ "DISTRIBUTED_NOTIFICATION_SUPPORTED" ] + deps += [ "${services_path}/distributed:libans_distributed" ] + include_dirs += [ "${services_path}/distributed/include" ] + } + external_deps = [ "distributeddatamgr:distributeddata_inner", "multimedia_image_standard:image_native", diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index 6d03972..e1fb967 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" @@ -105,6 +106,12 @@ public: 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 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; @@ -116,6 +123,10 @@ public: // SystemEvent void OnBundleRemoved(const sptr &bundleOption); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + void OnScreenOn(); + void OnScreenOff(); +#endif // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); @@ -134,6 +145,7 @@ 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); @@ -161,6 +173,20 @@ private: ErrCode PrepereContinuousTaskNotificationRequest(const sptr &request, const int &uid); bool GetActiveUserId(int& userId); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + std::vector GetLocalNotificationKeys(const sptr &bundleOption); + 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); +#endif + private: static sptr instance_; static std::mutex instanceMutex_; diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index ab4fb0c..f753d91 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -33,7 +33,7 @@ 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); private: void Connect(); diff --git a/services/ans/include/notification_record.h b/services/ans/include/notification_record.h index 12b5413..9939e09 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" @@ -30,6 +32,9 @@ struct NotificationRecord { 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/system_event_observer.h b/services/ans/include/system_event_observer.h index 8e4be39..382959c 100644 --- a/services/ans/include/system_event_observer.h +++ b/services/ans/include/system_event_observer.h @@ -28,7 +28,7 @@ namespace OHOS { namespace Notification { class SystemEventObserver { public: - SystemEventObserver(const ISystemEvent& callbacks); + SystemEventObserver(const ISystemEvent &callbacks); ~SystemEventObserver(); private: diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 8f2af8f..95ae995 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -34,6 +34,11 @@ #include "permission_filter.h" #include "reminder_data_manager.h" +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED +#include "distributed_notification_manager.h" +#include "distributed_preferences.h" +#endif + namespace OHOS { namespace Notification { namespace { @@ -196,6 +201,28 @@ AdvancedNotificationService::AdvancedNotificationService() 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() @@ -203,6 +230,9 @@ AdvancedNotificationService::~AdvancedNotificationService() dataManager_.UnRegisterKvStoreServiceDeathRecipient(distributedKvStoreDeathRecipient_); StopFilters(); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedNotificationManager::GetInstance()->UngegisterCallback(); +#endif } sptr AdvancedNotificationService::GenerateBundleOption() @@ -235,6 +265,22 @@ sptr AdvancedNotificationService::GenerateValidBundleO return validBundleOption; } +ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ptr &record) +{ + 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::PrepareNotificationInfo( const sptr &request, sptr &bundleOption) { @@ -262,6 +308,7 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification( record->request = request; record->notification = new Notification(request); record->bundleOption = bundleOption; + ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { result = AssignValidNotificationSlot(record); @@ -276,22 +323,16 @@ ErrCode AdvancedNotificationService::PublishPreparedNotification( 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; } @@ -418,6 +459,9 @@ ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::strin UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete("", notification); +#endif } })); return result; @@ -439,6 +483,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; @@ -449,6 +496,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 } } @@ -465,6 +515,10 @@ ErrCode AdvancedNotificationService::AddSlots(const std::vector bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -730,10 +784,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; @@ -744,6 +805,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 } })); @@ -758,6 +822,10 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -767,6 +835,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); @@ -779,6 +850,9 @@ ErrCode AdvancedNotificationService::DeleteByBundle(const sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } } @@ -796,12 +870,19 @@ 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 = RemoveFromNotificationListForDeleteAll(key, notification); @@ -814,6 +895,9 @@ ErrCode AdvancedNotificationService::DeleteAll() UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } } @@ -905,6 +989,10 @@ 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; @@ -934,6 +1022,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; @@ -954,6 +1046,10 @@ 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; @@ -997,9 +1093,14 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrnotification->IsRemoveAllowed()) { continue; } - if (((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && - (record->bundleOption->GetUid() == bundleOption->GetUid())) && - (record->notification->GetLabel() == label) && (record->notification->GetId() == notificationId)) { + if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && + (record->bundleOption->GetUid() == bundleOption->GetUid()) && + (record->notification->GetLabel() == label) && + (record->notification->GetId() == notificationId) +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + && record->deviceId.empty() +#endif + ) { if (!isCancel && record->request->IsUnremovable()) { return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; } @@ -1057,10 +1158,6 @@ 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; @@ -1070,6 +1167,10 @@ ErrCode AdvancedNotificationService::Subscribe( return ERR_ANS_PERMISSION_DENIED; } + if (subscriber == nullptr) { + return ERR_ANS_INVALID_PARAM; + } + return NotificationSubscriberManager::GetInstance()->AddSubscriber(subscriber, info); } @@ -1078,17 +1179,17 @@ ErrCode AdvancedNotificationService::Unsubscribe( { 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 (!IsSystemApp()) { - ANS_LOGE("Client is not a system app"); - return ERR_ANS_NON_SYSTEM_APP; + if (subscriber == nullptr) { + return ERR_ANS_INVALID_PARAM; } return NotificationSubscriberManager::GetInstance()->RemoveSubscriber(subscriber, info); @@ -1185,6 +1286,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_) { @@ -1204,6 +1309,10 @@ 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) { @@ -1259,6 +1368,10 @@ 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) { @@ -1293,6 +1406,9 @@ ErrCode AdvancedNotificationService::IsSpecialBundleAllowedNotify( if (!IsSystemApp()) { return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } targetBundle = GenerateValidBundleOption(bundleOption); } } @@ -1473,6 +1589,11 @@ ErrCode AdvancedNotificationService::ActiveNotificationDump(std::vectordeviceId.empty()) { + continue; + } +#endif stream.clear(); stream << "\tBundleName: " << record->notification->GetBundleName() << "\n"; @@ -1651,8 +1772,11 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr keys = GetLocalNotificationKeys(bundleOption); +#else std::vector keys = GetNotificationKeys(bundleOption); +#endif for (auto key : keys) { sptr notification = nullptr; result = RemoveFromNotificationList(key, notification, true); @@ -1665,6 +1789,9 @@ void AdvancedNotificationService::OnBundleRemoved(const sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete("", notification); +#endif } } })); @@ -1673,8 +1800,12 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrPostTask( - std::bind([&]() { NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); })); + handler_->PostTask(std::bind([&]() { + NotificationPreferences::GetInstance().OnDistributedKvStoreDeathRecipient(); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DistributedNotificationManager::GetInstance()->OnDistributedKvStoreDeathRecipient(); +#endif + })); } ErrCode AdvancedNotificationService::RemoveAllSlots() @@ -1743,15 +1874,23 @@ ErrCode AdvancedNotificationService::RemoveNotification( handler_->PostSyncTask(std::bind([&]() { sptr notification = 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; break; } +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + deviceId = record->deviceId; +#endif notification = record->notification; notificationList_.remove(record); result = ERR_OK; @@ -1764,6 +1903,9 @@ ErrCode AdvancedNotificationService::RemoveNotification( UpdateRecentNotification(notification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(deviceId, notification); +#endif } })); @@ -1795,7 +1937,11 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptrbundleOption->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); } } @@ -1807,6 +1953,9 @@ ErrCode AdvancedNotificationService::RemoveAllNotifications(const sptrnotification, true, reason); sptr sortingMap = GenerateSortingMap(); NotificationSubscriberManager::GetInstance()->NotifyCanceled(record->notification, sortingMap, reason); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + DoDistributedDelete(record->deviceId, record->notification); +#endif } } })); @@ -1822,6 +1971,10 @@ ErrCode AdvancedNotificationService::GetSlotNumAsBundle(const sptr bundle = GenerateValidBundleOption(bundleOption); if (bundle == nullptr) { return ERR_ANS_INVALID_BUNDLE; @@ -1858,6 +2011,9 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName) 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); } @@ -1871,6 +2027,9 @@ ErrCode AdvancedNotificationService::CancelGroup(const std::string &groupName) 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 } } })); @@ -1887,6 +2046,10 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( return ERR_ANS_NON_SYSTEM_APP; } + if (!CheckPermission(GetClientBundleName())) { + return ERR_ANS_PERMISSION_DENIED; + } + if (bundleOption == nullptr || groupName.empty()) { return ERR_ANS_INVALID_PARAM; } @@ -1901,6 +2064,9 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( for (auto record : notificationList_) { 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); } @@ -1914,6 +2080,9 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( 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 } } })); @@ -2011,6 +2180,10 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptr bundleOption = GenerateBundleOption(); if (bundleOption == nullptr) { @@ -2096,6 +2277,15 @@ ErrCode AdvancedNotificationService::GetDoNotDisturbDate(sptrPostSyncTask(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; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, 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; + } + + 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; + } + + ErrCode result = ERR_OK; + handler_->PostSyncTask(std::bind([&]() { + result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, enabled); + if (result != ERR_OK) { + result = ERR_OK; + enabled = false; + } + })); + return result; +#else + return ERR_INVALID_OPERATION; +#endif +} + +#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; +} + +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) +{ + 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; + + 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; + + 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); + } + })); +} +#endif + ErrCode AdvancedNotificationService::PrepereContinuousTaskNotificationRequest( const sptr &request, const int &uid) { @@ -2146,4 +2678,4 @@ bool AdvancedNotificationService::GetActiveUserId(int& userId) return false; } } // namespace Notification -} // namespace OHOS +} // 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 c548526..f57a452 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -100,7 +100,7 @@ void BundleManagerHelper::Disconnect() } } -int BundleManagerHelper::GetDefaultUidByBundleName(const std::string& bundle) +int BundleManagerHelper::GetDefaultUidByBundleName(const std::string &bundle) { int uid = -1; diff --git a/services/ans/src/notification_preferences_database.cpp b/services/ans/src/notification_preferences_database.cpp index 3359c9c..966e69a 100644 --- a/services/ans/src/notification_preferences_database.cpp +++ b/services/ans/src/notification_preferences_database.cpp @@ -145,7 +145,7 @@ OHOS::DistributedKv::Status NotificationPreferencesDatabase::GetKvStore() OHOS::DistributedKv::Options options = { .createIfMissing = true, .encrypt = false, - .autoSync = true, + .autoSync = false, .kvStoreType = OHOS::DistributedKv::KvStoreType::SINGLE_VERSION, }; auto status = dataManager_.GetSingleKvStore(options, appId_, storeId_, kvStorePtr_); @@ -1312,6 +1312,7 @@ std::string NotificationPreferencesDatabase::GenerateBundleLablel( { return bundleInfo.GetBundleName().append(std::to_string(bundleInfo.GetBundleUid())); } + void NotificationPreferencesDatabase::GetDoNotDisturbType(NotificationPreferencesInfo &info, int userId) { std::string key = @@ -1407,6 +1408,5 @@ void NotificationPreferencesDatabase::GetEnableAllNotification(NotificationPrefe } }); } - } // namespace Notification } // namespace OHOS \ No newline at end of file diff --git a/services/ans/src/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index f6a4e94..9c2dcda 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -99,7 +99,6 @@ void NotificationSubscriberManager::NotifyConsumed( ANS_LOGE("handler is nullptr"); return; } - AppExecFwk::EventHandler::Callback NotifyConsumedFunc = std::bind(&NotificationSubscriberManager::NotifyConsumedInner, this, notification, notificationMap); diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index d29b10e..faab50d 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -45,6 +45,8 @@ ohos_unittest("ans_unit_test") { "//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", @@ -91,6 +93,12 @@ ohos_unittest("ans_unit_test") { "//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", diff --git a/services/ans/test/unittest/advanced_notification_service_test.cpp b/services/ans/test/unittest/advanced_notification_service_test.cpp index f4693c9..441a16c 100644 --- a/services/ans/test/unittest/advanced_notification_service_test.cpp +++ b/services/ans/test/unittest/advanced_notification_service_test.cpp @@ -35,7 +35,6 @@ using namespace OHOS::Media; namespace OHOS { namespace Notification { - class AdvancedNotificationServiceTest : public testing::Test { public: static void SetUpTestCase(); diff --git a/services/distributed/BUILD.gn b/services/distributed/BUILD.gn new file mode 100644 index 0000000..757c4c4 --- /dev/null +++ b/services/distributed/BUILD.gn @@ -0,0 +1,58 @@ +# Copyright (c) 2021 Huawei Device Co., Ltd. +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import("//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", + ] + + 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 = [ + "aafwk_standard:want", + "appexecfwk_standard:libeventhandler", + "distributeddatamgr:distributeddata_inner", + "dmsfwk_standard:zuri", + "hiviewdfx_hilog_native:libhilog", + "ipc:ipc_core", + "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 0000000..7782e0f --- /dev/null +++ b/services/distributed/include/distributed_database.h @@ -0,0 +1,71 @@ +/* + * 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_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 0000000..f6fcdc1 --- /dev/null +++ b/services/distributed/include/distributed_database_callback.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_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 0000000..3d7f089 --- /dev/null +++ b/services/distributed/include/distributed_device_callback.h @@ -0,0 +1,45 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef BASE_NOTIFICATION_ANS_STANDARD_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 0000000..af28ed2 --- /dev/null +++ b/services/distributed/include/distributed_flow_control.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_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 0000000..c960937 --- /dev/null +++ b/services/distributed/include/distributed_notification_manager.h @@ -0,0 +1,104 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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 0000000..deafccf --- /dev/null +++ b/services/distributed/include/distributed_preferences.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_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 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 0000000..e930070 --- /dev/null +++ b/services/distributed/include/distributed_preferences_database.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_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 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 0000000..feea944 --- /dev/null +++ b/services/distributed/include/distributed_preferences_info.h @@ -0,0 +1,40 @@ +/* + * 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_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); + +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/src/distributed_database.cpp b/services/distributed/src/distributed_database.cpp new file mode 100644 index 0000000..b763e6d --- /dev/null +++ b/services/distributed/src/distributed_database.cpp @@ -0,0 +1,322 @@ +/* + * 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_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 0000000..c42ee6b --- /dev/null +++ b/services/distributed/src/distributed_database_callback.cpp @@ -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. + */ + +#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 0000000..9742f3e --- /dev/null +++ b/services/distributed/src/distributed_device_callback.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 "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 0000000..fa7524d --- /dev/null +++ b/services/distributed/src/distributed_flow_control.cpp @@ -0,0 +1,94 @@ +/* + * 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_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 0000000..6134bed --- /dev/null +++ b/services/distributed/src/distributed_notification_manager.cpp @@ -0,0 +1,424 @@ +/* + * 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_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 0000000..07838e9 --- /dev/null +++ b/services/distributed/src/distributed_preferences.cpp @@ -0,0 +1,195 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#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::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 0000000..dc861eb --- /dev/null +++ b/services/distributed/src/distributed_preferences_database.cpp @@ -0,0 +1,192 @@ +/* + * 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_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::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 0000000..b357225 --- /dev/null +++ b/services/distributed/src/distributed_preferences_info.cpp @@ -0,0 +1,54 @@ +/* + * 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_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; +} +} // 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 0000000..1a3e4b4 --- /dev/null +++ b/services/distributed/test/unittest/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") +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", + "//base/hiviewdfx/hilog/interfaces/native/innerkits/include", + "//base/hiviewdfx/hitrace/interfaces/native/innerkits/include", + "//foundation/aafwk/standard/interfaces/innerkits/base/include", + "//foundation/appexecfwk/standard/interfaces/innerkits/appexecfwk_base/include", + "//foundation/appexecfwk/standard/libs/libeventhandler/src", + "//foundation/communication/ipc/interfaces/innerkits/ipc_core/include", + "//foundation/distributeddatamgr/distributeddatamgr/interfaces/innerkits/distributeddata/include", + "//foundation/distributedschedule/dmsfwk/services/dtbschedmgr/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/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/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 = [ "hiviewdfx_hilog_native:libhilog" ] + + 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 0000000..4d1dac7 --- /dev/null +++ b/services/distributed/test/unittest/distributed_database_test.cpp @@ -0,0 +1,193 @@ +/* + * 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 "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 0000000..db3f367 --- /dev/null +++ b/services/distributed/test/unittest/distributed_notification_manager_test.cpp @@ -0,0 +1,184 @@ +/* + * 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 "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("

    + *
  • 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() {} + + 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 index 0370550..a33c014 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_timer.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -62,7 +62,7 @@ public: bool ReadFromParcel(Parcel &parcel) override; protected: - virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool forceToGetNext) const override; + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const override; private: ReminderRequestTimer() {}; diff --git a/interfaces/kits/napi/ans/include/reminder/reminder_common.h b/interfaces/kits/napi/ans/include/reminder/reminder_common.h index 0f9b9e0..63b1d0f 100644 --- a/interfaces/kits/napi/ans/include/reminder/reminder_common.h +++ b/interfaces/kits/napi/ans/include/reminder/reminder_common.h @@ -26,22 +26,38 @@ namespace ReminderAgentNapi { using namespace OHOS::Notification; namespace { -const char* REMINDER_TYPE = "reminderType"; -const char* ALARM_HOUR = "hour"; -const char* ALARM_MINUTE = "minute"; -const char* ALARM_DAYS_OF_WEEK = "daysOfWeek"; -const char* TIMER_COUNT_DOWN_TIME = "triggerTimeInSeconds"; const char* ACTION_BUTTON = "actionButton"; const char* ACTION_BUTTON_TITLE = "title"; const char* ACTION_BUTTON_TYPE = "type"; -const char* WANT_AGENT = "wantAgent"; -const char* WANT_AGENT_PKG = "pkgName"; -const char* WANT_AGENT_ABILITY = "abilityName"; -const char* TITLE = "title"; +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 { @@ -58,7 +74,7 @@ public: 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); + 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); @@ -67,8 +83,20 @@ public: const char* propertyName, napi_value& propertyVal); private: - static bool CreateReminder(const napi_env &env, const napi_value &value, - const int32_t &reminderType, std::shared_ptr& reminder); + 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); @@ -76,20 +104,17 @@ private: static void GenWantAgent( 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( + static void GenMaxScreenWantAgent( const napi_env &env, const napi_value &value, std::shared_ptr& reminder); - static napi_value CreateReminderTimer( + static bool GenActionButtons( const napi_env &env, const napi_value &value, std::shared_ptr& reminder); - static napi_value CreateReminderAlarm( + static napi_value GenReminder( const napi_env &env, const napi_value &value, std::shared_ptr& reminder); - static napi_value ParseDaysOfWeek( - const napi_env &env, const napi_value &value, std::vector &daysOfWeek); + 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 diff --git a/interfaces/kits/napi/ans/src/reminder/native_module.cpp b/interfaces/kits/napi/ans/src/reminder/native_module.cpp index 386a92f..f4fe365 100644 --- a/interfaces/kits/napi/ans/src/reminder/native_module.cpp +++ b/interfaces/kits/napi/ans/src/reminder/native_module.cpp @@ -51,12 +51,18 @@ napi_value ConstantInit(napi_env env, napi_value exports) 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), diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 699925f..2f792d9 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -16,6 +16,7 @@ #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" @@ -105,8 +106,7 @@ napi_value ParseCanCelParameter(const napi_env &env, const napi_callback_info &i // argv[0]: reminder id int32_t reminderId = -1; - if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId)) { - ANSR_LOGW("Param id of cancels Reminder should be a number."); + if (!ReminderCommon::GetInt32(env, argv[0], nullptr, reminderId, true)) { return nullptr; } if (reminderId < 0) { @@ -279,42 +279,99 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) } } +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) { - napi_value value = nullptr; switch (type) { case ReminderRequest::ReminderType::TIMER: { - ReminderRequestTimer& timer = (ReminderRequestTimer&)reminder; - napi_create_uint32(env, timer.GetInitInfo(), &value); - napi_set_named_property(env, result, TIMER_COUNT_DOWN_TIME, value); + ParseReminderTimer(env, reminder, result); break; } case ReminderRequest::ReminderType::ALARM: { - ANSR_LOGD("Parse alarm info"); - - // hour - ReminderRequestAlarm& alarm = (ReminderRequestAlarm&)reminder; - napi_create_uint32(env, static_cast(alarm.GetHour()), &value); - - // minute - napi_set_named_property(env, result, ALARM_HOUR, value); - 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++; - } - } - ANSR_LOGD("Parse alarm info end"); + ParseReminderAlarm(env, reminder, result); + break; + } + case ReminderRequest::ReminderType::CALENDAR: { + ParseReminderCalendar(env, reminder, result); break; } default: { @@ -334,6 +391,7 @@ void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_val 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); @@ -364,6 +422,20 @@ void ParseWantAgent(const napi_env &env, ReminderRequest &reminder, napi_value & 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"); @@ -392,10 +464,26 @@ napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi 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); @@ -405,9 +493,11 @@ napi_value SetValidReminder(const napi_env &env, ReminderRequest &reminder, napi // wantAgent ParseWantAgent(env, reminder, result); + // maxScreenWantAgent + ParseMaxScreenWantAgent(env, reminder, result); + // actionButtons ParseActionButtons(env, reminder, result); - return NotificationNapi::Common::NapiGetBoolean(env, true); } diff --git a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp index 7b60e47..4bf5d49 100644 --- a/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp +++ b/interfaces/kits/napi/ans/src/reminder/reminder_common.cpp @@ -16,6 +16,7 @@ #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" @@ -30,7 +31,7 @@ napi_value ReminderCommon::GetReminderRequest( napi_valuetype valuetype = napi_undefined; NAPI_CALL(env, napi_typeof(env, value, &valuetype)); if (valuetype != napi_object) { - ANSR_LOGE("Wrong argument type. Object expected."); + ANSR_LOGW("Wrong argument type. Object expected."); return nullptr; } @@ -53,7 +54,7 @@ bool ReminderCommon::GenActionButtons( bool isArray = false; napi_is_array(env, actionButtons, &isArray); if (!isArray) { - ANSR_LOGE("Wrong argument type:%{public}s. array expected.", ACTION_BUTTON); + ANSR_LOGW("Wrong argument type:%{public}s. array expected.", ACTION_BUTTON); return false; } @@ -64,15 +65,16 @@ bool ReminderCommon::GenActionButtons( napi_get_element(env, actionButtons, i, &actionButton); NAPI_CALL(env, napi_typeof(env, actionButton, &valuetype)); if (valuetype != napi_object) { - ANSR_LOGE("Wrong element type:%{public}s. object expected.", ACTION_BUTTON); + 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)) { - if (ReminderRequest::ActionButtonType(buttonType) != ReminderRequest::ActionButtonType::CLOSE) { + 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; } @@ -105,9 +107,32 @@ void ReminderCommon::GenWantAgent( } } -bool ReminderCommon::CreateReminder(const napi_env &env, const napi_value &value, - const int32_t &reminderType, std::shared_ptr& reminder) +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); @@ -115,8 +140,11 @@ bool ReminderCommon::CreateReminder(const napi_env &env, const napi_value &value 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."); + ANSR_LOGW("Reminder type is not support. (type:%{public}d)", reminderType); break; } if (reminder == nullptr) { @@ -133,16 +161,12 @@ napi_value ReminderCommon::GenReminder( bool hasProperty = false; NAPI_CALL(env, napi_has_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &hasProperty)); if (!hasProperty) { - ANSR_LOGE("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); + ANSR_LOGW("Property %{public}s expected.", ReminderAgentNapi::REMINDER_TYPE); return nullptr; } - napi_value result = nullptr; - napi_get_named_property(env, value, ReminderAgentNapi::REMINDER_TYPE, &result); - int32_t propertyVal = -1; - napi_get_value_int32(env, result, &propertyVal); // createReminder - if (!CreateReminder(env, value, propertyVal, reminder)) { + if (!CreateReminder(env, value, reminder)) { return nullptr; } char str[NotificationNapi::STR_MAX_SIZE] = {0}; @@ -162,14 +186,51 @@ napi_value ReminderCommon::GenReminder( 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 - if (GetInt32(env, value, ReminderAgentNapi::NOTIFICATION_ID, propertyVal)) { + 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)) { + 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."); @@ -181,6 +242,9 @@ napi_value ReminderCommon::GenReminder( // wantAgent GenWantAgent(env, value, reminder); + // maxScreenWantAgent + GenMaxScreenWantAgent(env, value, reminder); + // actionButtons if (!GenActionButtons(env, value, reminder)) { return nullptr; @@ -201,7 +265,7 @@ bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value, napi_get_named_property(env, value, propertyName, &result); NAPI_CALL(env, napi_typeof(env, result, &valuetype)); if (valuetype != napi_string) { - ANSR_LOGE("Wrong argument type:%{public}s. string expected.", propertyName); + 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)); @@ -210,10 +274,13 @@ bool ReminderCommon::GetStringUtf8(const napi_env &env, const napi_value &value, } bool ReminderCommon::GetInt32(const napi_env &env, const napi_value &value, - const char* propertyName, int32_t& propertyVal) + 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); @@ -270,7 +337,7 @@ bool ReminderCommon::GetObject(const napi_env &env, const napi_value &value, napi_get_named_property(env, value, propertyName, &propertyVal); NAPI_CALL(env, napi_typeof(env, propertyVal, &valuetype)); if (valuetype != napi_object) { - ANSR_LOGE("Wrong argument type:%{public}s. object expected.", propertyName); + ANSR_LOGW("Wrong argument type:%{public}s. object expected.", propertyName); return false; } return true; @@ -281,14 +348,13 @@ napi_value ReminderCommon::CreateReminderTimer( { int64_t propertyCountDownTime = 0; if (!GetInt64(env, value, ReminderAgentNapi::TIMER_COUNT_DOWN_TIME, propertyCountDownTime)) { - ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); + ANSR_LOGW("Correct property %{public}s expected.", ReminderAgentNapi::TIMER_COUNT_DOWN_TIME); return nullptr; } - if (propertyCountDownTime <= 0 || - propertyCountDownTime > static_cast((UINT64_MAX / ReminderRequest::MILLI_SECONDS))) { - ANSR_LOGE("Property %{public}s must between (0, %{public}llu).", - ReminderAgentNapi::ALARM_MINUTE, (unsigned long long)(UINT64_MAX / ReminderRequest::MILLI_SECONDS)); + 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; } @@ -301,54 +367,128 @@ napi_value ReminderCommon::CreateReminderAlarm( { // hour int32_t propertyHourVal = 0; - if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal)) { - ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_HOUR); + if (!GetInt32(env, value, ReminderAgentNapi::ALARM_HOUR, propertyHourVal, true)) { return nullptr; } // minute int32_t propertyMinuteVal = 0; - if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal)) { - ANSR_LOGE("Correct property %{public}s expected.", ReminderAgentNapi::ALARM_MINUTE); + if (!GetInt32(env, value, ReminderAgentNapi::ALARM_MINUTE, propertyMinuteVal, true)) { return nullptr; } if (propertyHourVal < 0 || propertyHourVal > 23) { - ANSR_LOGE("Property %{public}s must between [0, 23].", ReminderAgentNapi::ALARM_HOUR); + ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 23].", + ReminderAgentNapi::ALARM_HOUR); return nullptr; } if (propertyMinuteVal < 0 || propertyMinuteVal > 59) { - ANSR_LOGE("Property %{public}s must between [0, 59].", ReminderAgentNapi::ALARM_MINUTE); + ANSR_LOGW("Create alarm reminder fail: designated %{public}s must between [0, 59].", + ReminderAgentNapi::ALARM_MINUTE); return nullptr; } // daysOfWeek std::vector daysOfWeek; - ParseDaysOfWeek(env, value, 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::ParseDaysOfWeek( - const napi_env &env, const napi_value &value, std::vector &daysOfWeek) +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, ReminderAgentNapi::ALARM_DAYS_OF_WEEK, result)) { + 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_LOGE("Property %{public}s is expected to be an array.", ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + 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); - uint8_t maxDaysOfWeek = 7; - if (length > maxDaysOfWeek) { - ANSR_LOGE( - "The max length of array of %{public}s is %{public}d.", ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + 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; @@ -358,20 +498,18 @@ napi_value ReminderCommon::ParseDaysOfWeek( napi_get_element(env, result, i, &repeatDayVal); NAPI_CALL(env, napi_typeof(env, repeatDayVal, &valuetype)); if (valuetype != napi_number) { - ANSR_LOGE("%{public}s's element is expected to be number.", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK); + 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 > maxDaysOfWeek) { - ANSR_LOGE("%{public}s's element must between [1, %{public}d].", - ReminderAgentNapi::ALARM_DAYS_OF_WEEK, maxDaysOfWeek); + if (propertyDayVal < 1 || propertyDayVal > maxLen) { + ANSR_LOGW("%{public}s's element must between [1, %{public}d].", propertyName, maxLen); return nullptr; } - daysOfWeek.push_back(static_cast(propertyDayVal)); + propertyVal.push_back(static_cast(propertyDayVal)); } } return NotificationNapi::Common::NapiGetNull(env); } } -} \ No newline at end of file +} diff --git a/services/ans/BUILD.gn b/services/ans/BUILD.gn index c8d5705..12c62d3 100644 --- a/services/ans/BUILD.gn +++ b/services/ans/BUILD.gn @@ -71,8 +71,10 @@ ohos_shared_library("libans") { 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", ] diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index f7029a8..b4b7abe 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -131,6 +131,8 @@ public: // Distributed KvStore void OnDistributedKvStoreDeathRecipient(); + ErrCode CancelPreparedNotification( + int notificationId, const std::string &label, const sptr &bundleOption); ErrCode PrepareNotificationInfo( const sptr &request, sptr &bundleOption); ErrCode PublishPreparedNotification( diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 8990973..531060b 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -20,6 +20,7 @@ #include #include "advanced_notification_service.h" +#include "player.h" #include "reminder_request.h" #include "reminder_timer_info.h" @@ -78,6 +79,13 @@ public: 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. * @@ -105,18 +113,60 @@ public: * * @param isSysTimeChanged Indicates it is triggered as dateTime changed by user or not. */ - void ShowReminder(bool isSysTimeChanged); + 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(sptr &reminder) const; + void CancelNotification(const sptr &reminder) const; /** * Check whether the number limit of reminders if exceeded. @@ -125,15 +175,17 @@ private: * @return true if number limit is exceeded. */ bool CheckReminderLimitExceededLocked(const std::string &bundleName) const; - - void CloseReminder(const int32_t &reminderId, bool cancelNotification); + 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() const; + std::shared_ptr CreateTimerInfo(TimerType type) const; + + std::string GetSoundUri(const sptr &reminder); /** * Find the reminder from reminderVector_ by reminder id. @@ -159,7 +211,7 @@ private: * @param reminderId Indicates the reminder id. * @return pointer of NotificationBundleOption or nullptr. */ - sptr FindNotificationBundleOption(const int32_t &reminderId); + sptr FindNotificationBundleOption(const int32_t &reminderId) const; /** * Obtains the recent reminder which is not expired from reminder vector. @@ -197,6 +249,8 @@ private: */ void HandleSameNotificationIdShowing(const sptr reminder); + bool HandleSysTimeChange(const sptr reminder) const; + /** * Judge the two reminders is belong to the same application or not. * @@ -208,6 +262,18 @@ private: 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. * @@ -227,12 +293,30 @@ private: /** * Resets timer status. - * 1. Sets timerId_ with 0. - * 2. Sets activeReminderId_ with -1. + * 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 ResetStates(); + void ShowReminder(const sptr &reminder, const bool &isNeedToPlaySound, + const bool &isNeedToStartNext, const bool &isSysTimeChanged, const bool &needScheduleTimeout); - void ShowDesignatedReminderLocked(sptr &reminder, bool isSysTimeChanged); + void SnoozeReminderImpl(sptr &reminder); /** * Starts the recent reminder timing. @@ -243,18 +327,42 @@ private: * Starts timing actually. * * @param reminderRequest Indicates the reminder. + * @param type Indicates the timer type. */ - void StartTimerLocked(sptr &reminderRequest); + void StartTimerLocked(const sptr &reminderRequest, TimerType type); + void StartTimer(const sptr &reminderRequest, TimerType type); /** - * Stops timing. + * @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 StopTimer(); + 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 StopTimerLocked(); + 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. @@ -265,6 +373,8 @@ private: void UpdateAndSaveReminderLocked( const sptr &reminder, const sptr &bundleOption); + void UpdateNotification(const sptr &reminder); + static bool cmp(sptr &reminderRequest, sptr &other); /** @@ -276,6 +386,8 @@ private: * 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. @@ -287,27 +399,44 @@ private: */ static const int16_t MAX_NUM_REMINDER_LIMIT_APP; - static const uint16_t SAME_TIME_DISTINGUISH_MILLISECONDS; - /** * 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> shownReminderVector_; + /** * Map used to record all the bundle information of the reminders in system. */ std::map> notificationBundleOptionMap_; /** - * Indicates the id of the timer that has called StartTimerLocked. + * 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}; + 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. @@ -317,5 +446,4 @@ private: }; } // 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 index 25a2079..bfc7214 100644 --- a/services/ans/include/reminder_event_manager.h +++ b/services/ans/include/reminder_event_manager.h @@ -40,6 +40,10 @@ public: 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_; }; }; diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h index 0bc1e89..0434923 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -31,6 +31,10 @@ public: 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. */ @@ -56,10 +60,8 @@ public: */ void SetWantAgent(std::shared_ptr wantAgent) override; - /** - * Publish common event. - */ - bool PublishCommonEvent(const std::string &action) const; +private: + std::string action_; }; } // namespace OHOS } // namespace Notification diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index 484f975..61f7b0d 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -292,6 +292,33 @@ ErrCode AdvancedNotificationService::AssignToNotificationList(const std::shared_ 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) { @@ -454,29 +481,7 @@ ErrCode AdvancedNotificationService::Cancel(int notificationId, const std::strin { 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); -#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED - DoDistributedDelete("", notification); -#endif - } - })); - return result; + return CancelPreparedNotification(notificationId, label, bundleOption); } ErrCode AdvancedNotificationService::CancelAll() @@ -2825,4 +2830,4 @@ void AdvancedNotificationService::TriggerRemoveWantAgent(const sptr 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) @@ -49,9 +52,13 @@ void ReminderDataManager::CancelReminder( ANSR_LOGW("Cancel reminder, not find the reminder"); return; } - if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { - ANSR_LOGD("Cancel active reminder, id=%{public}d", activeReminderId_); - StopTimerLocked(); + 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); @@ -59,7 +66,7 @@ void ReminderDataManager::CancelReminder( StartRecentReminder(); } -void ReminderDataManager::CancelNotification(sptr &reminder) const +void ReminderDataManager::CancelNotification(const sptr &reminder) const { if (!(reminder->IsShowing())) { ANSR_LOGD("No need to cancel notification"); @@ -75,7 +82,9 @@ void ReminderDataManager::CancelNotification(sptr &reminder) co ANSR_LOGE("Cancel notification fail"); return; } - advancedNotificationService_->Cancel(notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL); + sptr bundleOption = FindNotificationBundleOption(reminder->GetReminderId()); + advancedNotificationService_->CancelPreparedNotification( + notification->GetNotificationId(), ReminderRequest::NOTIFICATION_LABEL, bundleOption); } bool ReminderDataManager::CheckReminderLimitExceededLocked(const std::string &bundleName) const @@ -113,10 +122,10 @@ void ReminderDataManager::CancelAllReminders(const sptrsecond->GetBundleName() == bundleOption->GetBundleName()) { - StopTimer(); + StopTimer(TimerType::TRIGGER_TIMER); } } for (auto vit = reminderVector_.begin(); vit != reminderVector_.end();) { @@ -124,15 +133,19 @@ void ReminderDataManager::CancelAllReminders(const sptrsecond->GetBundleName() == bundleOption->GetBundleName()) { - CancelNotification(*vit); - ANSR_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); - vit = reminderVector_.erase(vit); - notificationBundleOptionMap_.erase(mit); - totalCount_--; - continue; + ++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; } @@ -160,13 +173,88 @@ void ReminderDataManager::GetValidReminders( } } -std::shared_ptr ReminderDataManager::CreateTimerInfo() const +void ReminderDataManager::AddToShowedReminders(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = shownReminderVector_.begin(); it != shownReminderVector_.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()); + shownReminderVector_.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 = shownReminderVector_.begin(); it != shownReminderVector_.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); + shownReminderVector_.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); - sharedTimerInfo->SetWantAgent(nullptr); + + 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; } @@ -202,7 +290,7 @@ sptr ReminderDataManager::FindReminderRequestLocked( return reminder; } -sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) +sptr ReminderDataManager::FindNotificationBundleOption(const int32_t &reminderId) const { auto it = notificationBundleOptionMap_.find(reminderId); if (it == notificationBundleOptionMap_.end()) { @@ -220,21 +308,27 @@ bool ReminderDataManager::cmp(sptr &reminderRequest, sptr(want.GetIntParam(ReminderRequest::PARAM_REMINDER_ID, -1)); - CloseReminder(reminderId, cancelNotification); -} - -void ReminderDataManager::CloseReminder(const int32_t &reminderId, bool cancelNotification) -{ sptr reminder = FindReminderRequestLocked(reminderId); if (reminder == nullptr) { ANSR_LOGW("Invilate reminder id: %{public}d", reminderId); return; } - if (activeReminderId_ != -1 && activeReminderId_ == reminderId) { + 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(); + StopTimerLocked(TimerType::TRIGGER_TIMER); + } + if (alertingReminderId_ == reminderId) { + StopTimerLocked(TimerType::ALERTING_TIMER); + StopSoundAndVibrationLocked(reminder); } reminder->OnClose(true); + RemoveFromShowedReminders(reminder); if (cancelNotification) { CancelNotification(reminder); } @@ -256,7 +350,7 @@ void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) 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(); + StopTimerLocked(TimerType::TRIGGER_TIMER); } std::vector> showImmediately = RefreshRemindersLocked(type); if (!showImmediately.empty()) { @@ -266,19 +360,62 @@ void ReminderDataManager::RefreshRemindersDueToSysTimeChange(uint8_t type) 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(vector/map) add. reminderId=%{public}d", reminderId); + 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_++; } @@ -288,97 +425,207 @@ void ReminderDataManager::SetService(AdvancedNotificationService *advancedNotifi advancedNotificationService_ = advancedNotificationService; } -void ReminderDataManager::ShowReminder(bool isSysTimeChanged) +void ReminderDataManager::ShowActiveReminder() { - ANSR_LOGD("ShowReminder"); + ANSR_LOGI("Begin to show reminder."); if (activeReminderId_ == -1) { ANSR_LOGE("Active reminder not exist"); return; } - sptr reminder = FindReminderRequestLocked(activeReminderId_); - ShowDesignatedReminderLocked(reminder, isSysTimeChanged); - ResetStates(); + if (HandleSysTimeChange(activeReminder_)) { + ResetStates(TimerType::TRIGGER_TIMER); + return; + } + ShowActiveReminderExtendLocked(activeReminder_); + ResetStates(TimerType::TRIGGER_TIMER); StartRecentReminder(); } -void ReminderDataManager::ShowDesignatedReminderLocked(sptr &reminder, bool isSysTimeChanged) +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 > ReminderDataManager::SAME_TIME_DISTINGUISH_MILLISECONDS) { + if ((*it)->GetTriggerTimeInMilli() - triggerTime > ReminderRequest::SAME_TIME_DISTINGUISH_MILLISECONDS) { continue; } - if (isSysTimeChanged) { - if ((*it)->GetReminderId() != reminder->GetReminderId()) { - continue; - } - } - int32_t reminderId = (*it)->GetReminderId(); - sptr bundleOption = FindNotificationBundleOption(reminderId); - sptr notificationRequest = (*it)->GetNotificationRequest(); - if (bundleOption == nullptr) { - ANSR_LOGE("Get bundle option fail, reminderId=%{public}d", reminderId); - continue; + if (!isAlerting) { + playSoundReminder = (*it); + isAlerting = true; + } else { + ShowReminder((*it), false, false, false, false); } - if (advancedNotificationService_ == nullptr) { - ANSR_LOGE("ShowReminder fail"); - (*it)->OnShow(isSysTimeChanged, 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 { - ANSR_LOGD("publish notification.(reminderId=%{public}d)", reminderId); - (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::COMMON, ""); - (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::REMOVAL_WANT_AGENT, ""); - (*it)->UpdateNotificationRequest(ReminderRequest::UpdateNotificationType::ACTION_BUTTON, ""); - advancedNotificationService_->PublishPreparedNotification(notificationRequest, bundleOption); - (*it)->OnShow(isSysTimeChanged, true); - HandleSameNotificationIdShowing((*it)); + 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::StartRecentReminder() +void ReminderDataManager::UpdateNotification(const sptr &reminder) { - sptr reminder = GetRecentReminderLocked(); + 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_LOGI("No reminder need to start"); + ANSR_LOGW("Invilate reminder id: %{public}d", reminderId); return; } + SnoozeReminderImpl(reminder); +} - bool toStart = true; - if (activeReminderId_ != -1) { - if (activeReminderId_ != reminder->GetReminderId()) { - ANSR_LOGI("Stop active reminder"); - StopTimerLocked(); - } else { - ANSR_LOGI("Recent reminder has already run, no need to start again."); - toStart = false; - } +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); } - if (toStart) { - ANSR_LOGI("Start recent reminder"); - StartTimerLocked(reminder); + + // 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(); } -void ReminderDataManager::StopTimer() +// snoozeReminder(bool snoozeAll) + +void ReminderDataManager::StartRecentReminder() { - if (timerId_ == 0) { - ANSR_LOGD("Timer is not running"); + sptr reminder = GetRecentReminderLocked(); + if (reminder == nullptr) { + ANSR_LOGI("No reminder need to start"); + SetActiveReminder(reminder); return; } - ANSR_LOGD("Stop timer id=%{public}llu", (unsigned long long)timerId_); - sptr timer = MiscServices::TimeServiceClient::GetInstance(); - timer->StopTimer(timerId_); - ResetStates(); + 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::StopTimerLocked() +void ReminderDataManager::StopAlertingReminder(const sptr &reminder) { - std::lock_guard lock(ReminderDataManager::MUTEX); - StopTimer(); + 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 @@ -435,27 +682,27 @@ sptr ReminderDataManager::GetRecentReminderLocked() { std::lock_guard lock(ReminderDataManager::MUTEX); sort(reminderVector_.begin(), reminderVector_.end(), cmp); - for (auto reminder = reminderVector_.begin(); reminder != reminderVector_.end();) { - if (!(*reminder)->IsExpired()) { - ANSR_LOGD("GetRecentReminderLocked: %{public}s", (*reminder)->Dump().c_str()); - return *reminder; - } - if (!(*reminder)->CanRemove()) { - ANSR_LOGD("Reminder has been expired: %{public}s", (*reminder)->Dump().c_str()); - reminder++; + 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 = (*reminder)->GetReminderId(); + int32_t reminderId = (*it)->GetReminderId(); ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); - auto it = notificationBundleOptionMap_.find((*reminder)->GetReminderId()); - if (it == notificationBundleOptionMap_.end()) { + auto mit = notificationBundleOptionMap_.find((*it)->GetReminderId()); + if (mit == notificationBundleOptionMap_.end()) { ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", - (*reminder)->GetReminderId()); + (*it)->GetReminderId()); } else { - ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); - notificationBundleOptionMap_.erase(it); + ANSR_LOGD("Containers(vector/map) remove. reminderId=%{public}d", reminderId); + notificationBundleOptionMap_.erase(mit); } - reminder = reminderVector_.erase(reminder); + it = reminderVector_.erase(it); totalCount_--; } return nullptr; @@ -482,13 +729,21 @@ std::vector> ReminderDataManager::GetSameBundleRemindersLo void ReminderDataManager::HandleImmediatelyShow( std::vector> &showImmediately, bool isSysTimeChanged) { + bool isAlerting = false; for (auto it = showImmediately.begin(); it != showImmediately.end(); ++it) { - ShowDesignatedReminderLocked((*it), isSysTimeChanged); + 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(); @@ -497,6 +752,11 @@ sptr ReminderDataManager::HandleRefreshReminder(uint8_t &type, needShowImmediately = reminder->OnDateTimeChange(); } if (!needShowImmediately) { + uint64_t triggerTimeAfter = reminder->GetTriggerTimeInMilli(); + if (triggerTimeBefore != triggerTimeAfter + || reminder->GetReminderId() == alertingReminderId_) { + CloseReminder(reminder, true); + } return nullptr; } else { return reminder; @@ -505,7 +765,7 @@ sptr ReminderDataManager::HandleRefreshReminder(uint8_t &type, void ReminderDataManager::HandleSameNotificationIdShowing(const sptr reminder) { - // not add ReminderDataManager::MUTEX, as ShowDesignatedReminderLocked has locked + // 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(); @@ -524,7 +784,11 @@ void ReminderDataManager::HandleSameNotificationIdShowing(const sptrGetNotificationId() && IsBelongToSameApp(reminder, bundleOption->GetBundleName(), 0)) { + if ((*it)->IsAlerting()) { + StopAlertingReminder(*it); + } (*it)->OnSameNotificationIdCovered(); + RemoveFromShowedReminders(*it); } } } @@ -545,6 +809,87 @@ bool ReminderDataManager::IsBelongToSameApp( 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(); + sptr nullReminder = nullptr; + SetAlertingReminder(nullReminder); +} + +void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) +{ + std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); + for (auto it = shownReminderVector_.begin(); it != shownReminderVector_.end(); ++it) { + if ((*it)->GetReminderId() == reminder->GetReminderId()) { + ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); + shownReminderVector_.erase(it); + break; + } + } +} + std::vector> ReminderDataManager::RefreshRemindersLocked(uint8_t type) { std::lock_guard lock(ReminderDataManager::MUTEX); @@ -566,7 +911,6 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) ANSR_LOGD("Containers(vector) remove. reminderId=%{public}d", reminderId); it = reminderVector_.erase(it); totalCount_--; - ANSR_LOGD("Remove reminder(id=%{public}d) success", reminderId); break; } else { ++it; @@ -576,26 +920,117 @@ void ReminderDataManager::RemoveReminderLocked(const int32_t &reminderId) if (it == notificationBundleOptionMap_.end()) { ANSR_LOGE("Remove notificationBundleOption(reminderId=%{public}d) fail", reminderId); } else { - ANSR_LOGD("Containers(map) remove: reminderId=%{public}d", reminderId); + ANSR_LOGD("Containers(map) remove. reminderId=%{public}d", reminderId); notificationBundleOptionMap_.erase(it); } } -void ReminderDataManager::ResetStates() +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) { - ANSR_LOGD("ResetStates"); - timerId_ = 0; - activeReminderId_ = -1; + 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::StartTimerLocked(sptr &reminderRequest) +void ReminderDataManager::StopTimerLocked(TimerType type) { - ANSR_LOGD("Start timer: millSeconds=%{public}llu", (unsigned long long)(reminderRequest->GetTriggerTimeInMilli())); std::lock_guard lock(ReminderDataManager::MUTEX); + StopTimer(type); +} + +void ReminderDataManager::StopTimer(TimerType type) +{ sptr timer = MiscServices::TimeServiceClient::GetInstance(); - timerId_ = timer->CreateTimer(REMINDER_DATA_MANAGER->CreateTimerInfo()); - timer->StartTimer(timerId_, reminderRequest->GetTriggerTimeInMilli()); - activeReminderId_ = reminderRequest->GetReminderId(); + 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 index 117c831..d085adf 100644 --- a/services/ans/src/reminder_event_manager.cpp +++ b/services/ans/src/reminder_event_manager.cpp @@ -14,9 +14,14 @@ */ #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" @@ -32,7 +37,9 @@ void ReminderEventManager::init(std::shared_ptr &reminderDa { 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); @@ -58,34 +65,37 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw { Want want = data.GetWant(); std::string action = want.GetAction(); - ANSR_LOGD("Recieved common event:%{public}s", action.c_str()); + ANSR_LOGI("Recieved common event:%{public}s", action.c_str()); if (action == ReminderRequest::REMINDER_EVENT_ALARM_ALERT) { - reminderDataManager_->ShowReminder(false); + 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) { - OHOS::AppExecFwk::ElementName ele = want.GetElement(); - std::string bundleName = ele.GetBundleName(); - int uid = want.GetIntParam(OHOS::AppExecFwk::Constants::UID, -1); - ANSR_LOGD("bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); - sptr bundleOption = new NotificationBundleOption(bundleName, uid); - reminderDataManager_->CancelAllReminders(bundleOption); + HandlePackageRemove(want); return; } if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_DATA_CLEARED) { - // todo + HandlePackageRemove(want); return; } if (action == CommonEventSupport::COMMON_EVENT_PACKAGE_RESTARTED) { - // todo + HandleProcessDied(want); return; } if (action == CommonEventSupport::COMMON_EVENT_TIMEZONE_CHANGED) { @@ -97,5 +107,43 @@ void ReminderEventManager::ReminderEventSubscriber::OnReceiveEvent(const EventFw 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 \ No newline at end of file +} // namespace Notification diff --git a/services/ans/src/reminder_timer_info.cpp b/services/ans/src/reminder_timer_info.cpp index 3c7c39c..486ae1d 100644 --- a/services/ans/src/reminder_timer_info.cpp +++ b/services/ans/src/reminder_timer_info.cpp @@ -44,19 +44,7 @@ void ReminderTimerInfo::SetWantAgent(std::shared_ptr Date: Mon, 24 Jan 2022 22:16:19 +0800 Subject: [PATCH 113/131] fix codeCheck Signed-off-by: derek Change-Id: I799007a8f24844f659a78f302d636aedff8187e9 --- .../kits/napi/ans/src/reminder/publish.cpp | 24 +++++++------------ 1 file changed, 8 insertions(+), 16 deletions(-) diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 2f792d9..162dca0 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -206,10 +206,8 @@ napi_value CancelReminder(napi_env env, napi_callback_info info) napi_delete_reference(env, asynccallbackinfo->info.callback); } napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; ANSR_LOGI("Cancel napi_create_async_work complete end"); }, (void *)asynccallbackinfo, @@ -262,10 +260,8 @@ napi_value CancelAllReminders(napi_env env, napi_callback_info info) napi_delete_reference(env, asynccallbackinfo->info.callback); } napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; ANSR_LOGD("CancelAll napi_create_async_work complete end"); }, (void *)asynccallbackinfo, @@ -568,10 +564,8 @@ napi_value GetValidReminders(napi_env env, napi_callback_info info) napi_delete_reference(env, asynccallbackinfo->info.callback); } napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; }, (void *)asynccallbackinfo, &asynccallbackinfo->asyncWork); @@ -631,10 +625,8 @@ napi_value PublishReminder(napi_env env, napi_callback_info info) napi_delete_reference(env, asynccallbackinfo->info.callback); } napi_delete_async_work(env, asynccallbackinfo->asyncWork); - if (asynccallbackinfo) { - delete asynccallbackinfo; - asynccallbackinfo = nullptr; - } + delete asynccallbackinfo; + asynccallbackinfo = nullptr; ANSR_LOGI("Publish napi_create_async_work complete end"); }, (void *)asynccallbackinfo, -- Gitee From a84b926af61382890f2031638ff65909dbc4ebdb Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 25 Jan 2022 17:22:02 +0800 Subject: [PATCH 114/131] fix codeCheck Signed-off-by: derek Change-Id: I8ac924a5c41b79f4c478bbcffeb2f9770cf4b5ac --- .../ans/native/src/reminder_request.cpp | 65 +++++++++++-------- .../ans/native/src/reminder_request_alarm.cpp | 38 ++++++----- .../native/src/reminder_request_calendar.cpp | 32 ++++++--- .../reminder_request_calendar_test.cpp | 52 +++++++++++++-- .../ans/native/include/reminder_request.h | 13 +++- .../include/reminder_request_calendar.h | 2 - .../kits/napi/ans/src/reminder/publish.cpp | 1 - services/ans/include/reminder_timer_info.h | 3 +- services/ans/src/reminder_data_manager.cpp | 4 +- 9 files changed, 145 insertions(+), 65 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index bb8245d..f50bdc0 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -107,17 +107,13 @@ bool ReminderRequest::CanShow() const std::string ReminderRequest::Dump() const { - struct tm *timeInfo; - const time_t nextTriggerTime = static_cast(triggerTimeInMilli_ / 1000); - timeInfo = localtime(&nextTriggerTime); - uint8_t dateTimeLen = 80; - char dateTimeBuffer[dateTimeLen]; - (void)strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); + 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=" + dateTimeBuffer + + ", nextTriggerTime=" + dateTimeInfo.c_str() + "]"; } @@ -231,7 +227,8 @@ bool ReminderRequest::HandleSysTimeChange(uint64_t oriTriggerTime, uint64_t optT return showImmediately; } -bool ReminderRequest::HandleTimeZoneChange(uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime) +bool ReminderRequest::HandleTimeZoneChange( + uint64_t oldZoneTriggerTime, uint64_t newZoneTriggerTime, uint64_t optTriggerTime) { if (isExpired_) { return false; @@ -449,8 +446,8 @@ bool ReminderRequest::ShouldShowImmediately() const return true; } -std::map ReminderRequest::GetActionButtons() const +std::map ReminderRequest::GetActionButtons( + ) const { return actionButtonMap_; } @@ -573,7 +570,7 @@ bool ReminderRequest::UpdateNextReminder() void ReminderRequest::UpdateNotificationRequest(UpdateNotificationType type, std::string extra) { - switch(type) { + switch (type) { case UpdateNotificationType::COMMON: { ANSR_LOGI("UpdateNotification common information"); UpdateNotificationCommon(); @@ -861,13 +858,7 @@ bool ReminderRequest::IsAlerting() const std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const { - struct tm *timeInfo; - timeInfo = localtime(&timeInSecond); - uint8_t dateTimeLen = 80; - char dateTimeBuffer[dateTimeLen]; - strftime(dateTimeBuffer, dateTimeLen, "%Y-%m-%d %H:%M:%S", timeInfo); - std::string dateTimeInfo(dateTimeBuffer); - return dateTimeInfo; + return GetTimeInfoInner(timeInSecond, TimeFormat::YMDHMS); } uint64_t ReminderRequest::GetNowInstantMilli() const @@ -886,17 +877,39 @@ std::string ReminderRequest::GetShowTime(const uint64_t showTime) const if (reminderType_ == ReminderType::TIMER) { return ""; } else { - struct tm *timeInfo; - const time_t showTimeInSecond = static_cast(showTime / 1000); - timeInfo = localtime(&showTimeInSecond); - uint8_t dateTimeLen = 80; - char dateTimeBuffer[dateTimeLen]; - strftime(dateTimeBuffer, dateTimeLen, "%H:%M", timeInfo); - std::string time = dateTimeBuffer; - return time; + 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; + 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 = "'"; diff --git a/frameworks/ans/native/src/reminder_request_alarm.cpp b/frameworks/ans/native/src/reminder_request_alarm.cpp index 918736d..f133468 100644 --- a/frameworks/ans/native/src/reminder_request_alarm.cpp +++ b/frameworks/ans/native/src/reminder_request_alarm.cpp @@ -103,6 +103,17 @@ 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; @@ -112,13 +123,6 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const tar.tm_min = minute_; tar.tm_sec = 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_); - const time_t target = mktime(&tar); int8_t nextDayInterval = GetNextAlarm(now, target); time_t nextTriggerTime = 0; @@ -134,6 +138,9 @@ uint64_t ReminderRequestAlarm::GetNextTriggerTime(bool forceToGetNext) const 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), @@ -223,16 +230,15 @@ bool ReminderRequestAlarm::UpdateNextReminder() 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 { - 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; - } + ANSR_LOGW("Set reminder to expired"); + SetExpired(true); + return false; } } return true; diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp index 42dbc30..7e60eec 100644 --- a/frameworks/ans/native/src/reminder_request_calendar.cpp +++ b/frameworks/ans/native/src/reminder_request_calendar.cpp @@ -26,8 +26,8 @@ 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) + 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); @@ -44,7 +44,11 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, uint64_t nextTriggerTime = INVALID_LONG_LONG_VALUE; if ((nextTriggerTime = GetNextTriggerTime()) != INVALID_LONG_LONG_VALUE) { time_t target = static_cast(nextTriggerTime / MILLI_SECONDS); - dateTime_ = *(localtime(&target)); + 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( @@ -82,8 +86,12 @@ uint8_t ReminderRequestCalendar::GetDaysOfMonth(const uint16_t &year, const uint 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 % 4) && (0 != year % 100)) || (0 == year % 400)) ? leapMonth : nonLeapMonth); + days = ((((0 == year % leapParam1) && (0 != year % leapParam2)) || (0 == year % solarYear)) + ? leapMonth : nonLeapMonth); } else { days = daysArray[month - 1]; } @@ -128,8 +136,13 @@ uint64_t ReminderRequestCalendar::GetNextTriggerTime() const { uint64_t triggerTimeInMilli = INVALID_LONG_LONG_VALUE; time_t now; - time(&now); // unit is seconds. - struct tm nowTime = *(localtime(&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_); @@ -232,7 +245,8 @@ bool ReminderRequestCalendar::IsRepeatMonth(uint8_t month) const return (repeatMonth_ & (1 << (month - 1))) > 0; } -bool ReminderRequestCalendar::IsRepeatDay(uint8_t day) const{ +bool ReminderRequestCalendar::IsRepeatDay(uint8_t day) const +{ return (repeatDay_ & (1 << (day - 1))) > 0; } @@ -289,7 +303,7 @@ void ReminderRequestCalendar::SetRepeatDaysOfMonth(const std::vector &r std::vector ReminderRequestCalendar::GetRepeatMonths() const { std::vector repeatMonths; - for (int i = 0; i < 12; i++) { + for (int i = 0; i < MAX_MONTHS_OF_YEAR; i++) { if (IsRepeatMonth(i + 1)) { repeatMonths.push_back(i + 1); } @@ -300,7 +314,7 @@ std::vector ReminderRequestCalendar::GetRepeatMonths() const std::vector ReminderRequestCalendar::GetRepeatDays() const { std::vector repeatDays; - for (int i = 0; i < 31; i++) { + for (int i = 0; i < MAX_DAYS_OF_MONTH; i++) { if (IsRepeatDay(i + 1)) { repeatDays.push_back(i + 1); } diff --git a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp index 89767ab..4396dc2 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp @@ -35,10 +35,15 @@ public: ReminderHelper::CancelAllReminders(); } - std::shared_ptr CreateCalendar(tm &nowTime) { + std::shared_ptr CreateCalendar(tm &nowTime) + { time_t now; time(&now); // unit is seconds. - nowTime = *(localtime(&now)); + tm *tmp = localtime(&now); + if (tmp == nullptr) { + return nullptr; + } + nowTime = *tmp; nowTime.tm_year = 0; nowTime.tm_mon = 0; nowTime.tm_mday = 1; @@ -52,7 +57,8 @@ public: return calendar; } - bool IsVectorEqual(std::vector &vectorA, std::vector &vectorB) { + bool IsVectorEqual(std::vector &vectorA, std::vector &vectorB) + { if (vectorA.size() != vectorB.size()) { return false; } @@ -81,6 +87,9 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00100, Function | SmallTest | { 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."; } @@ -94,6 +103,9 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00200, Function | SmallTest | { 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."; } @@ -107,6 +119,9 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00300, Function | SmallTest | { 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."; } @@ -120,7 +135,12 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00400, Function | SmallTest | { time_t now; time(&now); // unit is seconds. - struct tm nowTime = *(localtime(&now)); + 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); @@ -156,7 +176,11 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00500, Function | SmallTest | { time_t now; time(&now); // unit is seconds. - struct tm nowTime = *(localtime(&now)); + 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; @@ -193,7 +217,11 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00600, Function | SmallTest | { time_t now; time(&now); // unit is seconds. - struct tm nowTime = *(localtime(&now)); + 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); @@ -229,7 +257,11 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00700, Function | SmallTest | { time_t now; time(&now); // unit is seconds. - struct tm nowTime = *(localtime(&now)); + 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; @@ -267,6 +299,9 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00800, Function | SmallTest | { 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."; } @@ -279,6 +314,9 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00900, Function | SmallTest | { 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."; } diff --git a/interfaces/innerkits/ans/native/include/reminder_request.h b/interfaces/innerkits/ans/native/include/reminder_request.h index 65b4ff1..3b06e3b 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request.h +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -87,6 +87,15 @@ public: WEEK }; + /** + * @brief Enumerates the Time format for print. + * + */ + enum class TimeFormat : uint8_t { + YMDHMS, + HM + }; + /** * @brief Attributes of action button. */ @@ -510,7 +519,8 @@ protected: ReminderRequest(); explicit ReminderRequest(ReminderType reminderType); std::string GetDateTimeInfo(const time_t &timeInSecond) const; - virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const { + virtual uint64_t PreGetNextTriggerTimeIgnoreSnooze(bool ignoreRepeat, bool forceToGetNext) const + { return INVALID_LONG_LONG_VALUE; } static const int BASE_YEAR; @@ -521,6 +531,7 @@ private: 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); diff --git a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h index a2b788c..bb7c25a 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h @@ -18,8 +18,6 @@ #include "reminder_request.h" -#include - namespace OHOS { namespace Notification { class ReminderRequestCalendar : public ReminderRequest { diff --git a/interfaces/kits/napi/ans/src/reminder/publish.cpp b/interfaces/kits/napi/ans/src/reminder/publish.cpp index 162dca0..1608449 100644 --- a/interfaces/kits/napi/ans/src/reminder/publish.cpp +++ b/interfaces/kits/napi/ans/src/reminder/publish.cpp @@ -387,7 +387,6 @@ void ParseActionButtons(const napi_env &env, ReminderRequest &reminder, napi_val 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); diff --git a/services/ans/include/reminder_timer_info.h b/services/ans/include/reminder_timer_info.h index 0434923..0d8ddeb 100644 --- a/services/ans/include/reminder_timer_info.h +++ b/services/ans/include/reminder_timer_info.h @@ -31,7 +31,8 @@ public: ReminderTimerInfo(ReminderTimerInfo &other) = delete; ReminderTimerInfo& operator = (const ReminderTimerInfo &other) = delete; - inline void SetAction(const std::string &action) { + inline void SetAction(const std::string &action) + { action_ = action; } diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 584bb5d..25c4424 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -501,8 +501,8 @@ void ReminderDataManager::ShowActiveReminderExtendLocked(sptr & 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()); + 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(); -- Gitee From 64021336b62c9f60fcf78dc9ea0c93f0b86ec423 Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 25 Jan 2022 17:30:22 +0800 Subject: [PATCH 115/131] fix gn format Signed-off-by: derek Change-Id: Ie1e94ede88d2539b49d1ae409211b6c4ad54e8cc --- frameworks/ans/test/moduletest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index 2c117a4..02b2a94 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -341,11 +341,11 @@ group("moduletest") { deps = [] deps += [ + ":ReminderAgentTest", ":ReminderAgentTest", ":ans_fw_module_test", ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", - ":ReminderAgentTest", ] } -- Gitee From bcc85f289e4b128694226b2c6f3c7f78a3da89e2 Mon Sep 17 00:00:00 2001 From: zero-cyc Date: Tue, 25 Jan 2022 15:01:33 +0800 Subject: [PATCH 116/131] chenlien@huawei.com Signed-off-by: zero-cyc Change-Id: Ib0fa36ef1ea9811351616591fe1c16c35da8e79a --- frameworks/ans/native/test/unittest/BUILD.gn | 2 +- frameworks/ans/test/moduletest/BUILD.gn | 8 ++++---- frameworks/wantagent/BUILD.gn | 2 +- .../test/unittest/completed_dispatcher_test/BUILD.gn | 2 +- .../wantagent/test/unittest/pending_want_test/BUILD.gn | 2 +- .../wantagent/test/unittest/trigger_Info_test/BUILD.gn | 2 +- .../test/unittest/want_agent_helper_test/BUILD.gn | 2 +- .../wantagent/test/unittest/want_agent_info_test/BUILD.gn | 2 +- .../wantagent/test/unittest/want_agent_test/BUILD.gn | 2 +- interfaces/kits/napi/wantagent/BUILD.gn | 2 +- notification.gni | 2 +- services/ans/test/unittest/BUILD.gn | 2 +- services/distributed/BUILD.gn | 2 +- services/test/moduletest/BUILD.gn | 2 +- test/common/acts/actsnotificationfuzztest/BUILD.gn | 2 +- 15 files changed, 18 insertions(+), 18 deletions(-) diff --git a/frameworks/ans/native/test/unittest/BUILD.gn b/frameworks/ans/native/test/unittest/BUILD.gn index 2512cfd..2d50fe2 100644 --- a/frameworks/ans/native/test/unittest/BUILD.gn +++ b/frameworks/ans/native/test/unittest/BUILD.gn @@ -48,13 +48,13 @@ ohos_unittest("ans_reminder_unit_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index f4478b3..4d374f2 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -84,12 +84,12 @@ ohos_moduletest("ans_fw_module_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", @@ -162,12 +162,12 @@ ohos_moduletest("ans_innerkits_module_publish_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", @@ -237,12 +237,12 @@ ohos_moduletest("ans_innerkits_module_slot_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", @@ -312,12 +312,12 @@ ohos_moduletest("ans_innerkits_module_setting_test") { external_deps = [ "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", diff --git a/frameworks/wantagent/BUILD.gn b/frameworks/wantagent/BUILD.gn index 3079a9f..4c3a05b 100644 --- a/frameworks/wantagent/BUILD.gn +++ b/frameworks/wantagent/BUILD.gn @@ -69,10 +69,10 @@ ohos_shared_library("wantagent_innerkits") { "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "ces_standard:cesfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "samgr_standard:samgr_proxy", diff --git a/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn index 0e7c0b4..c2fdd1b 100644 --- a/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/completed_dispatcher_test/BUILD.gn @@ -44,11 +44,11 @@ ohos_unittest("completed_dispatcher_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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 e2e2cd6..8c0f2ef 100644 --- a/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/pending_want_test/BUILD.gn @@ -51,11 +51,11 @@ ohos_unittest("pending_want_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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/trigger_Info_test/BUILD.gn b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn index 7085953..936039c 100644 --- a/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/trigger_Info_test/BUILD.gn @@ -44,11 +44,11 @@ ohos_unittest("trigger_Info_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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 a709539..e33afab 100644 --- a/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_helper_test/BUILD.gn @@ -48,11 +48,11 @@ ohos_unittest("want_agent_helper_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn index f5dfa55..0d7bc82 100644 --- a/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_info_test/BUILD.gn @@ -44,11 +44,11 @@ ohos_unittest("want_agent_info_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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/BUILD.gn b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn index f09422c..2d84376 100644 --- a/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn +++ b/frameworks/wantagent/test/unittest/want_agent_test/BUILD.gn @@ -44,11 +44,11 @@ ohos_unittest("want_agent_test") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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/interfaces/kits/napi/wantagent/BUILD.gn b/interfaces/kits/napi/wantagent/BUILD.gn index 305da38..666c747 100644 --- a/interfaces/kits/napi/wantagent/BUILD.gn +++ b/interfaces/kits/napi/wantagent/BUILD.gn @@ -45,9 +45,9 @@ ohos_shared_library("wantagent") { "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "napi:ace_napi", diff --git a/notification.gni b/notification.gni index c35ab1c..8a5ca46 100644 --- a/notification.gni +++ b/notification.gni @@ -32,11 +32,11 @@ aafwk_path = "//foundation/aafwk/standard" ans_standard_external_deps = [ "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", diff --git a/services/ans/test/unittest/BUILD.gn b/services/ans/test/unittest/BUILD.gn index de0decb..13cc23f 100644 --- a/services/ans/test/unittest/BUILD.gn +++ b/services/ans/test/unittest/BUILD.gn @@ -78,12 +78,12 @@ ohos_unittest("ans_unit_test") { "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", diff --git a/services/distributed/BUILD.gn b/services/distributed/BUILD.gn index 43dd484..22c67f6 100644 --- a/services/distributed/BUILD.gn +++ b/services/distributed/BUILD.gn @@ -46,9 +46,9 @@ ohos_shared_library("libans_distributed") { external_deps = [ "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "distributeddatamgr:distributeddata_inner", "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", diff --git a/services/test/moduletest/BUILD.gn b/services/test/moduletest/BUILD.gn index 194d497..43e087b 100644 --- a/services/test/moduletest/BUILD.gn +++ b/services/test/moduletest/BUILD.gn @@ -65,12 +65,12 @@ ohos_moduletest("ans_module_test") { "ability_runtime:abilitykit_native", "ability_runtime:app_manager", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "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", diff --git a/test/common/acts/actsnotificationfuzztest/BUILD.gn b/test/common/acts/actsnotificationfuzztest/BUILD.gn index c033414..cdc3f20 100644 --- a/test/common/acts/actsnotificationfuzztest/BUILD.gn +++ b/test/common/acts/actsnotificationfuzztest/BUILD.gn @@ -79,10 +79,10 @@ ohos_systemtest("ActsNotificationFuzzTest") { "ability_runtime:app_manager", "ability_runtime:base", "ability_runtime:want", - "appexecfwk_standard:libeventhandler", "bundle_framework:appexecfwk_base", "bundle_framework:appexecfwk_core", "dmsfwk_standard:zuri", + "eventhandler:libeventhandler", "hiviewdfx_hilog_native:libhilog", "ipc:ipc_core", "multimedia_image_standard:image_native", -- Gitee From 332dae069c5534f0b22ef6b695813d58177d74a3 Mon Sep 17 00:00:00 2001 From: derek Date: Tue, 25 Jan 2022 19:50:12 +0800 Subject: [PATCH 117/131] fix codeCheck Signed-off-by: derek Change-Id: If8b61587f63c0bf8fdf00352833793757f8ac5ef --- frameworks/ans/native/src/reminder_request.cpp | 7 +++---- frameworks/ans/native/src/reminder_request_calendar.cpp | 2 +- .../test/unittest/reminder_request_calendar_test.cpp | 8 ++++---- 3 files changed, 8 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index f50bdc0..92b8a4b 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -246,7 +246,7 @@ bool ReminderRequest::HandleTimeZoneChange( } else { // case2. timezone change to larger time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. if (static_cast(now) < 0) { ANSR_LOGE("Get now time error"); return false; @@ -864,7 +864,7 @@ std::string ReminderRequest::GetDateTimeInfo(const time_t &timeInSecond) const uint64_t ReminderRequest::GetNowInstantMilli() const { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. if (static_cast(now) < 0) { ANSR_LOGE("Get now time error"); return 0; @@ -886,8 +886,7 @@ std::string ReminderRequest::GetTimeInfoInner(const time_t &timeInSecond, const { uint8_t dateTimeLen = 80; char dateTimeBuffer[dateTimeLen]; - struct tm *timeInfo; - timeInfo = localtime(&timeInSecond); + struct tm *timeInfo = localtime(&timeInSecond); if (timeInfo == nullptr) { ANSR_LOGW("GetTimeInfoInner fail."); } else { diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp index 7e60eec..2fa11c5 100644 --- a/frameworks/ans/native/src/reminder_request_calendar.cpp +++ b/frameworks/ans/native/src/reminder_request_calendar.cpp @@ -44,7 +44,7 @@ ReminderRequestCalendar::ReminderRequestCalendar(const tm &dateTime, 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); + tm *tar = localtime(&target); if (tar == nullptr) { throw std::invalid_argument("Get localtime error"); } diff --git a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp index 4396dc2..77c61bb 100644 --- a/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp +++ b/frameworks/ans/native/test/unittest/reminder_request_calendar_test.cpp @@ -38,7 +38,7 @@ public: std::shared_ptr CreateCalendar(tm &nowTime) { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. tm *tmp = localtime(&now); if (tmp == nullptr) { return nullptr; @@ -134,7 +134,7 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00300, Function | SmallTest | HWTEST_F(ReminderRequestCalendarTest, initDateTime_00400, Function | SmallTest | Level1) { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. tm *tmp = localtime(&now); if (tmp == nullptr) { EXPECT_TRUE(false) << "calendar is null"; @@ -216,7 +216,7 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00500, Function | SmallTest | HWTEST_F(ReminderRequestCalendarTest, initDateTime_00600, Function | SmallTest | Level1) { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. tm *tmp = localtime(&now); if (tmp == nullptr) { EXPECT_TRUE(false) << "calendar is null"; @@ -256,7 +256,7 @@ HWTEST_F(ReminderRequestCalendarTest, initDateTime_00600, Function | SmallTest | HWTEST_F(ReminderRequestCalendarTest, initDateTime_00700, Function | SmallTest | Level1) { time_t now; - time(&now); // unit is seconds. + (void)time(&now); // unit is seconds. tm *tmp = localtime(&now); if (tmp == nullptr) { EXPECT_TRUE(false) << "calendar is null"; -- Gitee From bb5568e1ceeff9e79ba79de48457950a4f1c80df Mon Sep 17 00:00:00 2001 From: liqiang Date: Tue, 25 Jan 2022 20:49:23 +0800 Subject: [PATCH 118/131] IsueNo:#I4S78C Description:fix displaybadge xts timeout fail bug Sig: SIG_ApplicationFramework Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: liqiang Change-Id: I5403b1841b8b054a8b39b2b043bf76707ab8110d --- interfaces/kits/napi/ans/src/common.cpp | 15 +++++-- .../kits/napi/ans/src/display_badge.cpp | 42 +++++++++++++++---- 2 files changed, 45 insertions(+), 12 deletions(-) diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index a86f7c8..f2ee37a 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -3621,10 +3621,16 @@ 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.SetBundleName(str); @@ -3634,7 +3640,10 @@ napi_value Common::GetBundleOption(const napi_env &env, const napi_value &value, 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."); + if (valuetype != napi_number) { + ANS_LOGE("Wrong argument type. Number expected."); + return nullptr; + } napi_get_value_int32(env, result, &uid); option.SetUid(uid); } diff --git a/interfaces/kits/napi/ans/src/display_badge.cpp b/interfaces/kits/napi/ans/src/display_badge.cpp index 3484b24..71da17f 100644 --- a/interfaces/kits/napi/ans/src/display_badge.cpp +++ b/interfaces/kits/napi/ans/src/display_badge.cpp @@ -57,12 +57,19 @@ 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[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + 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."); @@ -71,13 +78,19 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: enable NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + 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[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } @@ -92,14 +105,21 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[IS_DISPLAY_BADGE_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= IS_DISPLAY_BADGE_MIN_PARA, "Wrong number of arguments"); + + 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[PARAM0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_function) || (valuetype == napi_object), - "Wrong argument type. Function or object expected."); + + 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[PARAM0], params.option); if (retValue == nullptr) { @@ -114,7 +134,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]:callback if (argc >= IS_DISPLAY_BADGE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } @@ -213,6 +236,7 @@ napi_value IsBadgeDisplayed(napi_env env, napi_callback_info info) IsDisplayBadgeParams params {}; if (ParseParameters(env, info, params) == nullptr) { + ANS_LOGE("Failed to parse params!"); return Common::NapiGetUndefined(env); } -- Gitee From a99ffb6af4aafc7ad928ee209527f999b20f755b Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 26 Jan 2022 10:26:53 +0800 Subject: [PATCH 119/131] fix codeCheck Signed-off-by: derek Change-Id: Ifb5b3c7aee4c4a4e33a887799a24a616e0b56967 --- .../ans/native/src/reminder_request.cpp | 2 +- .../ans/native/include/reminder_request.h | 46 ++++++++++++++++--- .../native/include/reminder_request_alarm.h | 2 +- .../include/reminder_request_calendar.h | 2 +- .../native/include/reminder_request_timer.h | 2 +- 5 files changed, 44 insertions(+), 10 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request.cpp b/frameworks/ans/native/src/reminder_request.cpp index 92b8a4b..3b27d3b 100644 --- a/frameworks/ans/native/src/reminder_request.cpp +++ b/frameworks/ans/native/src/reminder_request.cpp @@ -82,7 +82,7 @@ ReminderRequest::ReminderRequest(ReminderType reminderType) maxScreenWantAgentInfo_ == nullptr ? std::make_shared() : maxScreenWantAgentInfo_; } -bool ReminderRequest::CanRemove() +bool ReminderRequest::CanRemove() const { if ((state_ & (REMINDER_STATUS_SHOWING | REMINDER_STATUS_ALERTING | REMINDER_STATUS_ACTIVE)) == 0) { return true; diff --git a/interfaces/innerkits/ans/native/include/reminder_request.h b/interfaces/innerkits/ans/native/include/reminder_request.h index 3b06e3b..b671414 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request.h +++ b/interfaces/innerkits/ans/native/include/reminder_request.h @@ -89,7 +89,6 @@ public: /** * @brief Enumerates the Time format for print. - * */ enum class TimeFormat : uint8_t { YMDHMS, @@ -131,7 +130,7 @@ public: */ explicit ReminderRequest(const ReminderRequest &other); ReminderRequest& operator = (const ReminderRequest &other); - virtual ~ReminderRequest() {}; + virtual ~ReminderRequest() override {}; /** * @brief Marshal a NotificationRequest object into a Parcel. @@ -153,7 +152,7 @@ public: * * @return true if it can be removed automatically. */ - bool CanRemove(); + bool CanRemove() const; bool CanShow() const; @@ -292,7 +291,10 @@ public: bool IsShowing() const; /** - * @brief Close the reminder by manual. + * @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. */ @@ -312,17 +314,50 @@ public: void OnSameNotificationIdCovered(); /** - * @brief Show the reminder on panel. TriggerTime will be updated to next. + * @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(); /** @@ -592,5 +627,4 @@ private: }; } // 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 index 5d7471e..07239f1 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_alarm.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_alarm.h @@ -47,7 +47,7 @@ public: */ explicit ReminderRequestAlarm(const ReminderRequestAlarm &other); ReminderRequestAlarm& operator = (const ReminderRequestAlarm &other); - ~ReminderRequestAlarm() {}; + ~ReminderRequestAlarm() override {}; /** * Obtains the repeat days vector. diff --git a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h index bb7c25a..b315ad8 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h @@ -54,7 +54,7 @@ public: explicit ReminderRequestCalendar(const ReminderRequestCalendar &other); ReminderRequestCalendar& operator = (const ReminderRequestCalendar &other); - ~ReminderRequestCalendar() {} + ~ReminderRequestCalendar() override {} inline uint16_t GetYear() const { diff --git a/interfaces/innerkits/ans/native/include/reminder_request_timer.h b/interfaces/innerkits/ans/native/include/reminder_request_timer.h index a33c014..9fc2362 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_timer.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_timer.h @@ -40,7 +40,7 @@ public: */ explicit ReminderRequestTimer(const ReminderRequestTimer &other); ReminderRequestTimer& operator = (const ReminderRequestTimer &other); - ~ReminderRequestTimer() {}; + ~ReminderRequestTimer() override {}; uint64_t GetInitInfo() const; virtual bool OnDateTimeChange() override; -- Gitee From a5c3fcaffa46fd8b91d94a4996c0753a4741a5d9 Mon Sep 17 00:00:00 2001 From: liqiang Date: Wed, 26 Jan 2022 10:32:45 +0800 Subject: [PATCH 120/131] IssueNo:https://gitee.com/openharmony/notification_ans_standard/issues/I4S87I?from=project-issue Description:fix ActsAnsEnableNotificationTest xts timeout bug Sig: SIG_ApplicationFramework Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: liqiang Change-Id: I989ca4a832f02fffc98fd55cb8d2ad5188740105 --- .../kits/napi/ans/src/enable_notification.cpp | 32 ++++++++++++++----- 1 file changed, 24 insertions(+), 8 deletions(-) diff --git a/interfaces/kits/napi/ans/src/enable_notification.cpp b/interfaces/kits/napi/ans/src/enable_notification.cpp index 7850a4f..c9b896d 100644 --- a/interfaces/kits/napi/ans/src/enable_notification.cpp +++ b/interfaces/kits/napi/ans/src/enable_notification.cpp @@ -56,12 +56,18 @@ 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[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type. Object expected."); + 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."); @@ -70,13 +76,19 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]: enable NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_boolean, "Wrong argument type. Bool expected."); + 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[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, ¶ms.callback); } @@ -99,9 +111,10 @@ 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[PARAM0], &valuetype)); - NAPI_ASSERT(env, - (valuetype == napi_function) || (valuetype == napi_object), - "Wrong argument type. Function or object expected."); + 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[PARAM0], params.option); if (retValue == nullptr) { @@ -116,7 +129,10 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, // argv[1]:callback if (argc >= IS_NOTIFICATION_ENABLE_MAX_PARA) { NAPI_CALL(env, napi_typeof(env, argv[PARAM1], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGW("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM1], 1, ¶ms.callback); } -- Gitee From 92c2d1f48640e2b915a9a883fa79bc087c546621 Mon Sep 17 00:00:00 2001 From: zengsiyu Date: Wed, 26 Jan 2022 11:27:21 +0800 Subject: [PATCH 121/131] fix: fix constants Signed-off-by: zengsiyu Change-Id: Ia9d99caf83e1cb3158d3ea24d2d0a524459df506 --- .../ans/src/advanced_notification_service.cpp | 30 +++++++++++++------ 1 file changed, 21 insertions(+), 9 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index eb2b4d0..795c9ca 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -46,17 +46,18 @@ namespace OHOS { namespace Notification { namespace { -static const std::string ACTIVE_NOTIFICATION_OPTION = "active"; -static const std::string RECENT_NOTIFICATION_OPTION = "recent"; +constexpr char ACTIVE_NOTIFICATION_OPTION[] = "active"; +constexpr char RECENT_NOTIFICATION_OPTION[] = "recent"; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -static const std::string DISTRIBUTED_NOTIFICATION_OPTION = "distributed"; +constexpr char DISTRIBUTED_NOTIFICATION_OPTION[] = "distributed"; #endif -static const std::string SET_RECENT_COUNT_OPTION = "setRecentCount"; +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; @@ -170,7 +171,7 @@ ErrCode PrepereNotificationRequest(const sptr &request) int pid = IPCSkeleton::GetCallingPid(); 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) { @@ -1485,6 +1486,14 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt return ERR_ANS_NOT_SYSTEM_SERVICE; } + 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) { @@ -2293,7 +2302,7 @@ ErrCode AdvancedNotificationService::SetDoNotDisturbDate(const sptrPostSyncTask(std::bind([&]() { result = NotificationPreferences::GetInstance().SetDoNotDisturbDate(bundleOption, newConfig); if (result == ERR_OK) { @@ -2366,6 +2375,9 @@ ErrCode AdvancedNotificationService::DoesSupportDoNotDisturbMode(bool &doesSuppo 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; -- Gitee From 0ad69adcfac28e898201a955dab60f24de8ae46c Mon Sep 17 00:00:00 2001 From: fangJinliang1 Date: Tue, 25 Jan 2022 19:17:18 +0800 Subject: [PATCH 122/131] add notification flags Signed-off-by: fangJinliang1 Change-Id: If5f7e6385128544df49e4dcbd33877d4132efad3 Signed-off-by: fangJinliang1 --- frameworks/ans/core/BUILD.gn | 1 + frameworks/ans/native/BUILD.gn | 1 + .../ans/native/src/notification_flags.cpp | 114 ++++++++++++++++++ .../ans/native/src/notification_request.cpp | 73 +++++++++++ .../ans_innerkits_module_publish_test.cpp | 51 ++++++++ .../ans/native/include/notification_flags.h | 107 ++++++++++++++++ .../ans/native/include/notification_request.h | 15 +++ .../kits/js/notification/notificationFlags.ts | 35 ++++++ .../js/notification/notificationRequest.d.ts | 8 ++ interfaces/kits/napi/ans/include/common.h | 3 + interfaces/kits/napi/ans/src/common.cpp | 39 +++++- 11 files changed, 445 insertions(+), 2 deletions(-) create mode 100644 frameworks/ans/native/src/notification_flags.cpp create mode 100644 interfaces/innerkits/ans/native/include/notification_flags.h create mode 100644 interfaces/kits/js/notification/notificationFlags.ts diff --git a/frameworks/ans/core/BUILD.gn b/frameworks/ans/core/BUILD.gn index 346ddd6..6aff569 100644 --- a/frameworks/ans/core/BUILD.gn +++ b/frameworks/ans/core/BUILD.gn @@ -59,6 +59,7 @@ ohos_shared_library("ans_core") { "${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", diff --git a/frameworks/ans/native/BUILD.gn b/frameworks/ans/native/BUILD.gn index 831a1d1..ae41de7 100644 --- a/frameworks/ans/native/BUILD.gn +++ b/frameworks/ans/native/BUILD.gn @@ -56,6 +56,7 @@ ohos_shared_library("ans_innerkits") { "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", diff --git a/frameworks/ans/native/src/notification_flags.cpp b/frameworks/ans/native/src/notification_flags.cpp new file mode 100644 index 0000000..901964b --- /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_request.cpp b/frameworks/ans/native/src/notification_request.cpp index 463ffe7..a486bb3 100644 --- a/frameworks/ans/native/src/notification_request.cpp +++ b/frameworks/ans/native/src/notification_request.cpp @@ -679,6 +679,7 @@ std::string NotificationRequest::Dump() ", messageUsers = " + (!messageUsers_.empty() ? messageUsers_.at(0)->Dump() : "empty") + ", userInputHistory = " + (!userInputHistory_.empty() ? userInputHistory_.at(0) : "empty") + ", distributedOptions = " + distributedOptions_.Dump() + + ", notificationFlags = " + (notificationFlags_ ? "not null" : "null") + " }"; } @@ -777,6 +778,12 @@ NotificationRequest *NotificationRequest::FromJson(const nlohmann::json &jsonObj return nullptr; } + if (!ConvertJsonToNotificationFlags(pRequest, jsonObject)) { + delete pRequest; + pRequest = nullptr; + return nullptr; + } + return pRequest; } @@ -1127,6 +1134,19 @@ bool NotificationRequest::Marshalling(Parcel &parcel) const } } + 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; } @@ -1337,6 +1357,15 @@ bool NotificationRequest::ReadFromParcel(Parcel &parcel) } } + valid = parcel.ReadBool(); + if (valid) { + notificationFlags_ = std::shared_ptr(parcel.ReadParcelable()); + if (!notificationFlags_) { + ANS_LOGE("Failed to read notificationFlags"); + return false; + } + } + return true; } @@ -1359,6 +1388,16 @@ 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_; @@ -1422,6 +1461,7 @@ void NotificationRequest::CopyOther(const NotificationRequest &other) this->distributedOptions_ = other.distributedOptions_; this->notificationTemplate_ = other.notificationTemplate_; + this->notificationFlags_ = other.notificationFlags_; } bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const @@ -1470,6 +1510,13 @@ bool NotificationRequest::ConvertObjectsToJson(nlohmann::json &jsonObject) const } 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; } @@ -1692,5 +1739,31 @@ bool NotificationRequest::ConvertJsonToNotificationDistributedOptions( 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/test/moduletest/ans_innerkits_module_publish_test.cpp b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp index b9115de..a8ac9f3 100644 --- a/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp +++ b/frameworks/ans/test/moduletest/ans_innerkits_module_publish_test.cpp @@ -55,6 +55,7 @@ const int32_t CASE_ELEVEN = 11; const int32_t CASE_TWELVE = 12; const int32_t CASE_THIRTEEN = 13; const int32_t CASE_FOURTEEN = 14; +const int32_t CASE_FIFTEEN = 15; const int32_t CALLING_UID = 9999; const int32_t PIXEL_MAP_TEST_WIDTH = 32; @@ -136,6 +137,8 @@ public: 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!!!!!"; } @@ -369,6 +372,15 @@ private: } 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 { @@ -1327,5 +1339,44 @@ HWTEST_F(AnsInterfaceModulePublishTest, ANS_Interface_MT_Publish_08000, Function 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 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); + 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(req)); + WaitOnConsumed(); + g_unsubscribe_mtx.lock(); + EXPECT_EQ(0, NotificationHelper::UnSubscribeNotification(subscriber, info)); + WaitOnUnsubscribeResult(); +} } // namespace Notification } // namespace OHOS \ 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 0000000..09664ed --- /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_request.h b/interfaces/innerkits/ans/native/include/notification_request.h index 93b5f2d..e2f6190 100644 --- a/interfaces/innerkits/ans/native/include/notification_request.h +++ b/interfaces/innerkits/ans/native/include/notification_request.h @@ -20,6 +20,7 @@ #include "notification_action_button.h" #include "notification_content.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" @@ -915,6 +916,18 @@ public: */ 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). @@ -958,6 +971,7 @@ private: 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}; @@ -1019,6 +1033,7 @@ private: NotificationDistributedOptions distributedOptions_; std::shared_ptr notificationTemplate_ {}; + std::shared_ptr notificationFlags_ {}; }; } // namespace Notification } // namespace OHOS diff --git a/interfaces/kits/js/notification/notificationFlags.ts b/interfaces/kits/js/notification/notificationFlags.ts new file mode 100644 index 0000000..58c4a68 --- /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/notificationRequest.d.ts b/interfaces/kits/js/notification/notificationRequest.d.ts index 6525bf1..971ecb0 100644 --- a/interfaces/kits/js/notification/notificationRequest.d.ts +++ b/interfaces/kits/js/notification/notificationRequest.d.ts @@ -19,6 +19,7 @@ import { WantAgent } from '../@ohos.wantAgent'; import { NotificationContent } from './notificationContent'; import { NotificationActionButton } from './notificationActionButton'; import { NotificationTemplate } from './notificationTemplate'; +import { NotificationFlags } from './notificationFlags'; /** * Defines a NotificationRequest instance. @@ -197,4 +198,11 @@ export interface NotificationRequest { * @since 8 */ template?: NotificationTemplate; + + /** + * Obtains the set of identifiers for the notification. + * + * @since 8 + */ + readonly notificationFlags?: NotificationFlags; } diff --git a/interfaces/kits/napi/ans/include/common.h b/interfaces/kits/napi/ans/include/common.h index f77e712..ba4cd1a 100644 --- a/interfaces/kits/napi/ans/include/common.h +++ b/interfaces/kits/napi/ans/include/common.h @@ -429,6 +429,9 @@ public: 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; diff --git a/interfaces/kits/napi/ans/src/common.cpp b/interfaces/kits/napi/ans/src/common.cpp index 2097b51..b7edb7c 100644 --- a/interfaces/kits/napi/ans/src/common.cpp +++ b/interfaces/kits/napi/ans/src/common.cpp @@ -548,7 +548,7 @@ napi_value Common::SetNotificationRequestByCustom( } napi_set_named_property(env, result, "actionButtons", arr); - // template?: NotificationTemplate; + // template?: NotificationTemplate std::shared_ptr templ = request->GetTemplate(); if (templ) { napi_value templateResult = nullptr; @@ -560,6 +560,18 @@ napi_value Common::SetNotificationRequestByCustom( 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); } @@ -4074,5 +4086,28 @@ napi_value Common::SetNotificationTemplateInfo( 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 \ No newline at end of file +} // namespace OHOS -- Gitee From 2933f75494a297ce33b40d7c863855143b10411b Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 26 Jan 2022 16:05:12 +0800 Subject: [PATCH 123/131] fix ringDuration stop sound Signed-off-by: derek Change-Id: If52fc465ca4f5bc2ee5afeb6bed00b6d13054f96 --- services/ans/include/reminder_event_manager.h | 2 +- services/ans/src/reminder_data_manager.cpp | 2 ++ 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/ans/include/reminder_event_manager.h b/services/ans/include/reminder_event_manager.h index bfc7214..09c908f 100644 --- a/services/ans/include/reminder_event_manager.h +++ b/services/ans/include/reminder_event_manager.h @@ -44,7 +44,7 @@ private: 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_; + std::shared_ptr reminderDataManager_ = nullptr; }; }; } // namespace OHOS diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 25c4424..8d73a2f 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -874,6 +874,8 @@ void ReminderDataManager::StopSoundAndVibration(const sptr &rem } ANSR_LOGD("Stop sound and vibration, reminderId=%{public}d", reminder->GetReminderId()); soundPlayer_->Stop(); + soundPlayer_->Release(); + soundPlayer_ = nullptr; sptr nullReminder = nullptr; SetAlertingReminder(nullReminder); } -- Gitee From e81d8cb114623a0342584d58a30465155c0a9daf Mon Sep 17 00:00:00 2001 From: derek Date: Wed, 26 Jan 2022 16:35:30 +0800 Subject: [PATCH 124/131] add js test cases Signed-off-by: derek Change-Id: I9c1c30d853eb3e2d0700496cbf9b8296521f1179 --- frameworks/ans/test/moduletest/BUILD.gn | 5 +- ...lperTest.test.js => ReminderHelperTest.js} | 488 +++++++++++++----- frameworks/ans/test/moduletest/config.json | 2 +- 3 files changed, 369 insertions(+), 126 deletions(-) rename frameworks/ans/test/moduletest/{ReminderHelperTest.test.js => ReminderHelperTest.js} (54%) diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index 02b2a94..83e278a 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -329,7 +329,7 @@ ohos_moduletest("ans_innerkits_module_setting_test") { part_name = "ans_standard" } -ohos_js_unittest("ReminderAgentTest") { +ohos_js_unittest("ReminderAgentJsTest") { module_out_path = module_output_path hap_profile = "./config.json" @@ -341,11 +341,10 @@ group("moduletest") { deps = [] deps += [ - ":ReminderAgentTest", - ":ReminderAgentTest", ":ans_fw_module_test", ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", + ":ReminderAgentJsTest", ] } diff --git a/frameworks/ans/test/moduletest/ReminderHelperTest.test.js b/frameworks/ans/test/moduletest/ReminderHelperTest.js similarity index 54% rename from frameworks/ans/test/moduletest/ReminderHelperTest.test.js rename to frameworks/ans/test/moduletest/ReminderHelperTest.js index d4b0c18..c61a047 100644 --- a/frameworks/ans/test/moduletest/ReminderHelperTest.test.js +++ b/frameworks/ans/test/moduletest/ReminderHelperTest.js @@ -145,19 +145,13 @@ describe("ReminderHelperTest", function () { */ it("testReminderHelper005", 0, async function (done) { let mySlot = { - type: 3 + type: 2 } reminderAgent.addNotificationSlot(mySlot).then(() => { - expect(true).assertTrue(); - setTimeout(() => { - done(); - }, 500); - }, (error) => { - expect(false).assertTrue(); - setTimeout(() => { - done(); - }, 500); + let i = 0; + expect(i).assertEqual(0); }); + done(); }) /* @@ -167,36 +161,11 @@ describe("ReminderHelperTest", function () { * @tc.require: */ it("testReminderHelper006", 0, async function (done) { - let mySlot0 = { - type: 0 - } - let mySlot1 = { - type: 1 - } - let mySlot2 = { - type: 2 - } - let mySlot3 = { - type: 3 - } - let mySlot4 = { - type: 4 - } - function reminderCallback(err, data){ - if (err) { - expect(true).assertTrue(); - } else { - expect(false).assertTrue(); - } - setTimeout(() => { - done(); - }, 500); - } - reminderAgent.addNotificationSlot(mySlot0, reminderCallback); - reminderAgent.addNotificationSlot(mySlot1, reminderCallback); - reminderAgent.addNotificationSlot(mySlot2, reminderCallback); - reminderAgent.addNotificationSlot(mySlot3, reminderCallback); - reminderAgent.addNotificationSlot(mySlot4, reminderCallback); + reminderAgent.addNotificationSlot(3, (err, data) => { + let i = 0; + expect(i).assertEqual(0); + }); + done(); }) /* @@ -210,16 +179,25 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 } - reminderAgent.publishReminder(timer).then((reminderId) => { - reminderAgent.getValidReminders().then((reminders) => {}); - setTimeout(() => { - reminderAgent.cancelAllReminders().then(() => { - reminderAgent.getValidReminders().then((reminders) => { - expect(0).assertEqual(reminders.length); - }); + 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); }); - }, 1000); - }); + }); + }, 5000); done(); }) @@ -234,16 +212,25 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 } - reminderAgent.publishReminder(timer, (error, reminderId) => { - reminderAgent.getValidReminders((err, reminders) => {}); - setTimeout(() => { - reminderAgent.cancelAllReminders((err, data) => { - reminderAgent.getValidReminders().then((reminders) => { - expect(0).assertEqual(reminders.length); - }); + 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); }); - }, 1000); - }); + }); + }, 5000); done(); }) @@ -256,7 +243,7 @@ describe("ReminderHelperTest", function () { it("testReminderHelper009", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 100 + triggerTimeInSeconds: 3 } let id = 1; let publishlength = -1; @@ -265,18 +252,14 @@ describe("ReminderHelperTest", function () { reminderAgent.publishReminder(timer).then(() => { reminderAgent.getValidReminders().then((reminders) => { publishlength=reminders.length - }); - setTimeout(() => { reminderAgent.cancelReminder(id).then(() => { reminderAgent.getValidReminders().then((reminders) => { cancellength = reminders.length - firstdiff = publishlength-cancellength; - if (firstdiff === 0) { - expect(0).assertEqual(firstdiff); - } + firstdiff = publishlength - cancellength; + expect(0).assertEqual(firstdiff); }); }); - }, 1000); + }); }); done(); }) @@ -290,33 +273,27 @@ describe("ReminderHelperTest", function () { it("testReminderHelper010", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, - triggerTimeInSeconds: 100 + triggerTimeInSeconds: 3 } - let id = 1; let publishlength = -1; let cancellength = -1; let firstdiff = -1; reminderAgent.publishReminder(timer).then(() => { reminderAgent.getValidReminders((err, reminders) => { publishlength = reminders.length; - }); - setTimeout(() => { - reminderAgent.cancelReminder(id,(err,data)=>{ + reminderAgent.cancelReminder(0, (err, data)=>{ reminderAgent.getValidReminders((err, reminders) => { cancellength = reminders.length; - firstdiff = publishlength-cancellength; - if (firstdiff === 0) { - expect(0).assertEqual(firstdiff); - } + firstdiff = publishlength - cancellength; + expect(0).assertEqual(firstdiff); }); }); - }, 1000); + }); }); done(); }) - - /* + /* * @tc.name: testReminderHelper011 * @tc.desc: test cancelReminder with exist reminder. * @tc.type: FUNC @@ -410,16 +387,15 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 } - reminderAgent.publishReminder(timer, (error, reminderId) => {}); - reminderAgent.publishReminder(alarm, (error, reminderId) => {}); - setTimeout(() => { - reminderAgent.getValidReminders().then((reminders) => { - if (reminders.length >= 2) { - let i = 0; - expect(0).assertEqual(i); - } - }); - }, 1000); + 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(); }) @@ -441,16 +417,15 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 } - reminderAgent.publishReminder(timer, (error, reminderId) => {}); - reminderAgent.publishReminder(alarm, (error, reminderId) => {}); - setTimeout(() => { - reminderAgent.getValidReminders((err, reminders) => { - if (reminders.length >= 2) { - let i = 0; - expect(0).assertEqual(i); - } - }); - }, 1000); + 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(); }) @@ -461,12 +436,12 @@ describe("ReminderHelperTest", function () { * @tc.require: */ it("testReminderHelper015", 0, function (done) { - function reminderCallback(err, data){ - let i = 0; - expect(0).assertEqual(i); - } - reminderAgent.removeNotificationSlot(0, reminderCallback); - done(); + function reminderCallback(err, data){ + let i = 0; + expect(0).assertEqual(i); + } + reminderAgent.removeNotificationSlot(0, reminderCallback); + done(); }) /* @@ -502,7 +477,7 @@ describe("ReminderHelperTest", function () { } reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { reminderAgent.removeNotificationSlot(tarRemoveSlot.type, (err, data) => { - expect(0).assertEqual(err.code); + expect(0).assertEqual(err.code); }); }); done(); @@ -520,7 +495,8 @@ describe("ReminderHelperTest", function () { } reminderAgent.addNotificationSlot(tarRemoveSlot.type, (err, data) => { reminderAgent.removeNotificationSlot(tarRemoveSlot.type).then(() => { - expect(0).assertEqual(err.code); + let i = 0; + expect(0).assertEqual(i); }); }); done(); @@ -537,10 +513,10 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } - reminderAgent.publishReminder(timer).then((reminderId) => {}); + reminderAgent.publishReminder(timer).then((reminderId) => { }); setTimeout(() => { reminderAgent.getValidReminders().then((reminders) => { - expect(0).assertEqual(reminders.length); + expect(reminders.length === 0).assertEqual(true); }); }, 5000); done(); @@ -557,10 +533,10 @@ describe("ReminderHelperTest", function () { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 3 } - reminderAgent.publishReminder(timer).then((reminderId) => {}); + reminderAgent.publishReminder(timer, (err, data) => { }); setTimeout(() => { reminderAgent.getValidReminders((err, reminders) => { - expect(0).assertEqual(reminders.length); + expect(reminders.length === 0).assertEqual(true); }); }, 5000); done(); @@ -576,13 +552,13 @@ describe("ReminderHelperTest", function () { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, - minute: 14 + minute: 14, + title: "this is title", + content: "this is content" } reminderAgent.publishReminder(alarm).then((reminderId) => { - if (reminderId) { - let i = 0; - expect(0).assertEqual(i); - } + let i = 0; + expect(i).assertEqual(0); }); done(); }) @@ -597,13 +573,13 @@ describe("ReminderHelperTest", function () { let alarm = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_ALARM, hour: 21, - minute: 14 + minute: 14, + title: "this is title", + content: "this is content" } function reminderCallback (err, reminderId) { - if (reminderId) { - let i = 0; - expect(0).assertEqual(i); - } + let i = 0; + expect(i).assertEqual(0); } reminderAgent.publishReminder(alarm, reminderCallback); done(); @@ -611,11 +587,277 @@ describe("ReminderHelperTest", function () { /* * @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("testReminderHelper023", 0, async function (done) { + it("testReminderHelper027", 0, async function (done) { let timer = { reminderType: reminderAgent.ReminderType.REMINDER_TYPE_TIMER, triggerTimeInSeconds: 100 @@ -623,9 +865,10 @@ describe("ReminderHelperTest", function () { let maxLimitNumsOfApp = 30; let firstId = 0; let secondId = 0; - let diffId = 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) { @@ -635,6 +878,7 @@ describe("ReminderHelperTest", function () { secondId = reminderId diffId = secondId - firstId expect(29).assertEqual(diffId); + i = null } }); }, 500 * i); diff --git a/frameworks/ans/test/moduletest/config.json b/frameworks/ans/test/moduletest/config.json index d779db8..7d3bb16 100644 --- a/frameworks/ans/test/moduletest/config.json +++ b/frameworks/ans/test/moduletest/config.json @@ -8,7 +8,7 @@ }, "apiVersion": { "compatible": 4, - "target": 5 + "target": 8 } }, "deviceConfig": {}, -- Gitee From 172f46b87f972658279e2f017f567b9d6480ef2c Mon Sep 17 00:00:00 2001 From: njupthan Date: Thu, 27 Jan 2022 17:12:46 +0000 Subject: [PATCH 125/131] Modify the problem of incomplete dump output Signed-off-by: njupthan --- tools/dump/include/notification_shell_command.h | 7 +++---- tools/dump/src/notification_shell_command.cpp | 15 ++++++--------- 2 files changed, 9 insertions(+), 13 deletions(-) diff --git a/tools/dump/include/notification_shell_command.h b/tools/dump/include/notification_shell_command.h index bede4da..26fc519 100644 --- a/tools/dump/include/notification_shell_command.h +++ b/tools/dump/include/notification_shell_command.h @@ -34,12 +34,11 @@ private: ErrCode RunAsDumpCommand(); ErrCode RunHelp(); - ErrCode RunActive(); - ErrCode RunRecent(); + ErrCode RunActive(std::vector &infos); + ErrCode RunRecent(std::vector &infos); #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED - ErrCode RunDistributed(); + ErrCode RunDistributed(std::vector &infos); #endif - ErrCode RunSetRecentCount(); private: std::shared_ptr ans_; diff --git a/tools/dump/src/notification_shell_command.cpp b/tools/dump/src/notification_shell_command.cpp index 2d44785..97de8dd 100644 --- a/tools/dump/src/notification_shell_command.cpp +++ b/tools/dump/src/notification_shell_command.cpp @@ -99,10 +99,9 @@ ErrCode NotificationShellCommand::RunHelp() return ERR_OK; } -ErrCode NotificationShellCommand::RunActive() +ErrCode NotificationShellCommand::RunActive(std::vector &infos) { ErrCode ret = ERR_OK; - std::vector infos; if (ans_ != nullptr) { ret = ans_->ShellDump("active", infos); resultReceiver_.append("Total:" + std::to_string(infos.size()) + "\n"); @@ -112,10 +111,9 @@ ErrCode NotificationShellCommand::RunActive() return ret; } -ErrCode NotificationShellCommand::RunRecent() +ErrCode NotificationShellCommand::RunRecent(std::vector &infos) { ErrCode ret = ERR_OK; - std::vector infos; if (ans_ != nullptr) { ret = ans_->ShellDump("recent", infos); resultReceiver_.append("Total:" + std::to_string(infos.size()) + "\n"); @@ -126,10 +124,9 @@ ErrCode NotificationShellCommand::RunRecent() } #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED -ErrCode NotificationShellCommand::RunDistributed() +ErrCode NotificationShellCommand::RunDistributed(std::vector &infos) { ErrCode ret = ERR_OK; - std::vector infos; if (ans_ != nullptr) { ret = ans_->ShellDump("distributed", infos); resultReceiver_.append("Total:" + std::to_string(infos.size()) + "\n"); @@ -157,14 +154,14 @@ ErrCode NotificationShellCommand::RunAsDumpCommand() ret = RunHelp(); break; case 'A': - ret = RunActive(); + ret = RunActive(infos); break; case 'R': - ret = RunRecent(); + ret = RunRecent(infos); break; #ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED case 'D': - ret = RunDistributed(); + ret = RunDistributed(infos); break; #endif case 0: -- Gitee From a873ab991dc75dbdd73b48b4673b934589382720 Mon Sep 17 00:00:00 2001 From: derek Date: Fri, 28 Jan 2022 09:50:38 +0800 Subject: [PATCH 126/131] fix codeCheck Signed-off-by: derek Change-Id: I6341fc8c2850df4593b67e347ddddba0c35aec8c --- .../ans/native/src/reminder_request_calendar.cpp | 2 +- .../ans/native/include/reminder_request_calendar.h | 2 +- services/ans/include/reminder_data_manager.h | 2 +- services/ans/src/reminder_data_manager.cpp | 12 ++++++------ 4 files changed, 9 insertions(+), 9 deletions(-) diff --git a/frameworks/ans/native/src/reminder_request_calendar.cpp b/frameworks/ans/native/src/reminder_request_calendar.cpp index 2fa11c5..115c6fa 100644 --- a/frameworks/ans/native/src/reminder_request_calendar.cpp +++ b/frameworks/ans/native/src/reminder_request_calendar.cpp @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 diff --git a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h index b315ad8..8c6868e 100644 --- a/interfaces/innerkits/ans/native/include/reminder_request_calendar.h +++ b/interfaces/innerkits/ans/native/include/reminder_request_calendar.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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 diff --git a/services/ans/include/reminder_data_manager.h b/services/ans/include/reminder_data_manager.h index 531060b..c1167f1 100644 --- a/services/ans/include/reminder_data_manager.h +++ b/services/ans/include/reminder_data_manager.h @@ -407,7 +407,7 @@ private: /** * Vector used to record all the reminders which has been shown on panel. */ - std::vector> shownReminderVector_; + std::vector> showedReminderVector_; /** * Map used to record all the bundle information of the reminders in system. diff --git a/services/ans/src/reminder_data_manager.cpp b/services/ans/src/reminder_data_manager.cpp index 8d73a2f..18f09d8 100644 --- a/services/ans/src/reminder_data_manager.cpp +++ b/services/ans/src/reminder_data_manager.cpp @@ -176,14 +176,14 @@ void ReminderDataManager::GetValidReminders( void ReminderDataManager::AddToShowedReminders(const sptr &reminder) { std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = shownReminderVector_.begin(); it != shownReminderVector_.end(); ++it) { + 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()); - shownReminderVector_.push_back(reminder); + showedReminderVector_.push_back(reminder); } void ReminderDataManager::OnProcessDiedLocked(const sptr bundleOption) @@ -192,7 +192,7 @@ void ReminderDataManager::OnProcessDiedLocked(const sptrGetUid(); ANSR_LOGI("OnProcessDiedLocked, bundleName=%{public}s, uid=%{public}d", bundleName.c_str(), uid); std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = shownReminderVector_.begin(); it != shownReminderVector_.end(); ++it) { + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { int32_t reminderId = (*it)->GetReminderId(); auto mit = notificationBundleOptionMap_.find(reminderId); if (mit == notificationBundleOptionMap_.end()) { @@ -208,7 +208,7 @@ void ReminderDataManager::OnProcessDiedLocked(const sptrOnClose(false); ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminderId); - shownReminderVector_.erase(it); + showedReminderVector_.erase(it); --it; } } @@ -883,10 +883,10 @@ void ReminderDataManager::StopSoundAndVibration(const sptr &rem void ReminderDataManager::RemoveFromShowedReminders(const sptr &reminder) { std::lock_guard lock(ReminderDataManager::SHOW_MUTEX); - for (auto it = shownReminderVector_.begin(); it != shownReminderVector_.end(); ++it) { + for (auto it = showedReminderVector_.begin(); it != showedReminderVector_.end(); ++it) { if ((*it)->GetReminderId() == reminder->GetReminderId()) { ANSR_LOGD("Containers(shownVector) remove. reminderId=%{public}d", reminder->GetReminderId()); - shownReminderVector_.erase(it); + showedReminderVector_.erase(it); break; } } -- Gitee From 0509681c2e45c386b5bc3fb627f0f2d3987919e0 Mon Sep 17 00:00:00 2001 From: derek Date: Fri, 28 Jan 2022 11:03:32 +0800 Subject: [PATCH 127/131] fix gn format Signed-off-by: derek Change-Id: Id85bfbd120a574c0d0874d76e5612a706a5df5e0 --- frameworks/ans/test/moduletest/BUILD.gn | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/frameworks/ans/test/moduletest/BUILD.gn b/frameworks/ans/test/moduletest/BUILD.gn index 83e278a..1015a68 100644 --- a/frameworks/ans/test/moduletest/BUILD.gn +++ b/frameworks/ans/test/moduletest/BUILD.gn @@ -341,10 +341,10 @@ group("moduletest") { deps = [] deps += [ + ":ReminderAgentJsTest", ":ans_fw_module_test", ":ans_innerkits_module_publish_test", ":ans_innerkits_module_setting_test", ":ans_innerkits_module_slot_test", - ":ReminderAgentJsTest", ] } -- Gitee From 373d53080730c421a7b7b21601a9f09b7723bf94 Mon Sep 17 00:00:00 2001 From: liqiang Date: Fri, 28 Jan 2022 14:09:11 +0800 Subject: [PATCH 128/131] IssueNo:https://gitee.com/openharmony/notification_ans_standard/issues/I4SGWD Description:fix unsubscribe xts bug Sig: SIG_ApplicationFramework Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: liqiang Change-Id: I13053be3e5f73d342b67a5c670e99e289a08089c --- interfaces/kits/napi/ans/src/subscribe.cpp | 62 +++++++++++++++++----- 1 file changed, 48 insertions(+), 14 deletions(-) diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index a0a5b2c..b21cb64 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -826,7 +826,10 @@ napi_value GetNotificationSubscriber( napi_value nOnConsumed = nullptr; napi_get_named_property(env, value, "onConsume", &nOnConsumed); NAPI_CALL(env, napi_typeof(env, nOnConsumed, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnConsumed, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CONSUME, result); } @@ -836,7 +839,10 @@ napi_value GetNotificationSubscriber( napi_value nOnCanceled = nullptr; napi_get_named_property(env, value, "onCancel", &nOnCanceled); NAPI_CALL(env, napi_typeof(env, nOnCanceled, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnCanceled, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CANCEL, result); } @@ -846,7 +852,10 @@ napi_value GetNotificationSubscriber( napi_value nOnUpdate = nullptr; napi_get_named_property(env, value, "onUpdate", &nOnUpdate); NAPI_CALL(env, napi_typeof(env, nOnUpdate, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnUpdate, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, UPDATE, result); } @@ -856,7 +865,10 @@ napi_value GetNotificationSubscriber( napi_value nOnConnected = nullptr; napi_get_named_property(env, value, "onConnect", &nOnConnected); NAPI_CALL(env, napi_typeof(env, nOnConnected, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnConnected, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CONNECTED, result); } @@ -866,7 +878,10 @@ napi_value GetNotificationSubscriber( napi_value nOnDisConnect = nullptr; napi_get_named_property(env, value, "onDisconnect", &nOnDisConnect); NAPI_CALL(env, napi_typeof(env, nOnDisConnect, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnDisConnect, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DIS_CONNECTED, result); } @@ -876,7 +891,10 @@ napi_value GetNotificationSubscriber( napi_value nOnDied = nullptr; napi_get_named_property(env, value, "onDestroy", &nOnDied); NAPI_CALL(env, napi_typeof(env, nOnDied, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnDied, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DIE, result); } @@ -886,7 +904,10 @@ napi_value GetNotificationSubscriber( napi_value nOnDisturbModeChanged = nullptr; napi_get_named_property(env, value, "onDisturbModeChange", &nOnDisturbModeChanged); NAPI_CALL(env, napi_typeof(env, nOnDisturbModeChanged, &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnDisturbModeChanged, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_MODE_CHANGE, result); } @@ -897,7 +918,10 @@ napi_value GetNotificationSubscriber( 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."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type. Function expected."); + return nullptr; + } napi_create_reference(env, nOnDisturbDateChanged, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_DATE_CHANGE, result); } @@ -953,13 +977,19 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[SUBSRIBE_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); + if (argc < 1) { + ANS_LOGE("Wrong number of arguments"); + return nullptr; + } napi_valuetype valuetype = napi_undefined; // argv[0]:subscriber NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. NotificationSubscriber object expected."); + if (valuetype != napi_object) { + ANS_LOGE("Wrong argument type for arg0. NotificationSubscriber object expected."); + return nullptr; + } SubscriberInstancesInfo subscriberInstancesInfo; if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { @@ -985,9 +1015,10 @@ 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[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) && (valuetype != napi_object)) { + ANS_LOGE("Wrong argument type for arg1. Function or NotificationSubscribeInfo object expected."); + return nullptr; + } if (valuetype == napi_function) { napi_create_reference(env, argv[PARAM1], 1, &callback); } else { @@ -1001,7 +1032,10 @@ 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[PARAM2], &valuetype)); - NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); + if (valuetype != napi_function) { + ANS_LOGE("Wrong argument type for arg2. Function expected."); + return nullptr; + } napi_create_reference(env, argv[PARAM2], 1, &callback); } -- Gitee From fadacecac7c098d9f54423c8e88b4ac220cb6388 Mon Sep 17 00:00:00 2001 From: njupthan Date: Fri, 28 Jan 2022 18:20:54 +0000 Subject: [PATCH 129/131] Added distributed notification enabling capability of application config.json Signed-off-by: njupthan --- bundle.json | 2 +- .../core/common/include/ans_const_define.h | 1 + .../test/moduletest/ans_fw_module_test.cpp | 33 ++++++++++ .../moduletest/mock/mock_bundle_mgr_proxy.cpp | 23 ++++--- interfaces/kits/napi/ans/src/subscribe.cpp | 62 +++++-------------- .../include/advanced_notification_service.h | 1 + services/ans/include/bundle_manager_helper.h | 3 + .../ans/src/advanced_notification_service.cpp | 47 ++++++++++++++ services/ans/src/bundle_manager_helper.cpp | 24 +++++++ .../src/notification_subscriber_manager.cpp | 5 +- .../mock/mock_bundle_manager_helper.cpp | 7 +++ .../include/distributed_preferences.h | 1 + .../distributed_preferences_database.h | 1 + .../include/distributed_preferences_info.h | 1 + .../src/distributed_preferences.cpp | 21 +++++++ .../src/distributed_preferences_database.cpp | 23 +++++++ .../src/distributed_preferences_info.cpp | 5 ++ .../src/distributed_screen_status_manager.cpp | 6 +- .../unittest/distributed_preferences_test.cpp | 11 ++++ 19 files changed, 217 insertions(+), 60 deletions(-) diff --git a/bundle.json b/bundle.json index 1c1a84c..397bdfd 100644 --- a/bundle.json +++ b/bundle.json @@ -90,4 +90,4 @@ ] } } -} \ No newline at end of file +} diff --git a/frameworks/ans/core/common/include/ans_const_define.h b/frameworks/ans/core/common/include/ans_const_define.h index 56287bf..9d842d2 100644 --- a/frameworks/ans/core/common/include/ans_const_define.h +++ b/frameworks/ans/core/common/include/ans_const_define.h @@ -50,6 +50,7 @@ const static std::string DEFAULT_TEMPLATE_PATH("/system/etc/NotificationTemplate #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/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index b6ac89e..dd1e6b1 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -38,6 +38,12 @@ #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; @@ -1732,6 +1738,33 @@ HWTEST_F(AnsFWModuleTest, DistributedNotification_Publish_00200, Function | Medi 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 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 ba85231..77116bd 100644 --- a/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp +++ b/frameworks/ans/test/moduletest/mock/mock_bundle_mgr_proxy.cpp @@ -24,17 +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; } @@ -51,8 +58,7 @@ bool BundleMgrProxy::GetBundleInfo( return true; } -bool BundleMgrProxy::GetBundleInfos( - const BundleFlag flag, std::vector &bundleInfos, int32_t userId) +bool BundleMgrProxy::GetBundleInfos(const BundleFlag flag, std::vector &bundleInfos, int32_t userId) { return true; } @@ -205,8 +211,7 @@ bool BundleMgrProxy::UnregisterBundleStatusCallback() return true; } -bool BundleMgrProxy::DumpInfos( - const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) +bool BundleMgrProxy::DumpInfos(const DumpFlag flag, const std::string &bundleName, int32_t userId, std::string &result) { return true; } @@ -264,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; diff --git a/interfaces/kits/napi/ans/src/subscribe.cpp b/interfaces/kits/napi/ans/src/subscribe.cpp index b21cb64..a0a5b2c 100644 --- a/interfaces/kits/napi/ans/src/subscribe.cpp +++ b/interfaces/kits/napi/ans/src/subscribe.cpp @@ -826,10 +826,7 @@ napi_value GetNotificationSubscriber( napi_value nOnConsumed = nullptr; napi_get_named_property(env, value, "onConsume", &nOnConsumed); NAPI_CALL(env, napi_typeof(env, nOnConsumed, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnConsumed, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CONSUME, result); } @@ -839,10 +836,7 @@ napi_value GetNotificationSubscriber( napi_value nOnCanceled = nullptr; napi_get_named_property(env, value, "onCancel", &nOnCanceled); NAPI_CALL(env, napi_typeof(env, nOnCanceled, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnCanceled, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CANCEL, result); } @@ -852,10 +846,7 @@ napi_value GetNotificationSubscriber( napi_value nOnUpdate = nullptr; napi_get_named_property(env, value, "onUpdate", &nOnUpdate); NAPI_CALL(env, napi_typeof(env, nOnUpdate, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnUpdate, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, UPDATE, result); } @@ -865,10 +856,7 @@ napi_value GetNotificationSubscriber( napi_value nOnConnected = nullptr; napi_get_named_property(env, value, "onConnect", &nOnConnected); NAPI_CALL(env, napi_typeof(env, nOnConnected, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnConnected, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, CONNECTED, result); } @@ -878,10 +866,7 @@ napi_value GetNotificationSubscriber( napi_value nOnDisConnect = nullptr; napi_get_named_property(env, value, "onDisconnect", &nOnDisConnect); NAPI_CALL(env, napi_typeof(env, nOnDisConnect, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnDisConnect, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DIS_CONNECTED, result); } @@ -891,10 +876,7 @@ napi_value GetNotificationSubscriber( napi_value nOnDied = nullptr; napi_get_named_property(env, value, "onDestroy", &nOnDied); NAPI_CALL(env, napi_typeof(env, nOnDied, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnDied, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DIE, result); } @@ -904,10 +886,7 @@ napi_value GetNotificationSubscriber( napi_value nOnDisturbModeChanged = nullptr; napi_get_named_property(env, value, "onDisturbModeChange", &nOnDisturbModeChanged); NAPI_CALL(env, napi_typeof(env, nOnDisturbModeChanged, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, nOnDisturbModeChanged, 1, &result); subscriberInfo.subscriber->SetCallbackInfo(env, DISTURB_MODE_CHANGE, result); } @@ -918,10 +897,7 @@ napi_value GetNotificationSubscriber( napi_value nOnDisturbDateChanged = nullptr; napi_get_named_property(env, value, "onDoNotDisturbDateChange", &nOnDisturbDateChanged); NAPI_CALL(env, napi_typeof(env, nOnDisturbDateChanged, &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type. Function expected."); - return nullptr; - } + 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); } @@ -977,19 +953,13 @@ napi_value ParseParameters(const napi_env &env, const napi_callback_info &info, napi_value argv[SUBSRIBE_MAX_PARA] = {nullptr}; napi_value thisVar = nullptr; NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, NULL)); - if (argc < 1) { - ANS_LOGE("Wrong number of arguments"); - return nullptr; - } + NAPI_ASSERT(env, argc >= 1, "Wrong number of arguments"); napi_valuetype valuetype = napi_undefined; // argv[0]:subscriber NAPI_CALL(env, napi_typeof(env, argv[PARAM0], &valuetype)); - if (valuetype != napi_object) { - ANS_LOGE("Wrong argument type for arg0. NotificationSubscriber object expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_object, "Wrong argument type for arg0. NotificationSubscriber object expected."); SubscriberInstancesInfo subscriberInstancesInfo; if (!HasNotificationSubscriber(env, argv[PARAM0], subscriberInstancesInfo)) { @@ -1015,10 +985,9 @@ 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[PARAM1], &valuetype)); - if ((valuetype != napi_function) && (valuetype != napi_object)) { - ANS_LOGE("Wrong argument type for arg1. Function or NotificationSubscribeInfo object expected."); - return nullptr; - } + 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[PARAM1], 1, &callback); } else { @@ -1032,10 +1001,7 @@ 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[PARAM2], &valuetype)); - if (valuetype != napi_function) { - ANS_LOGE("Wrong argument type for arg2. Function expected."); - return nullptr; - } + NAPI_ASSERT(env, valuetype == napi_function, "Wrong argument type. Function expected."); napi_create_reference(env, argv[PARAM2], 1, &callback); } diff --git a/services/ans/include/advanced_notification_service.h b/services/ans/include/advanced_notification_service.h index b4b7abe..95cc804 100644 --- a/services/ans/include/advanced_notification_service.h +++ b/services/ans/include/advanced_notification_service.h @@ -194,6 +194,7 @@ private: 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: diff --git a/services/ans/include/bundle_manager_helper.h b/services/ans/include/bundle_manager_helper.h index f753d91..5bd43d1 100644 --- a/services/ans/include/bundle_manager_helper.h +++ b/services/ans/include/bundle_manager_helper.h @@ -34,6 +34,9 @@ public: std::string GetBundleNameByUid(int uid); bool IsSystemApp(int uid); int GetDefaultUidByBundleName(const std::string &bundle); +#ifdef DISTRIBUTED_NOTIFICATION_SUPPORTED + bool GetDistributedNotificationEnabled(const std::string &bundleName, const int userId); +#endif private: void Connect(); diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index facee75..dd6a7b6 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1839,6 +1839,7 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrDeleteDistributedBundleInfo(bundleOption); std::vector keys = GetLocalNotificationKeys(bundleOption); #else std::vector keys = GetNotificationKeys(bundleOption); @@ -1866,12 +1867,14 @@ void AdvancedNotificationService::OnBundleRemoved(const sptrSetLocalScreenStatus(true); } void AdvancedNotificationService::OnScreenOff() { + ANS_LOGI("%{public}s", __FUNCTION__); localScreenOn_ = false; DistributedScreenStatusManager::GetInstance()->SetLocalScreenStatus(false); } @@ -2445,6 +2448,13 @@ ErrCode AdvancedNotificationService::EnableDistributedByBundle( return ERR_ANS_PERMISSION_DENIED; } + 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); @@ -2468,6 +2478,13 @@ ErrCode AdvancedNotificationService::EnableDistributedSelf(const bool enabled) 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); })); @@ -2491,6 +2508,14 @@ ErrCode AdvancedNotificationService::IsDistributedEnableByBundle( return ERR_ANS_PERMISSION_DENIED; } + bool appInfoEnable = true; + GetDistributedEnableInApplicationInfo(bundleOption, 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(bundleOption, enabled); @@ -2598,6 +2623,12 @@ std::string AdvancedNotificationService::GetNotificationDeviceId(const std::stri 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; } @@ -2796,6 +2827,22 @@ void AdvancedNotificationService::OnDistributedDelete( } })); } + +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( diff --git a/services/ans/src/bundle_manager_helper.cpp b/services/ans/src/bundle_manager_helper.cpp index f57a452..ff21b58 100644 --- a/services/ans/src/bundle_manager_helper.cpp +++ b/services/ans/src/bundle_manager_helper.cpp @@ -19,6 +19,9 @@ #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() @@ -117,5 +120,26 @@ 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/notification_subscriber_manager.cpp b/services/ans/src/notification_subscriber_manager.cpp index 9c2dcda..0307d32 100644 --- a/services/ans/src/notification_subscriber_manager.cpp +++ b/services/ans/src/notification_subscriber_manager.cpp @@ -281,7 +281,9 @@ ErrCode NotificationSubscriberManager::RemoveSubscriberInner( 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()) && @@ -297,9 +299,10 @@ 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()) && (notification->GetUserId() == record->userId || notification->GetUserId() == SUBSCRIBE_USER_ALL)) { 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 f124d50..53a462d 100644 --- a/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp +++ b/services/ans/test/unittest/mock/mock_bundle_manager_helper.cpp @@ -51,5 +51,12 @@ 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/distributed/include/distributed_preferences.h b/services/distributed/include/distributed_preferences.h index c86dbc2..44d6d89 100644 --- a/services/distributed/include/distributed_preferences.h +++ b/services/distributed/include/distributed_preferences.h @@ -35,6 +35,7 @@ public: 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: diff --git a/services/distributed/include/distributed_preferences_database.h b/services/distributed/include/distributed_preferences_database.h index 74f6c21..92b80d1 100644 --- a/services/distributed/include/distributed_preferences_database.h +++ b/services/distributed/include/distributed_preferences_database.h @@ -39,6 +39,7 @@ public: 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: diff --git a/services/distributed/include/distributed_preferences_info.h b/services/distributed/include/distributed_preferences_info.h index 860e088..840d3c9 100644 --- a/services/distributed/include/distributed_preferences_info.h +++ b/services/distributed/include/distributed_preferences_info.h @@ -29,6 +29,7 @@ public: 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; diff --git a/services/distributed/src/distributed_preferences.cpp b/services/distributed/src/distributed_preferences.cpp index 767ee90..551fb0f 100644 --- a/services/distributed/src/distributed_preferences.cpp +++ b/services/distributed/src/distributed_preferences.cpp @@ -179,6 +179,27 @@ ErrCode DistributedPreferences::GetDistributedBundleEnable( 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()) { diff --git a/services/distributed/src/distributed_preferences_database.cpp b/services/distributed/src/distributed_preferences_database.cpp index 9da4c0a..535bcda 100644 --- a/services/distributed/src/distributed_preferences_database.cpp +++ b/services/distributed/src/distributed_preferences_database.cpp @@ -160,6 +160,29 @@ bool DistributedPreferencesDatabase::GetEntriesFromDistributedDB( 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_); diff --git a/services/distributed/src/distributed_preferences_info.cpp b/services/distributed/src/distributed_preferences_info.cpp index 11f2d28..1e43052 100644 --- a/services/distributed/src/distributed_preferences_info.cpp +++ b/services/distributed/src/distributed_preferences_info.cpp @@ -50,5 +50,10 @@ bool DistributedPreferencesInfo::GetDistributedBundleEnable(const std::string &b 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 index 0ef6ee2..a1dddb7 100644 --- a/services/distributed/src/distributed_screen_status_manager.cpp +++ b/services/distributed/src/distributed_screen_status_manager.cpp @@ -183,9 +183,11 @@ ErrCode DistributedScreenStatusManager::CheckRemoteDevicesIsUsing(bool &isUsing) 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 |= entry.value.ToString() == SCREEN_STATUS_VALUE_ON; + isUsing = isUsing || (entry.value.ToString() == SCREEN_STATUS_VALUE_ON); break; } } @@ -194,12 +196,14 @@ ErrCode DistributedScreenStatusManager::CheckRemoteDevicesIsUsing(bool &isUsing) } } + 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; diff --git a/services/distributed/test/unittest/distributed_preferences_test.cpp b/services/distributed/test/unittest/distributed_preferences_test.cpp index 05a4ab7..1223d2b 100644 --- a/services/distributed/test/unittest/distributed_preferences_test.cpp +++ b/services/distributed/test/unittest/distributed_preferences_test.cpp @@ -101,5 +101,16 @@ HWTEST_F(DistributedPreferencesTest, ClearDataInRestoreFactorySettings_00100, Fu { EXPECT_EQ(distributedPreferences_->ClearDataInRestoreFactorySettings(), ERR_OK); } + +/** + * @tc.name : DistributedPreferences_DeleteDistributedBundleInfo_00100 + * @tc.number : DeleteDistributedBundleInfo_00100 + * @tc.desc : Clear bundle info with distributed notification enable state. + */ +HWTEST_F(DistributedPreferencesTest, DeleteDistributedBundleInfo_00100, Function | SmallTest | Level1) +{ + sptr bundleOption = new NotificationBundleOption("", 783); + EXPECT_EQ(distributedPreferences_->DeleteDistributedBundleInfo(bundleOption), ERR_OK); +} } // namespace Notification } // namespace OHOS \ No newline at end of file -- Gitee From d9dc2ef4dd2e13735a5fda23a46a1bfee5ebd9a9 Mon Sep 17 00:00:00 2001 From: liqiang Date: Sat, 29 Jan 2022 11:31:16 +0800 Subject: [PATCH 130/131] IssueNo:https://gitee.com/openharmony/notification_ans_standard/issues/I4SIQ5 Description:fix enableDistributedSelf api error bug Sig: SIG_ApplicationFramework Feature or Bugfix:Bugfix Binary Source:No Signed-off-by: liqiang Change-Id: Ib7c956dff68e6a211118071fadd1151b3bfc2616 --- .../ans/src/advanced_notification_service.cpp | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index dd6a7b6..cb95e52 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -2448,8 +2448,13 @@ ErrCode AdvancedNotificationService::EnableDistributedByBundle( return ERR_ANS_PERMISSION_DENIED; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + bool appInfoEnable = true; - GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable); + GetDistributedEnableInApplicationInfo(bundle, appInfoEnable); if (!appInfoEnable) { ANS_LOGD("Get from bms is %{public}d", appInfoEnable); return ERR_ANS_PERMISSION_DENIED; @@ -2457,7 +2462,7 @@ ErrCode AdvancedNotificationService::EnableDistributedByBundle( ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundleOption, enabled); + result = DistributedPreferences::GetInstance()->SetDistributedBundleEnable(bundle, enabled); if (result != ERR_OK) { result = ERR_OK; enabled = false; @@ -2508,8 +2513,13 @@ ErrCode AdvancedNotificationService::IsDistributedEnableByBundle( return ERR_ANS_PERMISSION_DENIED; } + sptr bundle = GenerateValidBundleOption(bundleOption); + if (bundle == nullptr) { + return ERR_ANS_INVALID_BUNDLE; + } + bool appInfoEnable = true; - GetDistributedEnableInApplicationInfo(bundleOption, appInfoEnable); + GetDistributedEnableInApplicationInfo(bundle, appInfoEnable); if (!appInfoEnable) { ANS_LOGD("Get from bms is %{public}d", appInfoEnable); enabled = appInfoEnable; @@ -2518,7 +2528,7 @@ ErrCode AdvancedNotificationService::IsDistributedEnableByBundle( ErrCode result = ERR_OK; handler_->PostSyncTask(std::bind([&]() { - result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundleOption, enabled); + result = DistributedPreferences::GetInstance()->GetDistributedBundleEnable(bundle, enabled); if (result != ERR_OK) { result = ERR_OK; enabled = false; -- Gitee From 17128836966bc5b896f46e6033bd894b1ba66a77 Mon Sep 17 00:00:00 2001 From: zero-cyc Date: Mon, 7 Feb 2022 14:57:21 +0800 Subject: [PATCH 131/131] chenlien@huawei.com Signed-off-by: zero-cyc Change-Id: Iabe47fea74be5549a3cb14433e326c74ad407355 --- .../core/common/include/ans_inner_errors.h | 1 + frameworks/ans/native/src/notification.cpp | 8 +++++ .../test/moduletest/ans_fw_module_test.cpp | 2 +- .../ans/native/include/notification.h | 6 ++++ .../ans/src/advanced_notification_service.cpp | 30 ++++++++----------- 5 files changed, 29 insertions(+), 18 deletions(-) diff --git a/frameworks/ans/core/common/include/ans_inner_errors.h b/frameworks/ans/core/common/include/ans_inner_errors.h index c205fea..d8a4581 100644 --- a/frameworks/ans/core/common/include/ans_inner_errors.h +++ b/frameworks/ans/core/common/include/ans_inner_errors.h @@ -72,6 +72,7 @@ enum ErrorCode : uint32_t { 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/native/src/notification.cpp b/frameworks/ans/native/src/notification.cpp index 4b8e261..b94a72e 100644 --- a/frameworks/ans/native/src/notification.cpp +++ b/frameworks/ans/native/src/notification.cpp @@ -161,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_; diff --git a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp index dd1e6b1..ec094df 100644 --- a/frameworks/ans/test/moduletest/ans_fw_module_test.cpp +++ b/frameworks/ans/test/moduletest/ans_fw_module_test.cpp @@ -2451,7 +2451,7 @@ HWTEST_F(AnsFWModuleTest, ANS_Interface_MT_PulbishContinuousTask_07600, Function EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetLabel().c_str(), NOTIFICATION_LABEL_0); EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetId(), 0); - EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->IsRemoveAllowed(), false); + EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->IsUnremovable(), true); EXPECT_EQ(eventParser.GetOnConsumedReq()[0]->GetSourceType(), NotificationConstant::SourceType::TYPE_CONTINUOUS); EXPECT_EQ(NotificationHelper::UnSubscribeNotification(subscriber), ERR_OK); diff --git a/interfaces/innerkits/ans/native/include/notification.h b/interfaces/innerkits/ans/native/include/notification.h index a12b7f4..a187b95 100644 --- a/interfaces/innerkits/ans/native/include/notification.h +++ b/interfaces/innerkits/ans/native/include/notification.h @@ -164,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 * diff --git a/services/ans/src/advanced_notification_service.cpp b/services/ans/src/advanced_notification_service.cpp index cb95e52..11d9f81 100644 --- a/services/ans/src/advanced_notification_service.cpp +++ b/services/ans/src/advanced_notification_service.cpp @@ -1108,9 +1108,6 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { - if (!record->notification->IsRemoveAllowed()) { - continue; - } if ((record->bundleOption->GetBundleName() == bundleOption->GetBundleName()) && (record->bundleOption->GetUid() == bundleOption->GetUid()) && (record->notification->GetLabel() == label) && @@ -1119,8 +1116,8 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList(const sptrdeviceId.empty() #endif ) { - if (!isCancel && record->request->IsUnremovable()) { - return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + if (!isCancel && !record->notification->IsRemoveAllowed()) { + return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; // delete or delete all, call the function @@ -1139,12 +1136,9 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationList( const std::string &key, sptr ¬ification, bool isCancel) { for (auto record : notificationList_) { - if (!record->notification->IsRemoveAllowed() && isCancel) { - continue; - } if (record->notification->GetKey() == key) { - if (!isCancel && record->request->IsUnremovable()) { - return ERR_ANS_NOTIFICATION_IS_UNREMOVABLE; + if (!isCancel && !record->notification->IsRemoveAllowed()) { + return ERR_ANS_NOTIFICATION_IS_UNALLOWED_REMOVEALLOWED; } notification = record->notification; // delete or delete all, call the function @@ -1163,10 +1157,10 @@ ErrCode AdvancedNotificationService::RemoveFromNotificationListForDeleteAll( const std::string &key, sptr ¬ification) { for (auto record : notificationList_) { - if (!record->notification->IsRemoveAllowed()) { - continue; - } 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; } @@ -1509,14 +1503,13 @@ ErrCode AdvancedNotificationService::PublishContinuousTaskNotification(const spt 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); - record->notification->SetRemoveAllowed(false); } handler_->PostSyncTask(std::bind([&]() { @@ -1969,8 +1962,8 @@ ErrCode AdvancedNotificationService::RemoveNotification( (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 @@ -2152,6 +2145,9 @@ ErrCode AdvancedNotificationService::RemoveGroupByBundle( 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 -- Gitee